← Demos
Web Pages · Demos

Campus Compass

Campus Compass helps Kentucky college students see when rent and bills could leave them short before their next paycheck or aid refund. It lets them test purchases and spending changes against a semester cash-flow forecast.

by Morgan Powers Nov 19, 2026 17 views 771.6 KB
Sandbox · campus-compass · no access to your account
View source — the whole page is this one file
<!-- Copyright (c) 2026 Morgan Powers. Released under the MIT License. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob:; connect-src 'none'; form-action 'none'; base-uri 'none'">
<meta name="description" content="Campus Compass: a private, offline money plan for Kentucky college students.">
<meta name="theme-color" content="#145e4d">
<title>Campus Compass · Your money, made clear</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2040%2040%22%3E%3Crect%20width%3D%2240%22%20height%3D%2240%22%20rx%3D%2212%22%20fill%3D%22%23145e4d%22%2F%3E%3Cg%20transform%3D%22rotate(38%2020%2020)%22%3E%3Cpath%20d%3D%22M20%207.5l4.6%2012.5h-9.2z%22%20fill%3D%22%23f2c14e%22%2F%3E%3Cpath%20d%3D%22M20%2032.5L15.4%2020h9.2z%22%20fill%3D%22%23fff%22%2F%3E%3C%2Fg%3E%3Ccircle%20cx%3D%2220%22%20cy%3D%2220%22%20r%3D%222.1%22%20fill%3D%22%23145e4d%22%2F%3E%3C%2Fsvg%3E">
<style>
:root{
  --bg:#f3f6f1;--card:#fff;--ink:#12272a;--ink2:#2c4540;--muted:#5d6f6a;--line:#dfe8e1;--line2:#edf2ee;
  --brand:#145e4d;--brand2:#1d7a63;--brand-d:#0e4639;--mint:#d8f3dc;--lime:#e8f4c8;--amber:#9a6208;--amber-bg:#fff4dc;--amber-line:#f0d9a0;
  --red:#b23b2f;--red-bg:#fdeeeb;--good:#17794f;--good-bg:#e4f6ec;--blue:#2c6f8d;--blue-bg:#e6f1f6;--soft-bg:#eef3ef;
  --shadow:0 1px 2px rgba(18,39,42,.04),0 10px 30px rgba(18,39,42,.07);--r:18px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI","Inter",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}
button,input,select,textarea{font:inherit;color:inherit}
button{cursor:pointer;border:0;background:none;padding:0}
button:disabled{opacity:.5;cursor:not-allowed}
h1,h2,h3,h4,p,ul,ol,dl,dd{margin:0}
ul,ol{padding:0;list-style:none}
:focus-visible{outline:3px solid rgba(29,122,99,.45);outline-offset:2px;border-radius:8px}
h1:focus{outline:none}
.skip{position:absolute;left:-999px;top:8px;background:#fff;padding:8px 12px;border-radius:8px;z-index:50}.skip:focus{left:8px}
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.ico{flex:none;vertical-align:middle}
.small{font-size:13px}.hint{font-size:13.5px;color:var(--muted);margin-top:6px}
[hidden]{display:none!important}

/* ---------- page frame ---------- */
.page{max-width:980px;margin:0 auto;padding:18px clamp(14px,3vw,28px) 56px}
.top{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;padding:6px 0 14px}
.brand{display:flex;align-items:center;gap:10px}
.brand-text{display:flex;flex-direction:column;line-height:1.05}
.brand-name{font-weight:800;font-size:19px;letter-spacing:-.4px}.brand-name b{color:var(--brand2)}
.brand-tag{font-size:10px;letter-spacing:1.2px;text-transform:uppercase;color:var(--muted);font-weight:700;margin-top:3px}
.top-right{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.privacy-chip{display:inline-flex;align-items:center;gap:6px;background:#e8f2ea;color:#245c49;border-radius:99px;padding:6px 12px;font-size:12.5px;font-weight:650}
.erase-confirm{display:inline-flex;align-items:center;gap:8px;flex-wrap:wrap}
.file-btn{position:relative;gap:6px}
.dot-unsaved{width:8px;height:8px;border-radius:50%;background:#d48a0b;box-shadow:0 0 0 2px #fff;margin-left:2px}
.save-state{font-size:12.5px;font-weight:650;color:var(--good)}.save-state.unsaved{color:var(--amber)}
.confirm-open .co-body{display:grid;gap:6px;flex:1;min-width:0}
.foot-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px}
.license{display:grid;gap:8px}.license p{overflow-wrap:anywhere}
@media (max-width:899px){.privacy-chip{display:none}}
@media (max-width:699px){.save-state{display:none}.top-right{gap:6px;width:100%}.top-right .btn.small{padding:7px 10px}}
@media (max-width:419px){.file-btn .ico{display:none}.top-right .btn.small{padding:7px 9px;font-size:13px}}
.main{display:block}
.foot{margin-top:34px;padding-top:18px;border-top:1px solid var(--line);font-size:12.5px;color:var(--muted);display:grid;gap:8px;max-width:760px}
.stack{display:grid;gap:16px}

/* ---------- progress ---------- */
.progress{margin:0 0 18px}
.progress ol{display:flex;gap:6px;flex-wrap:wrap}
.progress li{display:flex;align-items:center;gap:8px;flex:1 1 120px;min-width:0;padding:8px 10px;border-radius:12px;background:#e9efe9;color:#51635d;font-size:13px;font-weight:650}
.progress .dot{width:22px;height:22px;border-radius:50%;background:#fff;display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;flex:none}
.progress li.now{background:var(--brand);color:#fff}.progress li.now .dot{background:#fff;color:var(--brand)}
.progress li.done{background:var(--mint);color:var(--brand-d)}.progress li.done .dot{background:var(--brand2);color:#fff}
.progress .lbl{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}

/* ---------- cards ---------- */
.card{background:var(--card);border-radius:var(--r);box-shadow:var(--shadow);padding:clamp(18px,3vw,28px);display:grid;gap:14px;align-content:start}
.card.narrow{max-width:640px;margin:0 auto;width:100%}
.card.narrow-lg{max-width:820px;margin:0 auto;width:100%}
.stack>.card{width:100%}
.card-title{font-size:19px;letter-spacing:-.2px}
.card-sub{color:var(--muted);margin-top:-6px}
h1{font-size:clamp(25px,4.6vw,34px);line-height:1.15;letter-spacing:-.6px}
h2{font-size:20px;letter-spacing:-.2px}
h3{font-size:15px}
.eyebrow{font-size:12px;letter-spacing:1.3px;text-transform:uppercase;font-weight:800;color:var(--brand2)}
.lede{font-size:17px;color:var(--ink2)}
.sub{color:var(--muted)}

/* ---------- buttons ---------- */
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;border-radius:12px;padding:11px 18px;font-weight:700;transition:transform .08s,box-shadow .15s,background .15s;line-height:1.2}
.btn.primary{background:var(--brand);color:#fff;box-shadow:0 6px 16px rgba(20,94,77,.25)}.btn.primary:hover:not(:disabled){background:var(--brand-d)}
.btn.ghost{background:#eef3ef;color:var(--ink2)}.btn.ghost:hover:not(:disabled){background:#e2ebe4}
.btn.danger{background:var(--red);color:#fff}
.btn.big{padding:14px 22px;font-size:17px}
.btn.small{padding:7px 12px;font-size:13.5px;border-radius:10px}
.btn:active:not(:disabled){transform:translateY(1px)}
.actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;justify-content:flex-end;margin-top:6px}
.actions .btn.ghost:first-child{margin-right:auto}

/* ---------- forms ---------- */
.field{display:grid;gap:5px}
.field label{font-weight:650;font-size:14.5px}
.field.inline{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.field.inline label{min-width:120px}
input[type=text],input[type=date],input:not([type]),select,textarea{width:100%;border:1.5px solid #cdd9d1;border-radius:12px;padding:11px 13px;background:#fff;min-height:46px}
input:focus,select:focus,textarea:focus{border-color:var(--brand2);outline:3px solid rgba(29,122,99,.25);outline-offset:0}
textarea{resize:vertical;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:13px}
.money{display:flex;align-items:center;border:1.5px solid #cdd9d1;border-radius:12px;background:#fff;padding-left:13px}
.money:focus-within{border-color:var(--brand2);outline:3px solid rgba(29,122,99,.25)}
.money .cur{color:var(--muted);font-weight:700}
.money input{border:0;outline:0!important;padding-left:6px;min-height:44px}
.two{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px}
.selects{display:grid;gap:10px;margin-top:8px}
.error{background:var(--red-bg);color:var(--red);border-radius:10px;padding:10px 12px;font-weight:600;font-size:14px}
.chips{display:flex;gap:8px;flex-wrap:wrap}
.chip{border:1.5px solid #cdd9d1;border-radius:99px;padding:9px 15px;background:#fff;font-weight:650;font-size:14.5px}
.chip:hover{border-color:var(--brand2)}.chip.on{background:var(--brand);color:#fff;border-color:var(--brand)}
.confirm{display:flex;align-items:flex-start;gap:10px;background:var(--soft-bg);border-radius:12px;padding:12px 14px;font-weight:650;cursor:pointer}
.confirm input,.opt input,.found-row input,.use input{width:20px;height:20px;min-height:0;flex:none;margin-top:2px;accent-color:var(--brand)}
details>summary{cursor:pointer;font-weight:650;color:var(--brand2);padding:6px 0}
.paste textarea{margin:8px 0}

/* ---------- notes and badges ---------- */
.note{display:flex;gap:10px;align-items:center;flex-wrap:wrap;border-radius:12px;padding:11px 14px;font-size:14.5px;margin-bottom:12px}
.note .ico{flex:none}
.note.blue{background:var(--blue-bg);color:#1f5873}.note.amber{background:var(--amber-bg);color:#6e4606}.note.good{background:var(--good-bg);color:#0f5a39}
.fact{display:flex;gap:10px;align-items:flex-start;background:var(--soft-bg);padding:12px 14px;border-radius:12px;font-size:14px;color:var(--ink2)}
.badge{display:inline-flex;align-items:center;border-radius:99px;padding:3px 10px;font-size:12px;font-weight:750;background:var(--soft-bg);color:#46605a;white-space:nowrap}
.badge.good{background:var(--good-bg);color:var(--good)}.badge.blue{background:var(--blue-bg);color:var(--blue)}.badge.amber{background:var(--amber-bg);color:var(--amber)}.badge.warn{background:var(--red-bg);color:var(--red)}.badge.soft{background:var(--soft-bg)}
.neg{color:var(--ink)}.pos{color:var(--good)}

/* ---------- welcome ---------- */
.welcome{display:grid;gap:22px}
.hero{padding:clamp(8px,2vw,22px) 0 4px;display:grid;gap:12px;max-width:760px}
.hero h1{font-size:clamp(30px,6vw,46px);letter-spacing:-1.2px}
.welcome .edu-notice{font-size:17px;line-height:1.5;color:var(--ink)}
.dc{max-width:420px}
.dc-plot{position:relative;height:190px;border-left:2px solid var(--line);margin-bottom:4px}
.dc-line{position:absolute;left:0;right:0;height:0;border-top:2px solid var(--ink2)}
.dc-line.cushion{border-top:2px dashed var(--amber)}
.dc-tag{position:absolute;right:0;font-size:12px;font-weight:700;line-height:18px;color:var(--ink2);white-space:nowrap}
.dc-tag.cushion{color:var(--amber)}
.dc-bar{position:absolute;width:26%;border-radius:4px}
.dc-bar.before{background:var(--red)}.dc-bar.after{background:var(--good)}
.dc-val{position:absolute;width:26%;text-align:center;font-size:15px;line-height:20px;white-space:nowrap}
.dc-val.before{color:var(--red)}.dc-val.after{color:var(--good)}
.dc-cats{position:relative;height:56px}
.dc-cat{position:absolute;width:30%;font-size:12px;line-height:16px;color:var(--ink2)}.dc-cat>span{display:block}
.nw{white-space:nowrap}
.choices{display:grid;grid-template-columns:1fr;gap:10px}
.choice{display:flex;align-items:flex-start;gap:12px;width:100%;min-width:0;text-align:left;background:#fff;border:2px solid transparent;border-radius:14px;padding:14px 16px;box-shadow:var(--shadow);transition:border-color .15s}
.choice:hover{border-color:var(--brand2)}
.choice.main{background:linear-gradient(160deg,#145e4d,#1d7a63);color:#fff}
.choice.main .cd{color:#dff3e9}
.ci{width:32px;height:32px;border-radius:10px;background:var(--mint);color:var(--brand);display:inline-flex;align-items:center;justify-content:center;flex:none}
.choice.main .ci{background:rgba(255,255,255,.18);color:#fff}
.ct{display:grid;gap:2px;min-width:0;flex:1}.ch{font-size:16.5px;font-weight:800;letter-spacing:-.2px;line-height:1.25}.cd{color:var(--muted);font-size:14px;line-height:1.4}.ch,.cd{overflow-wrap:anywhere}
@media (min-width:700px){.choices{grid-template-columns:1fr 1fr;gap:14px}.choice{padding:24px 22px;gap:14px}.ci{width:38px;height:38px}.ct{gap:4px}.ch{font-size:18px}.cd{font-size:15px}}
.samples{display:grid;gap:10px}
.persona-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:12px;align-items:start}
@media (min-width:700px){.persona-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
.persona-card{display:grid;gap:12px;align-content:start;background:#fff;border-radius:16px;padding:16px;box-shadow:var(--shadow);border:2px solid transparent;transition:border-color .15s}
.persona-card:hover{border-color:var(--brand2)}
.pc-top{display:flex;gap:12px;align-items:center;text-align:left;min-width:0}
.samples-about{margin:-6px 0 -4px}
.samples-about summary{font-size:14.5px;padding:9px 0;width:max-content;max-width:100%}
.samples-about .sa-text{margin:2px 0 4px;font-size:14px;color:var(--ink2);line-height:1.5}
.pc-actions{display:flex;flex-wrap:wrap;gap:8px}
.pc-actions .btn{max-width:100%;height:auto;white-space:normal}
.pc-actions .persona{display:inline-flex;align-items:center;border-radius:10px;padding:7px 12px;font-size:13.5px;font-weight:700;background:#eef3ef;color:var(--ink2)}
.pc-actions .persona:hover{background:#e2ebe4}
.diffs{display:grid;gap:8px;margin-top:4px}
.diffs li{display:grid;gap:1px;padding:10px 14px;border-left:4px solid var(--brand2);background:#fff;border-radius:10px;box-shadow:0 1px 2px rgba(18,39,42,.05)}
.diffs b{font-size:15.5px}.diffs span{font-size:14px;color:var(--muted)}
.open-line{display:flex;flex-wrap:wrap;align-items:center;gap:10px;color:var(--muted);font-size:14.5px;margin-top:-6px}
.avatar{width:42px;height:42px;border-radius:50%;background:var(--lime);color:var(--brand-d);display:inline-flex;align-items:center;justify-content:center;font-weight:800;font-size:18px;flex:none}
.p-name{font-weight:800;font-size:17px;margin:0;min-width:0;overflow-wrap:anywhere}
.promises{display:grid;gap:8px;max-width:760px}
.promises li{display:flex;gap:10px;align-items:flex-start;color:var(--ink2);font-size:14.5px}.promises .ico{color:var(--brand2);margin-top:3px}

/* ---------- import / review ---------- */
.drop{display:grid;gap:6px;justify-items:center;text-align:center;border:2.5px dashed #b8cbbf;border-radius:var(--r);padding:30px 18px;background:#f8fbf8;cursor:pointer;color:var(--brand)}
.drop:hover,.drop.over{background:var(--mint);border-color:var(--brand2)}
.drop .dt{font-weight:800;font-size:18px;color:var(--ink)}.drop .dd{color:var(--muted);font-size:14px}
.tbl{width:100%;border-collapse:collapse;font-size:14px}
.tbl th{text-align:left;font-size:12px;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);padding:6px 8px;border-bottom:1.5px solid var(--line)}
.tbl td{padding:8px;border-bottom:1px solid var(--line2);overflow-wrap:anywhere}.r{text-align:right}.tbl .r{white-space:nowrap}
.facts{display:grid;gap:5px;margin-top:8px}.facts li{padding-left:2px}
.mini{display:grid;gap:4px}.mini li{display:flex;justify-content:space-between;gap:10px;font-size:14px;border-bottom:1px solid var(--line2);padding:4px 0}.mini span{overflow-wrap:anywhere}
.row-q{border:1.5px solid var(--line);border-radius:14px;padding:12px 14px;margin:0 0 12px;min-width:0}
.row-q legend{padding:0 6px;display:flex;gap:10px;flex-wrap:wrap;align-items:baseline;max-width:100%}.row-q legend b{overflow-wrap:anywhere}.rd{font-size:12.5px;color:var(--muted)}
.row-q .q{margin:6px 0 8px}
.opts{display:grid;gap:6px}
.opt{display:flex;align-items:center;gap:10px;padding:9px 12px;border-radius:10px;background:var(--soft-bg);cursor:pointer;font-weight:600;font-size:14.5px}
.catsel{margin-top:8px;max-width:260px}
.found-list{display:grid;gap:8px}
.found-row{display:flex;gap:12px;align-items:flex-start;border:1.5px solid var(--line);border-radius:14px;padding:12px 14px;cursor:pointer}
.found-row:hover{border-color:var(--brand2)}
.fr-main{display:grid;flex:1;min-width:0}.fr-name{font-weight:750;overflow-wrap:anywhere}.fr-why{font-size:13px;color:var(--muted)}
.fr-amt{display:grid;justify-items:end;gap:4px;white-space:nowrap}

/* ---------- lists ---------- */
.items{display:grid;gap:8px}
.item{display:flex;justify-content:space-between;gap:10px;align-items:center;padding:10px 12px;background:var(--soft-bg);border-radius:12px}
.i-main{display:grid;min-width:0}.i-main b{overflow-wrap:anywhere}.i-sub{font-size:13px;color:var(--muted)}
.type-row{margin-bottom:2px}
.form{display:grid;gap:12px}
.irr{display:grid;gap:10px}
.ask{border-left:5px solid var(--amber)}
.rent-fields{display:grid;gap:10px;margin-top:10px}

/* optional */
.opt-list{display:grid;gap:10px}
.opt-card{border:1.5px solid var(--line);border-radius:14px;overflow:hidden}
.opt-card.done{background:#fafcfa}
.opt-head{width:100%;display:flex;justify-content:space-between;align-items:center;gap:12px;padding:14px 16px;text-align:left}
.opt-head:hover{background:#f6faf6}
.oh-main{display:grid;gap:2px;min-width:0}.oh-title{font-weight:750}.oh-sub{font-size:13px;color:var(--muted)}
.opt-body{padding:4px 16px 16px;border-top:1px solid var(--line2);display:grid;gap:10px}

/* budgets */
.brows{display:grid;gap:12px}
.brow{border:1.5px solid var(--line);border-radius:14px;padding:14px 16px;display:grid;gap:8px}
.brow.approved{border-color:#b5dfc6;background:#f6fcf8}
.b-head{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.b-name{font-weight:800;font-size:17px}.b-kind{font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.8px;font-weight:700}
.b-head .badge{margin-left:auto}
.b-meta{display:flex;gap:6px;flex-wrap:wrap}
.b-why{font-size:13.5px;color:var(--muted)}
.b-input{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.b-input .cur{font-weight:700;color:var(--muted)}
.b-input input[type=text]{width:130px}
.per{color:var(--muted);font-size:14px}
.use{display:inline-flex;align-items:center;gap:8px;margin-left:auto;font-weight:700;cursor:pointer}
.fit{font-weight:650;font-size:14.5px;padding:10px 12px;border-radius:10px;background:var(--soft-bg)}.fit.good{background:var(--good-bg);color:#0f5a39}.fit.bad{background:var(--red-bg);color:var(--red)}

/* ---------- plan ---------- */
.plan .card-sub{margin-bottom:8px}
.plan-settings .i-sub,.plan-inputs .i-sub{display:block}
.plan-disclosure-body{display:grid;gap:12px;margin-top:10px}
.plan-subh{font-size:16px;margin-top:4px}
.plan .stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px}
.plan .sstat{background:var(--soft-bg);border-radius:12px;padding:12px;display:grid;gap:2px}
.plan .sstat .k-l{font-size:12.5px;color:var(--muted);font-weight:650}
.plan .sstat .k-v{font-size:20px;font-weight:800}
.plan .sstat .k-h{font-size:12px;color:var(--muted)}
.plan .sstat.neg .k-v{color:var(--red)}
.plan .amber-text{color:#8a5a00;font-weight:650}
.plan .offers{display:grid;gap:10px}
.conf{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:14px}
.cf{border-radius:14px;padding:14px;background:var(--soft-bg);display:grid;gap:8px;align-content:start}
.cf.solid{background:var(--good-bg)}.cf.est{background:var(--amber-bg)}.cf.imp{background:var(--blue-bg)}
.cf ul{display:grid;gap:8px}.cf li{font-size:14px;display:grid;gap:6px;justify-items:start}
.layers{display:grid;grid-template-columns:repeat(auto-fit,minmax(165px,1fr));gap:12px}
.layer{border-radius:14px;padding:14px;border:1.5px solid var(--line);display:grid;gap:6px;align-content:start}
.layer h3{font-size:16px}.kicker{font-size:11.5px;text-transform:uppercase;letter-spacing:1px;font-weight:800;color:var(--muted)}
.l-actual{background:#f4f8fb}.l-reserved{background:#fbf7ec}.l-expected{background:#f7f4fb}.l-projected{background:#f2f9f4}
.lines{display:grid;gap:5px}.lines dt{font-size:13px;color:var(--muted)}.lines dd{font-weight:750;font-size:15px;margin-bottom:3px;overflow-wrap:anywhere}
.note-s{font-size:12.5px;color:var(--muted)}
.callout{background:var(--soft-bg);border-radius:12px;padding:14px;display:grid;gap:8px;margin-top:6px}.callout.amber{background:var(--amber-bg)}
.next-note{color:var(--muted);font-size:14px;text-align:center;max-width:620px;margin:6px auto 0}
.intro h1{margin-top:2px}
/* needs-info callout on first plan (and Today spend-answer reuse) */
.hero-plan{background:linear-gradient(165deg,#0f4a3d,#1d7a63);color:#fff;gap:10px}
.hero-plan.warn{background:linear-gradient(165deg,#6a3f12,#9a6208)}
.hero-plan .badge{background:#fff;color:#0f4a3d}
.hp-top{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.hp-label{font-weight:700;opacity:.92}
.hp-num{display:flex;align-items:baseline;gap:6px}.pace-num{font-size:clamp(46px,10vw,72px);font-weight:850;letter-spacing:-2px;line-height:1}.hp-num .per{color:#d6efe3;font-size:20px;font-weight:650}
.hp-sub{font-size:16px;color:#e7f6ee}
.hp-need{font-size:22px}.need-q{background:rgba(255,255,255,.14);border-radius:14px;padding:14px;display:grid;gap:8px}.need-q .hint{color:#f3e4c4}.need-q .btn{justify-self:start;background:#fff;color:#5a3a06;box-shadow:none}
.kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:10px;margin-top:6px}
.kpi{background:rgba(255,255,255,.12);border-radius:14px;padding:12px 14px;display:grid;gap:2px}.k-l{font-size:12.5px;opacity:.9;font-weight:650}.k-v{font-size:25px;font-weight:800}.k-h{font-size:12px;opacity:.85}

@media (max-width:560px){
  .progress .lbl{display:none}.progress li{flex:1 1 40px;justify-content:center}
  .actions{justify-content:stretch}.actions .btn{flex:1 1 140px}.actions .btn.ghost:first-child{margin-right:0}
  .fr-amt{justify-items:start}.found-row{flex-wrap:wrap}.b-head .badge{margin-left:0}.use{margin-left:0}
  .strip{gap:3px}
}
@media (prefers-reduced-motion:reduce){*{transition:none!important}}
@media print{.progress,.actions,.top-right{display:none}.card{box-shadow:none;border:1px solid #ccc}}

/* header cards inside a stack line up with the cards below them */
.stack>.card.narrow-lg{max-width:none}


/* =====================================================================
   Stage 3: Today
   ===================================================================== */
.today{gap:16px;max-width:720px}
.today-head{display:flex;justify-content:space-between;align-items:flex-end;gap:12px;flex-wrap:wrap;padding:2px 2px 0}
.today-head .sub{margin-top:4px}
.th-actions{display:flex;gap:8px;flex-wrap:wrap}
.today .card{min-width:0}
.today .spend-answer .hp-num .pace-num{font-size:clamp(40px,10vw,56px)}
.today .spend-answer .hp-sub{font-size:16px;line-height:1.45;max-width:36em}
.one-purchase{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 12px;margin:12px 0 4px;padding:10px 12px;border-radius:10px;background:rgba(255,255,255,.14);color:#fff;max-width:36em}
.one-purchase .op-label{font-weight:700;font-size:15px}
.one-purchase .op-num{font-size:24px;font-weight:850;letter-spacing:-.5px}
.one-purchase .op-note{flex-basis:100%;font-size:14px;line-height:1.4;color:#e7f6ee}
.today .after-alert.amber-card,.today .card.amber-card{border-color:#c9a227;background:#fffbeb}
.today .rec.amber-card{border-left-width:0;border-left-style:none}
.today .after-alert{gap:8px;padding:14px 16px}
.today .after-lead{margin:0;font-size:20px;line-height:1.3}
.today .goal-remind .goal-bar{height:8px;max-width:240px}
.today .balance-line{margin:0}
.today .shortfall-notice p{margin:0 0 8px;line-height:1.45}
.today .shortfall-preview{margin-top:4px;display:grid;gap:6px;align-items:stretch}
.today .shortfall-preview p{margin:0}
.today .shortfall-preview .preview-line{display:flex;justify-content:space-between;align-items:baseline;gap:8px 12px;flex-wrap:wrap}
.today .shortfall-preview .preview-line b{white-space:nowrap}
.today .everyday-checkin{margin-top:14px;padding-top:12px;border-top:1px solid #d7dee6}
.today .spend-details{padding:12px 16px}
.today .spend-details>summary{cursor:pointer;list-style:none}
.today .spend-details>summary::-webkit-details-marker{display:none}
.today .spend-details-body{margin-top:10px}

/* hero: a slightly deeper gradient than the plan summary, so small text stays at 4.5:1 or better even at the lightest corner */
.hero-today{background:linear-gradient(165deg,#0c3f34,#17695a)}
.hero-today.amber{background:linear-gradient(165deg,#4d3a0c,#7a5e14)}
.hero-today.warn{background:linear-gradient(165deg,#5c360f,#85540a)}
.hero-today .hp-num{align-items:baseline;flex-wrap:wrap}
.hero-today .hp-num .per{font-size:22px}
.hero-today .hp-need{font-size:clamp(30px,7vw,44px);letter-spacing:-1px}
.hero-today .kpi.k-pace .k-v{font-size:22px}
.trio{grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}
.trio .kpi{align-content:start}
.trio .k-v{font-size:22px}
.trio .k-h{line-height:1.35}
.hp-relate{font-size:14px;color:#d6efe3}
.sure{border-radius:12px}
.hero-today .sure{background:rgba(255,255,255,.1);padding:8px 12px}
.hero-today .sure summary{cursor:pointer;font-weight:700;font-size:14px;color:#fff}
.sure summary{cursor:pointer;font-weight:700;font-size:14px;padding:4px 0}
.sure-list{display:grid;gap:6px;margin-top:6px;font-size:14px;padding-left:18px;list-style:disc}
.sure-list li{list-style:disc}
.hero-today .sure-list{color:#fff}

/* progress */
.prows{display:grid;gap:14px}
.prow{display:grid;gap:5px}
.prow-h{display:flex;justify-content:space-between;gap:10px;align-items:baseline}
.prow-v{font-weight:800;font-size:17px}.prow-v.neg{color:var(--red)}
.pbar{height:12px;border-radius:99px;background:var(--line);overflow:hidden}
.pfill{display:block;height:100%;background:var(--brand2);border-radius:99px;min-width:0}
.pbar.over .pfill{background:var(--red)}
.prow-s{font-size:13px;color:var(--muted)}
.sem-line{font-size:14.5px;background:var(--soft-bg);border-radius:10px;padding:9px 12px}
.lines.split{gap:10px}
.lines.split dt{display:flex;gap:8px;align-items:center;flex-wrap:wrap;font-weight:700;color:var(--ink2)}
.lines.split dd{font-weight:500;font-size:14.5px;margin-bottom:0}
.cats{display:grid;gap:6px;margin:6px 0;font-size:14px}.cats li{display:flex;justify-content:space-between;gap:10px}.cats .neg{color:var(--red);font-weight:700}

/* purchase checker */
.check-form,.log-form,.ev-form,.ci-form{display:grid;gap:12px}
.check-form .btn.big{justify-self:stretch}
.cr{border-radius:14px;padding:16px;display:grid;gap:10px;border:1.5px solid var(--line);background:var(--soft-bg)}
.cr:focus{outline:3px solid rgba(29,122,99,.35)}
.cr.tone-good{background:var(--good-bg);border-color:#bfe5d0}
.cr.tone-amber{background:var(--amber-bg);border-color:var(--amber-line)}
.cr.tone-bad{background:var(--red-bg);border-color:#f0c6bf}
.cr-top{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.cr-amt{font-size:15px}
.cr-head{font-size:19px}.cr-sum{font-size:15.5px}
.cr-lines{display:grid;gap:8px}
.cr-lines li{display:flex;gap:10px;align-items:flex-start;font-size:14.5px}
.cr-lines .dot{flex:none;width:10px;height:10px;border-radius:50%;margin-top:7px;background:#94a8a1}
.cr-lines .tone-good .dot{background:var(--good)}.cr-lines .tone-amber .dot{background:#c98a14}.cr-lines .tone-bad .dot{background:var(--red)}.cr-lines .tone-blue .dot{background:var(--blue)}
.cr-advice{background:rgba(255,255,255,.7);border-radius:12px;padding:10px 12px}.cr-advice ul{display:grid;gap:4px;padding-left:18px;margin-top:4px;font-size:14.5px}.cr-advice li{list-style:disc}
.row-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:2px}
.tv-msg{border-radius:10px;padding:10px 12px;font-size:14.5px;font-weight:600;background:var(--good-bg);color:#0f5a39}
.tv-msg.bad{background:var(--red-bg);color:var(--red)}
.tv-msg:focus{outline:3px solid rgba(29,122,99,.35)}
.dup{align-items:flex-start;margin-bottom:0}.dup-body{display:grid;gap:6px}.dup-list{display:grid;gap:3px;padding-left:18px}.dup-list li{list-style:disc;font-size:14px}

/* upcoming */
.evs{display:grid;gap:10px}
.ev{display:grid;grid-template-columns:76px minmax(0,1fr);gap:12px;padding:12px;border-radius:14px;background:var(--soft-bg);border-left:5px solid #b8c8c0}
.ev.confirmed{border-left-color:var(--good)}.ev.scheduled{border-left-color:var(--blue)}.ev.expected{border-left-color:#c98a14}.ev.uncertain{border-left-color:#94a8a1;border-left-style:dashed}
.ev.limiting{background:var(--amber-bg)}.ev.done{opacity:.75}
.ev-date{display:grid;align-content:start;font-size:13px;color:var(--muted)}.ev-date b{color:var(--ink);font-size:15px}
.ev-main{display:grid;gap:6px;min-width:0}
.ev-top{display:flex;justify-content:space-between;gap:10px;align-items:baseline}
.ev-name{overflow-wrap:anywhere}.ev-amt{font-weight:800;white-space:nowrap}.ev-amt.pos{color:var(--good)}
.ev-tags{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.ev-state{font-size:13px;color:var(--ink2)}
.ev-note{font-size:13.5px;color:var(--ink2)}
.ev-limit{display:flex;gap:8px;align-items:flex-start;font-size:13.5px;color:#6e4606;font-weight:600}
.ev-form{background:#fff;border-radius:12px;padding:12px;margin-top:4px}

/* status, scenario, callouts */
.st-top{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.st-top .card-title{flex:1 1 220px}
.facts{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px}
.fact{display:grid;gap:2px;background:var(--soft-bg);border-radius:12px;padding:10px 12px;align-content:start}
.fact .k-l{opacity:1;color:var(--muted);font-size:12.5px}.fact .k-v{font-size:21px}.fact .k-h{opacity:1;color:var(--muted);font-size:12.5px;line-height:1.35}
.status.on_track{border-top:5px solid var(--good)}.status.watch{border-top:5px solid #c98a14}.status.off_track{border-top:5px solid var(--red)}
.steps{display:grid;gap:4px;padding-left:20px;font-size:14.5px}.steps li{list-style:decimal}
.scen .sc-cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}
.sc-col{border-radius:14px;padding:14px;display:grid;gap:3px;align-content:start}
.sc-col.c{background:var(--amber-bg);border:1.5px solid var(--amber-line)}.sc-col.x{background:var(--soft-bg)}
.sc-pace{font-size:26px;letter-spacing:-.5px}
.ideas{display:grid;gap:10px;margin-top:6px}.ideas li{background:var(--soft-bg);border-radius:12px;padding:10px 12px;display:grid;gap:2px}
.idea-gain{font-weight:700;color:var(--good);font-size:14px}

/* log */
.prs{display:grid;gap:8px;margin:6px 0}
.pr{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 10px;align-items:center;padding:10px 12px;background:var(--soft-bg);border-radius:12px}
.pr .row-actions{grid-column:1/-1}.pr.editing{grid-template-columns:minmax(0,1fr)}
.pr-main{display:flex;gap:8px;align-items:center;flex-wrap:wrap;min-width:0}.pr-main b{overflow-wrap:anywhere}.pr-sub{font-size:13px;color:var(--muted)}
.pr-amt{white-space:nowrap}.pr-amt.pos{color:var(--good)}
.dupe{margin-top:8px}.dupes{align-items:flex-start;margin-bottom:0}

/* check-in, recommendation */
.checkin.due{border-top:5px solid #c98a14}
.chg{display:grid;gap:6px;margin:6px 0}.chg li{display:flex;justify-content:space-between;gap:10px;font-size:14px;align-items:flex-start}.chg .pos{color:var(--good)}
.rec{border-left:6px solid var(--blue)}
.rec.tone-bad{border-left-color:var(--red)}.rec.tone-amber{border-left-color:#c98a14}.rec.tone-good{border-left-color:var(--good)}
.rec-ico{flex:none;display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;border-radius:12px;background:var(--blue-bg);color:var(--blue)}
.rec.tone-amber .rec-ico,.rec.tone-bad .rec-ico{background:var(--amber-bg);color:var(--amber)}.rec.tone-good .rec-ico{background:var(--good-bg);color:var(--good)}
.evidence{display:grid;gap:4px;padding-left:18px;font-size:14px;color:var(--ink2)}.evidence li{list-style:disc}
.thin{border-left:6px solid #c98a14;background:var(--amber-bg)}
.cta-today{display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap;background:linear-gradient(165deg,#e8f4c8,#d8f3dc)}
.cta-today .card-sub{margin-top:2px}
@media (max-width:560px){
  .ev{grid-template-columns:62px minmax(0,1fr);gap:10px;padding:10px}
  .today-head{align-items:flex-start}
  .row-actions .btn{flex:1 1 auto}
  .trio{grid-template-columns:1fr}
  .btn.small{min-height:40px}.sure summary{min-height:36px;display:flex;align-items:center}
}
@media print{.row-actions,.th-actions{display:none}}

/* ---------- Stage 4: Semester ---------- */
.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.page.wide{max-width:1240px}
.mainnav{display:inline-flex;gap:4px;background:#e4ece6;border-radius:99px;padding:4px;margin:0 0 16px;max-width:100%;overflow:hidden;box-sizing:border-box}
.tab{padding:9px 20px;border-radius:99px;font-weight:700;font-size:15px;color:var(--ink2);white-space:nowrap;min-height:40px;line-height:1.2}
.tab:hover{background:#d5e2d9}.tab.on{background:var(--brand);color:#fff}
.semester .neg,.sem-card .neg,.sem-hero .neg{color:var(--red)}
.semester .pos{color:var(--good)}
.sem-head h1{font-size:clamp(24px,3.4vw,32px);letter-spacing:-.5px}
.period-pick{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:12px}.pp-l{font-size:13px;font-weight:750;color:var(--muted);text-transform:uppercase;letter-spacing:.8px}
.sem-hero{gap:12px;border-left:8px solid var(--good)}
.sem-hero.amber{border-left-color:#c98a0b}.sem-hero.warn{border-left-color:var(--red)}
.sh-top{display:flex;gap:12px;align-items:center;flex-wrap:wrap}
.sh-title{font-size:clamp(20px,2.8vw,27px);letter-spacing:-.4px;flex:1 1 320px;line-height:1.2}
.sh-badge{border-radius:99px;padding:5px 13px;font-size:13px;font-weight:800;background:var(--good-bg);color:var(--good)}
.sh-badge.amber{background:var(--amber-bg);color:#6e4606}.sh-badge.warn{background:var(--red-bg);color:var(--red)}
.sh-detail{font-size:16px;color:var(--ink2);max-width:80ch}
.sh-basis{font-size:13.5px;color:var(--muted);max-width:90ch}
.stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(215px,1fr));gap:12px}
.sstat{background:var(--soft-bg);border-radius:14px;padding:14px 16px;display:grid;gap:3px;align-content:start;min-width:0}
.sstat .k-l{opacity:1;color:var(--muted);font-size:13px;font-weight:700}
.sstat .k-v{font-size:clamp(24px,3vw,30px);font-weight:800;letter-spacing:-.6px;line-height:1.1}
.sstat .k-h{opacity:1;color:var(--muted);font-size:13px;line-height:1.35}
.rests{display:grid;gap:8px;font-size:14px;color:var(--ink2);border-top:1px solid var(--line);padding-top:12px}
.rest{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap}
.sem-warn{display:grid;gap:0}.sem-warn .note{margin-bottom:8px;align-items:flex-start}
.sem-row2{display:grid;grid-template-columns:minmax(0,3fr) minmax(0,2fr);gap:16px;align-items:start}
.sem-row2.even{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
table.cmp{width:100%;border-collapse:collapse;font-size:15px}
table.cmp th,table.cmp td{padding:10px 12px;text-align:left;border-bottom:1px solid var(--line2);vertical-align:top}
table.cmp thead th{font-size:12.5px;text-transform:uppercase;letter-spacing:.6px;color:var(--muted);font-weight:800;border-bottom:2px solid var(--line)}
table.cmp tbody th{font-weight:650;color:var(--ink2)}
table.cmp.small{font-size:14px}
.td-sub{color:var(--muted);font-size:13px}
table.cmp td.pos{color:var(--good);font-weight:700}table.cmp td.neg{color:var(--red);font-weight:700}table.cmp td.zero{color:var(--muted)}
table.cmp tr.base th,table.cmp tr.base td{background:var(--soft-bg)}
table.cmp tr.na th,table.cmp tr.na td{color:var(--muted);font-size:13px}
.compare{overflow-x:auto}.compare table{min-width:560px}
.ties{display:grid;gap:8px}.ties li{display:flex;justify-content:space-between;gap:12px;align-items:baseline;font-size:15px;border-bottom:1px solid var(--line2);padding-bottom:8px}.ties b{white-space:nowrap}
/* chart */
.chart-wrap{width:100%;overflow:hidden}
svg.chart{display:block;width:100%;height:auto}
.chart text{font-size:12px;fill:#374151;font-family:inherit}
.chart .c-cush{fill:#7c4a03;font-weight:700}.chart .c-neg{fill:#991b1b;font-weight:700}.chart .c-zero{fill:#374151;font-weight:650}.chart .c-after{fill:#374151;font-weight:800}
.chart .c-mark{fill:#1f2937;font-size:11.5px;font-weight:700}
.chart .c-low{fill:#991b1b;font-weight:800;font-size:12px;paint-order:stroke;stroke:#fff;stroke-width:3.5px;stroke-linejoin:round}
.chart .c-ok{fill:#1f5c4a;font-weight:750;font-size:12px;paint-order:stroke;stroke:#fff;stroke-width:3.5px;stroke-linejoin:round}
.chart .c-lane{fill:#4b5563;font-size:11px;font-weight:700}
.legend{display:flex;flex-wrap:wrap;gap:6px 18px;font-size:13px;color:var(--ink2)}.legend li{display:inline-flex;align-items:center;gap:6px}
.lg-ico{flex:none}
.pressure h3,.events h3,.rent-gaps h3{font-size:16px;margin:4px 0 8px}
.pp{display:grid;gap:10px}
.pp-item{border-left:5px solid #c98a0b;background:#fffaf0;border-radius:0 12px 12px 0;padding:10px 14px;display:grid;gap:4px}
.pp-item.short,.pp-item.below_cushion{border-left-color:var(--red);background:var(--red-bg)}
.pp-item.watch{border-left-color:var(--blue);background:var(--blue-bg)}
.pp-head{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.pp-item p{font-size:14.5px;color:var(--ink2)}
.evls{display:grid;gap:0}
.ev-month{font-size:12px;text-transform:uppercase;letter-spacing:1px;font-weight:800;color:var(--muted);padding:12px 0 4px}
.evl{display:grid;grid-template-columns:62px minmax(0,1fr) 92px auto 118px;gap:10px;align-items:center;padding:8px 0;border-bottom:1px solid var(--line2);font-size:14.5px}
.evl-d{font-weight:700;color:var(--ink2)}.evl-n{display:grid;min-width:0}.evl-k{font-size:12.5px;color:var(--muted)}
.evl-a{font-weight:800;text-align:right;white-space:nowrap}.evl-a.pos{color:var(--good)}
.evl-bal{font-size:12.5px;color:var(--muted);text-align:right}
.evl.uncertain .evl-n b{color:var(--muted)}
/* months */
.mcards{display:grid;grid-template-columns:repeat(auto-fit,minmax(285px,1fr));gap:14px}
.mcard{border:1.5px solid var(--line);border-radius:16px;padding:16px;display:grid;gap:10px;align-content:start;background:#fff}
.mcard.short{border-color:#e4a79f;background:#fffafa}.mcard.tight{border-color:#e6cd8a}
.mcard header{display:flex;justify-content:space-between;align-items:center;gap:8px}.mcard h3{font-size:18px}
.mc-part{font-size:13px;color:var(--muted);margin-top:-6px}
.mc-end{display:grid;gap:1px}.mc-end .k-l{opacity:1;color:var(--muted);font-size:12.5px;font-weight:700}.mc-end .k-v{font-size:28px;font-weight:800;letter-spacing:-.6px}.mc-end .k-h{opacity:1;color:var(--muted);font-size:13px}
.mc-rows{display:grid;gap:6px}.mc-rows>div{display:flex;justify-content:space-between;gap:10px;align-items:baseline;font-size:14.5px;flex-wrap:wrap}.mc-rows dt{color:var(--ink2)}.mc-rows dd{font-weight:750}.mc-rows dd.mc-sub{font-weight:500;color:var(--muted);font-size:12.5px;width:100%;text-align:right}
.mbar{display:grid;gap:4px}.mb-row{display:flex;height:10px;background:#eef3ef;border-radius:6px;overflow:hidden}
.seg.in{background:var(--good)}.seg.bills{background:#1f3a4d}.seg.ess{background:#6b8ea3}.seg.disc{background:#d9a93a}
.mc-low{font-size:13.5px;color:var(--ink2)}.mc-low.bad{color:var(--red);font-weight:650}
.mc-ev{display:grid;gap:4px;font-size:13.5px;margin-top:6px}
/* income */
.irs{display:grid;gap:10px}
.ir{border:1.5px solid var(--line);border-radius:14px;padding:12px 14px;display:grid;gap:6px}
.ir-head{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.ir-nums{display:flex;gap:6px 18px;flex-wrap:wrap;font-size:14px;color:var(--ink2)}
.ir-note{font-size:13.5px;color:var(--muted)}
.rg{display:grid;gap:8px}.rg li{border-left:4px solid var(--good);padding:6px 12px;background:var(--soft-bg);border-radius:0 10px 10px 0;font-size:14.5px}.rg li.bad{border-left-color:var(--red);background:var(--red-bg)}
/* stress */
.st-controls{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:14px 16px;align-items:start}
.st-item{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px;align-content:start}
.st-item.off .chip{opacity:.6}
.st-pick select{border:1.5px solid #cdd9d1;border-radius:10px;padding:8px 10px;background:#fff;font-weight:650;min-height:40px}
.st-why{font-size:13px;color:var(--muted);flex-basis:100%}
.st-empty{padding:6px 0}
.st-result{display:grid;gap:12px;border:1.5px solid var(--line);border-radius:14px;padding:16px;background:#fafcfa;scroll-margin-top:12px}
.st-assume{background:var(--blue-bg);color:#1f5873;padding:10px 12px;border-radius:10px;font-size:14.5px}
.st-status{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.st-changed{font-weight:700;color:#6e4606}
.safe-note{display:flex;align-items:center;gap:6px;font-size:13.5px;color:#245c49;font-weight:650}
/* recommendations */
.recs{display:grid;gap:12px}
.rec-item{border:1.5px solid var(--line);border-radius:14px;padding:14px 16px;display:grid;gap:8px}
.rec-item.fix{border-color:#9fd6b9;background:#f6fbf8}
.rec-item:focus{outline:3px solid rgba(29,122,99,.35)}
.ri-head{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.ri-head b{font-size:16.5px;flex:1 1 260px}
.verify{font-size:14px;background:var(--soft-bg);padding:8px 10px;border-radius:8px;color:var(--ink2)}
.confirm-box{background:var(--amber-bg);border-radius:10px;padding:12px;display:grid;gap:8px;color:#4d3406}
.ok-line{display:flex;align-items:center;gap:6px;color:#0f5a39;font-weight:650}
/* between semesters */
.bt-items{display:grid;gap:6px;font-size:14.5px}.bt-sum{font-size:14.5px;color:var(--ink2)}
.offers{display:grid;gap:10px}.offer{display:grid;gap:8px;justify-items:start;background:var(--soft-bg);border-radius:12px;padding:12px 14px}.amber-text{color:#6e4606}
/* expenses */
.pe-list{display:grid;gap:8px}.pe-list li{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:10px;align-items:center;font-size:14.5px;border-bottom:1px solid var(--line2);padding-bottom:8px}.pe-sub{color:var(--muted);font-size:13px}
.exp-form{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;align-items:end;margin-top:10px}
.exp-form .field.check{display:flex;align-items:center;gap:8px;grid-column:1/-1}.exp-form .field.check input{width:20px;height:20px}
.exp-form input[type=date],.exp-form select,.exp-form input[type=text]{width:100%;border:1.5px solid #cdd9d1;border-radius:12px;padding:11px 12px;background:#fff;min-height:44px}
.semester .next-note{font-size:13.5px;color:var(--muted)}
@media (max-width:900px){.sem-row2,.sem-row2.even{grid-template-columns:minmax(0,1fr)}}
@media (max-width:640px){
  .stat-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
  .sstat{padding:12px}.sstat .k-v{font-size:22px}
  .evl{grid-template-columns:54px minmax(0,1fr) auto;grid-template-areas:"d n a" ". b bal";row-gap:2px}
  .evl-d{grid-area:d}.evl-n{grid-area:n}.evl-a{grid-area:a}.evl-b{grid-area:b}.evl-bal{grid-area:bal;text-align:right}
  .pe-list li{grid-template-columns:minmax(0,1fr) auto}.pe-list li .btn{grid-column:1/-1;justify-self:start}
  .sh-detail{font-size:15px}
  .mcards{grid-template-columns:minmax(0,1fr)}
  table.cmp{font-size:14px}table.cmp th,table.cmp td{padding:8px 6px}
}
@media print{.mainnav,.st-controls,.exp-form{display:none}.sem-hero{border:1px solid #ccc}}

.exp-form .field.check input{width:24px;height:24px;flex:none}
.period-below{display:grid;gap:8px}.period-below:empty{display:none}.period-below .period-pick{margin-top:0}
@media (max-width:640px){
  .mainnav{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));width:100%;gap:2px;border-radius:16px;padding:4px;overflow:hidden}
  .tab{padding:8px 2px;font-size:12px;line-height:1.15;white-space:normal;text-align:center;min-height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center}
}
@media (max-width:400px){
  .mainnav{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));width:100%;gap:2px;border-radius:14px}
  .tab{padding:7px 1px;font-size:11.5px;min-height:44px}
  .sem-head .sub{font-size:14px}
  .sh-title{font-size:19px}
}
@media (max-width:640px){.exp-form .field.check input{width:28px;height:28px}}

/* ---------- Stage E: Finley, goals, breakdown, purchase alternatives ---------- */
.finley{display:grid;grid-template-columns:auto minmax(0,1fr);gap:12px;align-items:start;background:var(--blue-bg);border-radius:var(--r);padding:14px 16px;color:#1f5873}
.fin-who{font-size:12px;font-weight:800;letter-spacing:.8px;text-transform:uppercase;margin-bottom:2px;color:#2c6f8d}
.fin-say{font-size:15px;font-weight:600;line-height:1.45;color:var(--ink)}
.pockets .pocket{display:grid;gap:4px;align-items:start}
.goal-list{display:grid;gap:12px;margin-top:10px}
.goal-card{border:1.5px solid var(--line);border-radius:14px;padding:14px 16px;display:grid;gap:10px;background:#fafcfa}
.gc-head{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.gc-head h3{flex:1 1 180px;font-size:18px}
.gc-meta{font-size:13.5px;color:var(--muted)}
.gc-next{font-size:14.5px;font-weight:650}
.goal-form{margin-top:8px;padding-top:8px;border-top:1px solid var(--line2)}
.alts{display:grid;gap:10px;margin-top:8px;padding-top:8px;border-top:1px solid var(--line2)}
.alt-card{border:1.5px solid var(--line);border-radius:12px;padding:12px 14px;display:grid;gap:8px;background:#fff}
.alt-card.off{opacity:.75}
.hint-list{display:grid;gap:4px;padding-left:18px;font-size:13.5px;color:var(--ink2)}.hint-list li{list-style:disc}
.cr-alts{display:grid;gap:10px;margin-top:4px}
.cr-alt{background:rgba(255,255,255,.7);border-radius:12px;padding:10px 12px;display:grid;gap:6px}
.bd-wrap{overflow-x:auto;margin:10px 0}
.bd-tbl{width:100%;border-collapse:collapse;font-size:13.5px;min-width:720px}
.bd-tbl caption{text-align:left;font-weight:750;padding:4px 0 8px;color:var(--ink2)}
.bd-tbl th,.bd-tbl td{padding:8px 8px;border-bottom:1px solid var(--line2);text-align:right;vertical-align:top}
.bd-tbl th[scope="row"],.bd-tbl thead th:first-child,.bd-tbl thead th:nth-child(2){text-align:left}
.bd-tbl thead th{font-size:11.5px;text-transform:uppercase;letter-spacing:.4px;color:var(--muted);font-weight:750;white-space:nowrap}
.bd-row.incomplete th{box-shadow:inset 3px 0 0 var(--amber)}
.bd-row.past{background:#f7faf7}
.bd-row.current{background:var(--blue-bg)}
.fin-act{margin-top:8px}
.bd-cards{display:grid;gap:0;margin:4px 0 0}
.bd-card{border:0;border-radius:0;background:transparent;border-top:1px solid var(--line2);overflow:hidden}
.bd-card.incomplete{box-shadow:inset 3px 0 0 var(--amber)}
.bd-sum{display:grid;grid-template-columns:minmax(0,1fr) auto;grid-template-areas:"lab end" "phase end";gap:2px 10px;align-items:center;padding:10px 12px;min-height:44px;cursor:pointer;list-style:none}
.bd-sum::-webkit-details-marker{display:none}
.bd-lab{grid-area:lab;font-weight:750;font-size:14.5px}
.bd-phase{grid-area:phase;font-size:12px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.4px}
.bd-end{grid-area:end;font-weight:800;white-space:nowrap;font-size:14px}
.bd-dl{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;padding:0 12px 12px;font-size:13.5px;border-top:1px solid var(--line2)}
.bd-dl dt{color:var(--ink2)}.bd-dl dd{font-weight:750;text-align:right}
@media (max-width:640px){
  .finley{grid-template-columns:auto minmax(0,1fr);padding:12px}
  .goal-card{padding:12px}
}

/* where your money goes */
.spend .sp-total{font-size:15px;margin:4px 0 12px}.spend .sp-total b{font-size:24px;font-weight:800;color:var(--ink)}
.sp-kinds{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-bottom:14px}
.sp-kind{border-radius:12px;padding:10px 12px;display:grid;gap:2px;background:var(--soft-bg);border-left:4px solid var(--muted)}
.sp-kind.k-bill{border-left-color:var(--blue)}.sp-kind.k-essential{border-left-color:var(--brand2)}.sp-kind.k-flexible{border-left-color:var(--amber)}
.sk-l{font-size:12.5px;font-weight:650;color:var(--muted)}.sk-v{font-size:18px;font-weight:800}
.spend-list{list-style:none;margin:0;padding:0;display:grid;gap:12px}
.sp-row{display:grid;gap:5px}.sp-line{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}
.sp-cat,.sp-amt{display:grid;gap:1px;min-width:0}.sp-amt{text-align:right;flex-shrink:0}
.sp-track{display:block;height:8px;border-radius:99px;background:var(--line2);overflow:hidden}
.sp-bar{display:block;height:100%;border-radius:99px;background:var(--muted)}
.k-bill .sp-bar{background:var(--blue)}.k-essential .sp-bar{background:var(--brand2)}.k-flexible .sp-bar{background:var(--amber)}
.sp-bud{font-size:12.5px;color:var(--muted)}.sp-bud.over{color:var(--red);font-weight:650}
.sp-fixed{margin-top:14px;padding-top:12px;border-top:1px solid var(--line2)}
@media (max-width:519px){.sp-kinds{grid-template-columns:1fr}.sp-kind{grid-template-columns:1fr auto;align-items:center}}
@media (max-width:359px){table.cmp{font-size:13px}table.cmp th,table.cmp td{padding:7px 4px}table.cmp .badge{white-space:normal}}

/* Semester outlook and expandable forecast sections */
.sem-hero .sem-term{margin:0;color:var(--muted);font-size:14px;font-weight:650;line-height:1.35}
.sem-hero h1.sh-title{margin:0;font-size:clamp(28px,4.6vw,40px);font-weight:800;letter-spacing:-.6px;line-height:1.15}
.sem-hero.short{background:#fffbeb;border-color:#e7d7a2;border-left-color:#c98a0b}
.sem-why,.sem-help{margin:0;max-width:68ch;line-height:1.45}
.sem-help{font-weight:650}
.sem-k{font-weight:800}
.sem-controls{display:flex;flex-wrap:wrap;gap:10px 14px;align-items:center}
.sem-controls .period-pick{margin:0}
.sem-hero .chip.on{background:#fff;color:var(--brand);border-color:var(--brand)}
.sem-suggest{margin:0}
.sem-hero .sem-suggest > summary.btn.primary{display:inline-flex;width:auto;align-items:center;justify-content:center;color:#fff;background:var(--brand);border-radius:12px;padding:11px 18px;font-weight:700;list-style:none;min-height:44px;box-shadow:0 6px 16px rgba(20,94,77,.25)}
.sem-hero .sem-suggest > summary.btn.primary::-webkit-details-marker{display:none}
.sem-hero .sem-suggest > summary.btn.primary::marker{content:none}
.sem-hero .sem-suggest > summary.btn.primary:hover{background:var(--brand-d)}
.sem-hero .sem-suggest > summary.btn.primary:focus{outline:3px solid rgba(29,122,99,.45);outline-offset:2px}
.sem-ending{color:var(--ink2);margin:0}
.sem-ending b{font-size:1.1em;margin-left:.35em}
.sem-chart-foot{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;justify-content:space-between}
.sem-action-lead{font-weight:750;font-size:clamp(16px,2.4vw,20px);margin:0}
.sem-disclosure-body{display:grid;gap:10px;padding:4px 0 8px;min-width:0}
.sem-disclosure-body p{margin:0}
.sem-milestones{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));list-style:none;margin:8px 0;padding:0;gap:8px}
.sem-milestones li{display:grid;gap:3px;background:var(--soft-bg);padding:10px 12px;border-radius:10px}
.sem-milestones li span{font-size:.88em;color:var(--ink2)}
.sem-period-summary{display:grid;gap:8px;padding:12px 2px;cursor:pointer;color:var(--ink)}
.sem-period-name{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 10px}
.sem-period-figures{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px 16px}
.sem-fig{display:grid;gap:2px;min-width:0}
.sem-fig-l{color:var(--muted);font-size:13px;font-weight:650}
.sem-fig-v{font-weight:800;font-size:17px;font-variant-numeric:tabular-nums;letter-spacing:-.2px}
.sem-fig.neg .sem-fig-v{color:var(--red)}
.sem-period-low{color:var(--red);font-size:13px;font-weight:700}
.sem-period-detail{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(230px,100%),1fr));gap:12px;border-top:1px solid var(--line2);padding:12px 2px}
.sem-period-detail h3{margin:0;font-size:15px}
.semester .card.short{background:#fffbeb;border-left:8px solid #c98a0b}
.sem-bridge-lead{margin:0;font-size:clamp(22px,3vw,28px);font-weight:750;letter-spacing:-.3px;line-height:1.2}
.sem-bridge-lead b{font-weight:800}
.sem-bridge-notes{display:grid;gap:4px;min-width:0}
.sem-bridge-when{margin:0;max-width:62ch;line-height:1.45}
.sem-calc{display:grid;gap:8px;margin:0}
.sem-calc div{display:flex;justify-content:space-between;align-items:baseline;gap:12px}
.sem-calc dt{font-weight:650;min-width:0}
.sem-calc dd{margin:0;font-weight:800;font-variant-numeric:tabular-nums;white-space:nowrap}
.sem-calc dd.neg{color:var(--red)}
.sem-breakdown > summary{font-size:19px;font-weight:750;letter-spacing:-.2px;color:var(--ink);min-height:44px;display:flex;align-items:center}
.semester summary{min-height:32px}
.sem-chart-toggle{display:flex;align-items:center;gap:8px;min-height:32px;cursor:pointer}
.sem-chart-toggle input{width:24px;height:24px;flex:none;margin:0}
.sem-qa{display:grid;gap:12px;margin:0 0 14px;min-width:0}
.sem-qa-block{display:grid;gap:4px;min-width:0}
.sem-qa-q{margin:0;font-size:13px;font-weight:800;letter-spacing:.02em;text-transform:uppercase;color:var(--muted)}
.sem-qa-a{margin:0;font-size:15px;line-height:1.45;color:var(--ink);overflow-wrap:anywhere}
.sem-chart-basis{margin:2px 0 0;color:var(--ink2);font-size:13.5px;line-height:1.4;font-weight:500}
.sem-chart-panel{display:grid;gap:8px;min-width:0}
.sem-chart-head{display:flex;flex-wrap:wrap;gap:10px 14px;align-items:flex-start;justify-content:space-between}
.sem-chart-head-text{min-width:0;flex:1 1 12rem}
.sem-chart-h{margin:0;font-size:16px;font-weight:750}
.sem-chart-range{margin:4px 0 0;color:var(--muted);font-size:13.5px}
.sem-chart-legend{margin:0;color:var(--ink2);font-size:13px}
.sem-chart-key{display:flex;flex-wrap:wrap;gap:8px 16px;list-style:none;margin:0;padding:0;font-size:13px;color:var(--ink2);line-height:1.35}
.sem-chart-key li{display:inline-flex;align-items:center;gap:8px;min-width:0;max-width:100%}
.sem-chart-key li span:last-child{min-width:0;overflow-wrap:anywhere}
.sem-mark-list{display:flex;flex-wrap:wrap;gap:4px 16px;margin:0;padding:0;list-style:none;font-size:13.5px;font-weight:700;color:var(--ink)}
.sem-mark-list li{display:inline-flex;align-items:center;gap:6px}
.mk{width:9px;height:9px;flex:none;box-sizing:border-box;background:#fff}
.mk.rent{border:1.5px solid #991b1b}
.mk.low{border:2px solid #1f5c4a;border-radius:50%}
.mk.low.neg{border-color:#9a3412}
.mk.pay{width:0;height:0;background:transparent;border-left:5px solid transparent;border-right:5px solid transparent;border-bottom:8px solid #166534}
.sem-key-swatch{flex:none;width:22px;height:0;border-top:2px dashed #4b5563;border-radius:0}
.sem-key-swatch.cush{border-top-color:#b45309}
.sem-key-swatch.zero{border-top-color:#4b5563}
.sem-key-swatch.expected{border-top-style:dashed;border-top-color:#0f766e}
.sem-range{flex:none}
.sem-forecast-options{display:grid;gap:10px;padding-top:8px}
.sem-compare{display:grid;gap:6px}
.sem-compare-why{margin:0}
.semester .cmp{overflow-wrap:anywhere}
@media(max-width:480px){
  .sem-milestones{grid-template-columns:minmax(0,1fr)}
  .sem-milestones li{grid-template-columns:3.4em minmax(0,1fr) auto;align-items:baseline;gap:4px 8px}
  .sem-milestones li b:last-child{justify-self:end}
  .sem-period-figures{grid-template-columns:minmax(0,1fr)}
  .sem-fig{grid-template-columns:minmax(0,1fr) auto;align-items:baseline}
  .sem-hero .period-pick{margin:0}
  .sem-controls{flex-direction:column;align-items:stretch}
  .sem-chart-head,.sem-chart-foot{flex-direction:column;align-items:flex-start}
  .sem-mark-list{flex-direction:column;align-items:flex-start;gap:3px}
  .sem-qa-a{font-size:14.5px}
  .chart .c-low,.chart .c-ok,.chart .c-cush,.chart .c-zero{font-size:11px}
}

/* Goals */
.goals-head{align-items:center;flex-wrap:wrap}
.goals .goal-list{margin-top:0}
.goals .goal-card{background:#fff}
.goals .gc-head h2{min-width:0;overflow-wrap:anywhere}
.goal-due{font-size:.74em;font-weight:650;color:var(--muted)}
.goal-progress,.goal-option-summary{font-weight:750}
.goal-details-body{display:grid;gap:10px;padding-top:10px;min-width:0}
.goals summary{min-height:32px;cursor:pointer}
.goal-transfer-list{display:flex;flex-wrap:wrap;gap:6px 10px}
.goal-transfer-list li{padding:4px 9px;border-radius:8px;background:var(--soft-bg)}
.goals .row-actions{flex-wrap:wrap}

</style>
</head>
<body>
<a class="skip" href="#main">Skip to the main content</a>
<div id="app"></div>
<noscript><p style="padding:24px;font:16px/1.5 system-ui">Campus Compass needs JavaScript to run. It works offline and sends nothing anywhere.</p></noscript>

<script>
const CC_LICENSE = Object.freeze({"author":"Morgan Powers","year":2026,"line":"Copyright (c) 2026 Morgan Powers. Released under the MIT License."});
;
/* ===== engine/00-core.js ===== */
/* =========================================================================
   Campus Compass financial engine (v3) — 00 core: money, dates, helpers
   -------------------------------------------------------------------------
   * Money is ALWAYS an integer number of cents. Never a float dollar amount.
   * Dates are integer "day numbers" (days since 1970-01-01, UTC calendar),
     so there are no time zones, no daylight-saving bugs and no hidden clocks.
   * The engine never reads the system clock. Every function that needs "today"
     is given it explicitly, which makes every calculation repeatable.
   ========================================================================= */
const CCE = {};
(function (E) {
  'use strict';

  /* ---------- money (integer cents) ---------- */
  // Dollars (number) -> cents. Rounds half away from zero on the decimal value (1.005 -> 101).
  E.toCents = function (x) {
    const n = Number(x);
    if (!Number.isFinite(n)) return 0;
    return Math.sign(n) * Math.round(Math.abs(n) * 100 + 1e-7);
  };
  // Text like "$1,234.50", "(45.10)", "12.30-", "5 CR" -> cents, or null if it is not a clean amount.
  E.parseMoney = function (text) {
    let t = String(text == null ? '' : text).trim();
    if (!t) return null;
    let neg = false;
    if (/^\(.*\)$/.test(t)) { neg = true; t = t.slice(1, -1); }
    if (/\bDR\b/i.test(t)) neg = true;
    t = t.replace(/\b(CR|DR)\b/gi, '').replace(/[$,\s]/g, '');
    if (t.endsWith('-')) { neg = true; t = t.slice(0, -1); }
    if (t.startsWith('-')) { neg = true; t = t.slice(1); } else if (t.startsWith('+')) t = t.slice(1);
    if (!/^(\d+\.?\d*|\.\d+)$/.test(t)) return null;
    const v = E.toCents(Number(t));
    if (!Number.isSafeInteger(v)) return null;
    return neg ? -v : v;
  };
  E.fmt = function (cents, opt) {
    const c = Math.round(Number(cents) || 0), neg = c < 0, a = Math.abs(c);
    const showCents = !opt || opt.cents !== false;
    const dollars = showCents ? Math.floor(a / 100) : Math.floor((a + 50) / 100);
    const s = String(dollars).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    const body = '$' + s + (showCents ? '.' + String(a % 100).padStart(2, '0') : '');
    return (neg && (showCents ? a !== 0 : dollars !== 0) ? '-' : '') + body;
  };
  const isInt = v => typeof v === 'number' && Number.isSafeInteger(v);
  E.isInt = isInt;

  /* ---------- small helpers ---------- */
  E.clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
  E.sum = (arr, f) => { let s = 0; for (const x of arr) s += f ? f(x) : x; return s; };
  E.median = function (arr) {
    if (!arr.length) return 0;
    const a = arr.slice().sort((x, y) => x - y), m = a.length >> 1;
    return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2;
  };
  E.clone = x => JSON.parse(JSON.stringify(x));
  // Round a ratio of integers to the nearest integer (half away from zero), exactly.
  E.divRound = function (num, den) {
    if (den === 0) return 0;
    const s = (num < 0) !== (den < 0) ? -1 : 1;
    return s * Math.floor((Math.abs(num) * 2 + Math.abs(den)) / (Math.abs(den) * 2));
  };
  // Keep text short and free of control characters. (Rendering must still escape HTML; see UI stage.)
  E.safeStr = function (v, max, dflt) {
    let s = String(v == null ? (dflt == null ? '' : dflt) : v).replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
    return s.slice(0, max);
  };
  // FNV-1a 32-bit — used only to detect accidental corruption of backup files (not for security).
  E.hash32 = function (s) {
    let h = 0x811c9dc5;
    for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
    return h.toString(16).padStart(8, '0');
  };
  // Deterministic ids: derived from a counter stored in the plan (no clock, no randomness).
  E.newId = function (plan, prefix, taken) {
    let id;
    do { plan.seq = (plan.seq || 0) + 1; id = prefix + plan.seq.toString(36); } while (taken && taken.has(id));
    return id;
  };

  /* ---------- dates (integer day numbers) ---------- */
  const MS = 86400000, D = {};
  E.D = D;
  D.dim = (y, m) => new Date(Date.UTC(y, m, 0)).getUTCDate();                       // m = 1..12
  D.make = (y, m, d) => Math.floor(Date.UTC(y, m - 1, Math.min(Math.max(d, 1), D.dim(y, m))) / MS);   // day is clamped to month length
  D.ymd = n => { const t = new Date(n * MS); return { y: t.getUTCFullYear(), m: t.getUTCMonth() + 1, d: t.getUTCDate() }; };
  D.parse = function (s) {                                                        // strict 'YYYY-MM-DD' -> day number, or null
    const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(s == null ? '' : s).trim());
    if (!m) return null;
    const y = +m[1], mo = +m[2], d = +m[3];
    if (y < 1970 || y > 2200 || mo < 1 || mo > 12 || d < 1 || d > D.dim(y, mo)) return null;
    return D.make(y, mo, d);
  };
  D.fmt = n => { const t = D.ymd(n); return t.y + '-' + String(t.m).padStart(2, '0') + '-' + String(t.d).padStart(2, '0'); };
  D.dow = n => (((n + 4) % 7) + 7) % 7;                                           // 0 = Sunday ... 6 = Saturday (1970-01-01 was a Thursday)
  D.monthIndex = n => { const t = D.ymd(n); return t.y * 12 + t.m - 1; };
  D.fromMonthIndex = (idx, day) => D.make(Math.floor(idx / 12), (idx % 12) + 1, day);
  D.addMonths = (n, k, day) => { const t = D.ymd(n); return D.fromMonthIndex(t.y * 12 + t.m - 1 + k, day == null ? t.d : day); };
  D.monthStart = n => { const t = D.ymd(n); return D.make(t.y, t.m, 1); };
  D.monthEnd = n => { const t = D.ymd(n); return D.make(t.y, t.m, 31); };
  D.monthKey = n => { const t = D.ymd(n); return t.y + '-' + String(t.m).padStart(2, '0'); };
  D.weekStart = (n, startsOn) => n - ((D.dow(n) - (startsOn == null ? 1 : startsOn) + 7) % 7);
  D.weekEnd = (n, startsOn) => D.weekStart(n, startsOn) + 6;
  D.label = n => { const t = D.ymd(n); return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][t.m - 1] + ' ' + t.d; };
  const MON = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
  // Bank-export dates: 03/15/2026, 3/5/26, 2026-03-15, 2026/03/15, Mar 15, 2026, 15-Mar-2026. dmy:true reads 05/03/2026 as 5 March.
  D.parseLoose = function (s, dmy) {
    const t = String(s == null ? '' : s).trim().replace(/\s+\d{1,2}:\d{2}.*$/, '');
    let m = /^(\d{4})[-\/.](\d{1,2})[-\/.](\d{1,2})$/.exec(t);
    const build = (y, mo, d) => (y >= 1970 && y <= 2200 && mo >= 1 && mo <= 12 && d >= 1 && d <= D.dim(y, mo)) ? D.make(y, mo, d) : null;
    if (m) return build(+m[1], +m[2], +m[3]);
    m = /^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{2}|\d{4})$/.exec(t);
    if (m) { let y = +m[3]; if (m[3].length === 2) y += 2000; return dmy ? build(y, +m[2], +m[1]) : build(y, +m[1], +m[2]); }
    m = /^([A-Za-z]{3,9})\.?\s+(\d{1,2}),?\s+(\d{4})$/.exec(t);
    if (m && MON[m[1].slice(0, 3).toLowerCase()]) return build(+m[3], MON[m[1].slice(0, 3).toLowerCase()], +m[2]);
    m = /^(\d{1,2})[\s-]([A-Za-z]{3,9})\.?[\s-,]+(\d{4})$/.exec(t);
    if (m && MON[m[2].slice(0, 3).toLowerCase()]) return build(+m[3], MON[m[2].slice(0, 3).toLowerCase()], +m[1]);
    return null;
  };
})(CCE);

;
/* ===== engine/01-schedule.js ===== */
/* =========================================================================
   01 schedules — when does money arrive / leave?
   A schedule is a plain object:
     { freq: 'once'|'weekly'|'biweekly'|'semimonthly'|'monthly'|'yearly',
       anchor: 'YYYY-MM-DD'   // a real date the pattern is aligned to
       day: 1..31             // monthly: day of month (clamped to short months: 31st -> 28th/30th)
       days: [a, b]           // semimonthly: two days of the month (default 1 and 15)
       every: n               // monthly: every n months (2 = every other month, 6 = twice a year)
       start, end: 'YYYY-MM-DD' (inclusive)   // active range
       pauses: [{start, end}]                 // e.g. no paycheck during winter break
       shift: 'none'|'prev'|'next' }          // weekend deposits: move to Friday / Monday
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const FREQS = ['once', 'weekly', 'biweekly', 'semimonthly', 'monthly', 'yearly'];
  E.FREQS = FREQS;

  // Returns [{ day, nominal }] sorted by day, where `nominal` is the date before weekend shifting
  // and `day` is when the money actually moves. Both lie inside [from, to] for `day`.
  E.occurrences = function (sch, from, to) {
    if (!sch || from > to) return [];
    const startD = sch.start ? D.parse(sch.start) : null, endD = sch.end ? D.parse(sch.end) : null;
    const anchor = sch.anchor ? D.parse(sch.anchor) : null;
    const pauses = [];
    for (const p of sch.pauses || []) { const a = D.parse(p.start), b = D.parse(p.end); if (a !== null && b !== null) pauses.push([a, b]); }
    const lo = from - 3, hi = to + 3, raw = [];
    const monthsBetween = fn => { for (let idx = D.monthIndex(lo); idx <= D.monthIndex(hi); idx++) fn(idx); };
    switch (sch.freq) {
      case 'once': if (anchor !== null) raw.push(anchor); break;
      case 'weekly': case 'biweekly': {
        if (anchor === null) break;
        const step = sch.freq === 'weekly' ? 7 : 14;
        for (let d = anchor + Math.ceil((lo - anchor) / step) * step; d <= hi; d += step) raw.push(d);
        break;
      }
      case 'semimonthly': {
        const days = sch.days && sch.days.length ? sch.days : [1, 15];
        monthsBetween(idx => { for (const dd of days) raw.push(D.fromMonthIndex(idx, dd)); });
        break;
      }
      case 'monthly': case 'yearly': {
        const every = sch.freq === 'yearly' ? 12 : Math.max(1, sch.every | 0 || 1);
        const dom = sch.day || (anchor !== null ? D.ymd(anchor).d : 1);
        const aIdx = anchor !== null ? D.monthIndex(anchor) : 0;
        monthsBetween(idx => { if ((((idx - aIdx) % every) + every) % every === 0) raw.push(D.fromMonthIndex(idx, dom)); });
        break;
      }
      default: return [];
    }
    const out = [];
    for (const nominal of raw) {
      if (startD !== null && nominal < startD) continue;
      if (endD !== null && nominal > endD) continue;
      if (pauses.some(p => nominal >= p[0] && nominal <= p[1])) continue;
      let day = nominal;
      if (sch.shift === 'prev' || sch.shift === 'next') {
        const w = D.dow(nominal);
        if (sch.shift === 'prev') day += w === 6 ? -1 : w === 0 ? -2 : 0; else day += w === 6 ? 2 : w === 0 ? 1 : 0;
      }
      if (day >= from && day <= to) out.push({ day, nominal });
    }
    out.sort((a, b) => a.day - b.day);
    return out;
  };

  // How many cents per month does `amountCents` on this schedule represent on average? (exact rational, rounded once)
  E.monthlyEquivalent = function (sch, amountCents) {
    if (!sch) return 0;
    switch (sch.freq) {
      case 'weekly': return E.divRound(amountCents * 52, 12);
      case 'biweekly': return E.divRound(amountCents * 26, 12);
      case 'semimonthly': return amountCents * 2;
      case 'monthly': return E.divRound(amountCents, Math.max(1, sch.every | 0 || 1));
      case 'yearly': return E.divRound(amountCents, 12);
      default: return 0;       // 'once' has no monthly rate
    }
  };

  // Split a monthly amount across the days of a month so that every month adds up to EXACTLY the monthly amount.
  E.dailyShare = function (monthlyCents, day) {
    if (!monthlyCents) return 0;
    const t = D.ymd(day), n = D.dim(t.y, t.m), k = t.d - 1;
    return Math.floor(monthlyCents * (k + 1) / n) - Math.floor(monthlyCents * k / n);
  };
})(CCE);

;
/* ===== engine/02-model.js ===== */
/* =========================================================================
   02 model — the v3 "plan": data shapes, validation, migration, backup files
   -------------------------------------------------------------------------
   Three independent ideas describe how much to trust any financial input
   (the spec keeps these separate on purpose):
     source      WHERE it came from      'user' | 'detected' | 'estimated' | 'demo'
     verified    HAS THE STUDENT CHECKED  true | false  (amount and date)
     reliability HOW SURE is the future   'certain' | 'likely' | 'uncertain'
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;

  /* ---------- vocabulary ---------- */
  // kind: 'bill'      scheduled things that are modelled as dated obligations (rent, phone, tuition…)
  //       'essential' everyday needs that vary (groceries, gas, health) — money is RESERVED for them
  //       'flexible'  everything the student can choose to cut (dining out, fun, shopping…)
  E.CATEGORIES = {
    'Housing': 'bill', 'Utilities': 'bill', 'Phone': 'bill', 'Insurance': 'bill', 'Tuition & fees': 'bill', 'Debt payment': 'bill', 'Subscriptions': 'bill',
    'Groceries': 'essential', 'Transportation': 'essential', 'Health': 'essential', 'School supplies': 'essential', 'Fees': 'essential',
    'Dining out': 'flexible', 'Entertainment': 'flexible', 'Shopping': 'flexible', 'Personal': 'flexible', 'Travel': 'flexible', 'Other': 'flexible'
  };
  E.catKind = c => E.CATEGORIES[c] || 'flexible';
  E.INCOME_TYPES = ['job', 'workstudy', 'aid', 'scholarship', 'family', 'gig', 'other'];
  E.OBLIGATION_KINDS = ['bill', 'tuition', 'debt', 'subscription', 'oneTime', 'other'];
  E.GOAL_TYPES = ['emergency', 'purchase', 'trip', 'savings', 'other'];
  E.GOAL_STATUSES = ['active', 'paused', 'done'];
  E.FLOWS = ['spend', 'income', 'aid', 'refund', 'transfer', 'card_payment'];
  E.LIVING = ['On campus', 'Off campus', 'Living with family', 'Other'];
  const SOURCES = ['user', 'detected', 'estimated', 'demo'], RELIABILITY = ['certain', 'likely', 'uncertain'], PERIOD_KINDS = ['semester', 'break', 'summer'];
  const BAD_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
  const LIMIT = { cents: 1e9, tx: 12000, items: 150, goals: 40 };

  E.DEFAULT_SETTINGS = {
    scenario: 'cautious',          // which scenario drives headline warnings
    weekStartsOn: 1,               // 1 = Monday
    irregularLowFactorPct: 70,     // cautious pay for irregular income with no history = 70% of typical (an assumption, shown to the student)
    cautiousLateDays: 14,          // cautious scenario: "likely" aid/scholarship money arrives this many days late
    staleDays: 10,                 // balance older than this is labelled "not recently verified"
    minHorizonDays: 30,            // (legacy, no longer changes the semester forecast; kept so old backups still load)
    safetyHorizonDays: 30,         // the separate financial-SAFETY look-ahead is never shorter than this (it never changes the semester numbers)
    defaultHorizonDays: 120,       // when no semester dates are known
    reserveFixedCents: 0,          // OPTIONAL money to still have on the last day of the term, on top of the cushion (student's choice; 0 = off)
    reserveBridge: false,          // OPTIONAL: also keep what bills + essentials will need until the next aid refund arrives
    reserveBridgeMaxDays: 60,      // the bridge never looks further ahead than this when no refund is scheduled
    discretionaryFloorWeeklyCents: null   // the student's weekly minimum for discretionary spending (null = use the suggestion in 14-goals)
  };
  E.DEMO_SCHOOL = 'University of Kentucky';   // default school for demonstration data

  /* ---------- tiny normalizers ---------- */
  const cents = (v, dflt, lo, hi) => {
    let n = Number(v);
    if (!Number.isFinite(n)) return dflt;
    n = Math.round(n);
    return E.clamp(n, lo == null ? 0 : lo, hi == null ? LIMIT.cents : hi);
  };
  const oneOf = (v, list, dflt) => (list.indexOf(v) >= 0 ? v : dflt);
  const isoOrEmpty = v => { const d = D.parse(v); return d === null ? '' : D.fmt(d); };
  const bool = v => v === true;

  function normSchedule(s, warn, label) {
    if (!s || typeof s !== 'object') return null;
    const freq = oneOf(s.freq, E.FREQS, null);
    if (!freq) { warn(label + ': unknown repeat pattern'); return null; }
    const out = { freq };
    const a = D.parse(s.anchor); if (a !== null) out.anchor = D.fmt(a);
    const day = Math.round(Number(s.day)); if (day >= 1 && day <= 31) out.day = day;
    if (Array.isArray(s.days)) {
      const ds = [...new Set(s.days.map(x => Math.round(Number(x))).filter(x => x >= 1 && x <= 31))].slice(0, 2);
      if (ds.length === 2) out.days = ds.sort((x, y) => x - y);
    }
    const ev = Math.round(Number(s.every)); if (ev >= 2 && ev <= 12) out.every = ev;
    const st = D.parse(s.start), en = D.parse(s.end);
    if (st !== null) out.start = D.fmt(st);
    if (en !== null) out.end = D.fmt(en);
    if (Array.isArray(s.pauses)) {
      const ps = [];
      for (const p of s.pauses.slice(0, 10)) { const x = p && D.parse(p.start), y = p && D.parse(p.end); if (x !== null && y !== null && x <= y) ps.push({ start: D.fmt(x), end: D.fmt(y) }); }
      if (ps.length) out.pauses = ps;
    }
    if (s.shift === 'prev' || s.shift === 'next') out.shift = s.shift;
    const needsAnchor = freq === 'once' || freq === 'weekly' || freq === 'biweekly' || freq === 'yearly' || (freq === 'monthly' && out.every);
    if (needsAnchor && !out.anchor) { warn(label + ': needs a date'); return null; }
    if (freq === 'monthly' && !out.day && !out.anchor) { warn(label + ': needs a day of the month'); return null; }
    return out;
  }

  function uniqueId(raw, prefix, taken, plan) {
    let id = E.safeStr(raw, 40);
    if (!id || taken.has(id)) id = E.newId(plan, prefix, taken);
    taken.add(id);
    return id;
  }
  const eachItem = (arr, max, fn) => {
    if (!Array.isArray(arr)) return [];
    const out = [];
    for (const x of arr.slice(0, max)) if (x && typeof x === 'object' && !Array.isArray(x)) { const r = fn(x); if (r) out.push(r); }
    return out;
  };

  /* ---------- the plan ---------- */
  // Accepts anything (a saved plan, an import, a partial object) and returns { plan, warnings } in a clean, safe shape.
  // Throws only if `raw` is not an object at all. Items it cannot repair are dropped and reported.
  E.normalizePlan = function (raw) {
    if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('That is not a Campus Compass plan.');
    const warnings = [], warn = m => { if (warnings.length < 60) warnings.push(m); };
    const m = raw.meta && typeof raw.meta === 'object' ? raw.meta : {};
    const a = raw.account && typeof raw.account === 'object' ? raw.account : {};
    const st = raw.settings && typeof raw.settings === 'object' ? raw.settings : {};
    const S0 = E.DEFAULT_SETTINGS;
    const plan = {
      app: 'campus-compass', version: 3,
      seq: cents(raw.seq, 0, 0, 1e9),
      meta: { name: E.safeStr(m.name, 40), school: E.safeStr(m.school, 80), living: oneOf(m.living, E.LIVING, 'Off campus'), demo: E.safeStr(m.demo, 30) },
      periods: [], horizon: { endPeriodId: E.safeStr(raw.horizon && raw.horizon.endPeriodId, 40) },
      account: {
        balanceCents: cents(a.balanceCents, 0, -LIMIT.cents, LIMIT.cents), asOf: isoOrEmpty(a.asOf), seq: cents(a.seq, 0, 0, 1e9),
        // savingsCents is the savings-account balance at the end of savingsAsOf ('' = date unknown, e.g. an older backup). See E.savingsSummary.
        savingsCents: cents(a.savingsCents, 0), savingsAsOf: isoOrEmpty(a.savingsAsOf), savingsSeq: cents(a.savingsSeq, 0, 0, 1e9), savingsSpendable: bool(a.savingsSpendable), cushionCents: cents(a.cushionCents, 10000)
      },
      incomes: [], obligations: [], budgets: [], goals: [], transactions: [],
      settings: {
        scenario: oneOf(st.scenario, ['cautious', 'expected'], S0.scenario), weekStartsOn: st.weekStartsOn === 0 ? 0 : 1,
        irregularLowFactorPct: cents(st.irregularLowFactorPct, S0.irregularLowFactorPct, 30, 100), cautiousLateDays: cents(st.cautiousLateDays, S0.cautiousLateDays, 0, 60),
        staleDays: cents(st.staleDays, S0.staleDays, 3, 60), minHorizonDays: cents(st.minHorizonDays, S0.minHorizonDays, 14, 120), safetyHorizonDays: cents(st.safetyHorizonDays, S0.safetyHorizonDays, 14, 120), defaultHorizonDays: cents(st.defaultHorizonDays, S0.defaultHorizonDays, 30, 400),
        reserveFixedCents: cents(st.reserveFixedCents, S0.reserveFixedCents, 0, LIMIT.cents), reserveBridge: bool(st.reserveBridge), reserveBridgeMaxDays: cents(st.reserveBridgeMaxDays, S0.reserveBridgeMaxDays, 14, 180),
        discretionaryFloorWeeklyCents: st.discretionaryFloorWeeklyCents == null || st.discretionaryFloorWeeklyCents === '' ? null : cents(st.discretionaryFloorWeeklyCents, null, 0, LIMIT.cents)
      },
      resolutions: [], matchDecisions: [],
      ignored: Array.isArray(raw.ignored) ? raw.ignored.slice(0, 300).map(s => E.safeStr(s, 80)).filter(Boolean) : [],
      catRules: {}, checkIns: [], answered: Array.isArray(raw.answered) ? raw.answered.slice(0, 100).map(s => E.safeStr(s, 60)) : [],
      dismissed: Array.isArray(raw.dismissed) ? raw.dismissed.slice(0, 100).map(s => E.safeStr(s, 60)) : []
    };
    if (raw.catRules && typeof raw.catRules === 'object' && !Array.isArray(raw.catRules)) {
      for (const k of Object.keys(raw.catRules).slice(0, 400)) if (!BAD_KEYS.has(k) && E.CATEGORIES[raw.catRules[k]]) plan.catRules[E.safeStr(k, 60)] = raw.catRules[k];
    }
    const ids = new Set();

    plan.periods = eachItem(raw.periods, 12, x => {
      const s = D.parse(x.start), e = D.parse(x.end);
      if (s === null || e === null || e < s) { warn('A semester with unusable dates was removed.'); return null; }
      return { id: uniqueId(x.id, 'pd', ids, plan), name: E.safeStr(x.name, 40, 'Semester') || 'Semester', start: D.fmt(s), end: D.fmt(e), kind: oneOf(x.kind, PERIOD_KINDS, 'semester'), verified: bool(x.verified) };
    }).sort((p, q) => (p.start < q.start ? -1 : 1));

    plan.incomes = eachItem(raw.incomes, LIMIT.items, x => {
      const type = oneOf(x.type, E.INCOME_TYPES, 'other'), amount = cents(x.amountCents, 0);
      const schedule = normSchedule(x.schedule, warn, 'Income "' + E.safeStr(x.name, 30) + '"');
      return {
        id: uniqueId(x.id, 'in', ids, plan), name: E.safeStr(x.name, 60, 'Income') || 'Income', type, schedule, amountCents: amount,
        lowCents: x.lowCents == null ? null : Math.min(amount, cents(x.lowCents, amount)), irregular: bool(x.irregular),
        source: oneOf(x.source, SOURCES, 'user'), verified: bool(x.verified), reliability: oneOf(x.reliability, RELIABILITY, type === 'family' ? 'uncertain' : 'likely'),
        delayDays: cents(x.delayDays, 0, 0, 120), note: E.safeStr(x.note, 120),
        employer: E.safeStr(x.employer, 60), payerHints: Array.isArray(x.payerHints) ? x.payerHints.slice(0, 6).map(h => E.safeStr(h, 40)).filter(Boolean) : []
      };
    });
    plan.obligations = eachItem(raw.obligations, LIMIT.items, x => {
      const amount = cents(x.amountCents, 0);
      const schedule = normSchedule(x.schedule, warn, 'Bill "' + E.safeStr(x.name, 30) + '"');
      return {
        id: uniqueId(x.id, 'ob', ids, plan), name: E.safeStr(x.name, 60, 'Bill') || 'Bill', category: E.CATEGORIES[x.category] ? x.category : 'Other',
        kind: oneOf(x.kind, E.OBLIGATION_KINDS, 'bill'), schedule, amountCents: amount, highCents: x.highCents == null ? null : Math.max(amount, cents(x.highCents, amount)),
        essential: x.essential !== false, source: oneOf(x.source, SOURCES, 'user'), verified: bool(x.verified), reliability: oneOf(x.reliability, RELIABILITY, 'certain'),
        vendorKey: E.safeStr(x.vendorKey, 60), note: E.safeStr(x.note, 120)
      };
    });
    const seenCat = new Set();
    plan.budgets = eachItem(raw.budgets, 40, x => {
      if (!E.CATEGORIES[x.category] || seenCat.has(x.category)) return null;
      seenCat.add(x.category);
      return {
        category: x.category, approvedCents: x.approvedCents == null ? null : cents(x.approvedCents, 0), recommendedCents: x.recommendedCents == null ? null : cents(x.recommendedCents, 0),
        source: oneOf(x.source, ['student', 'accepted', 'thin', 'generic', 'starter', 'history'], 'starter')
      };
    });
    // savedCents is what the student said was saved for the goal at the end of savedAsOf (entries with a higher seq on that day come after it).
    // Progress grows only through transactions linked to the goal (goalId), never because a contribution was scheduled. See 14-goals.
    let goalIndex = 0;
    plan.goals = eachItem(raw.goals, LIMIT.goals, x => {
      goalIndex++;
      let contribution = null;
      if (x.contribution && typeof x.contribution === 'object') {
        const sch = normSchedule(x.contribution.schedule, warn, 'Savings plan for "' + E.safeStr(x.name, 30) + '"');
        if (sch && cents(x.contribution.amountCents, 0) > 0) contribution = { amountCents: cents(x.contribution.amountCents, 0), schedule: sch };
      }
      return {
        id: uniqueId(x.id, 'gl', ids, plan), name: E.safeStr(x.name, 60, 'Goal') || 'Goal', type: oneOf(x.type, E.GOAL_TYPES, 'other'),
        targetCents: cents(x.targetCents, 0), savedCents: cents(x.savedCents, 0), savedAsOf: isoOrEmpty(x.savedAsOf), savedSeq: cents(x.savedSeq, 0, 0, 1e9),
        dueDate: isoOrEmpty(x.dueDate), contribution, priority: cents(x.priority, goalIndex, 1, 99), status: oneOf(x.status, E.GOAL_STATUSES, 'active')
      };
    });
    const goalIds = new Set(plan.goals.map(g => g.id));
    const seenTx = new Set();
    plan.transactions = eachItem(raw.transactions, LIMIT.tx, x => {
      const d = D.parse(x.date), amt = Math.round(Number(x.amountCents));
      if (d === null || !Number.isSafeInteger(amt) || amt === 0 || Math.abs(amt) > LIMIT.cents) return null;
      let id = E.safeStr(x.id, 40); if (!id || seenTx.has(id)) id = E.newId(plan, 'tx', seenTx);
      seenTx.add(id);
      const flow = oneOf(x.flow, E.FLOWS, amt < 0 ? 'spend' : 'income');
      return {
        id, date: D.fmt(d), amountCents: amt, desc: E.safeStr(x.desc, 120, 'Transaction') || 'Transaction', flow, category: E.CATEGORIES[x.category] ? x.category : (flow === 'spend' ? 'Other' : ''),
        // account: 'checking' moves the spendable balance; 'card' (a credit-card statement) counts as spending but does NOT move checking
        // until the card is paid (that payment is a separate 'card_payment' row in checking).
        account: oneOf(x.account, ['checking', 'card'], 'checking'),
        source: oneOf(x.source, ['manual', 'import', 'demo'], 'import'), batch: E.safeStr(x.batch, 30), seq: cents(x.seq, 0, 0, 1e9), matchedTo: E.safeStr(x.matchedTo, 40), locked: bool(x.locked), review: bool(x.review),
        // the savings goal this transfer was confirmed for (out of checking = money saved, into checking = money taken back out)
        goalId: flow === 'transfer' && goalIds.has(E.safeStr(x.goalId, 40)) ? E.safeStr(x.goalId, 40) : ''
      };
    });
    const txIds = new Set(plan.transactions.map(t => t.id));
    for (const t of plan.transactions) if (t.matchedTo && !txIds.has(t.matchedTo)) t.matchedTo = '';
    plan.checkIns = eachItem(raw.checkIns, 200, x => { const d = D.parse(x.date); return d === null ? null : { date: D.fmt(d), actualCents: cents(x.actualCents, 0, -LIMIT.cents), projectedCents: cents(x.projectedCents, 0, -LIMIT.cents) }; });
    // "Not paid yet" / "not received yet" answers the student gave about scheduled items: key = kind|itemId|YYYY-MM-DD
    plan.resolutions = eachItem(raw.resolutions, 400, x => (typeof x.key === 'string' && /^(income|bill|savings)\|[^\s|][^|]{0,60}\|\d{4}-\d{2}-\d{2}$/.test(x.key) && x.status === 'unpaid' && D.parse(x.key.slice(x.key.lastIndexOf('|') + 1)) !== null) ? { key: x.key, status: 'unpaid' } : null);
    // "This deposit IS / is NOT that scheduled paycheck": key = income|incomeId|YYYY-MM-DD (the scheduled date), plus the transaction it is about
    plan.matchDecisions = eachItem(raw.matchDecisions, 400, x => (typeof x.key === 'string' && /^income\|[^\s|][^|]{0,60}\|\d{4}-\d{2}-\d{2}$/.test(x.key) && (x.decision === 'same' || x.decision === 'different') && txIds.has(E.safeStr(x.txId, 40))) ? { key: x.key, txId: E.safeStr(x.txId, 40), decision: x.decision } : null);
    plan.seq = Math.max(plan.seq, ...plan.transactions.map(t => t.seq), ...plan.goals.map(g => g.savedSeq), plan.account.seq, plan.account.savingsSeq);
    if (plan.horizon.endPeriodId && !plan.periods.some(p => p.id === plan.horizon.endPeriodId)) plan.horizon.endPeriodId = '';
    return { plan, warnings };
  };

  E.newPlan = function (opts) {
    opts = opts || {};
    const raw = { meta: opts.meta || {}, periods: opts.periods || [], account: Object.assign({ balanceCents: 0, asOf: '' }, opts.account || {}), incomes: opts.incomes || [], obligations: opts.obligations || [], budgets: opts.budgets || [], goals: opts.goals || [], transactions: opts.transactions || [], settings: opts.settings || {} };
    return E.normalizePlan(raw).plan;
  };

  /* ---------- semester dates ---------- */
  // PROVISIONAL guesses so the app can start working immediately. The student is asked to confirm them (verified:false).
  E.defaultPeriods = function (todayDay) {
    const t = D.ymd(todayDay), mk = (id, name, kind, y1, m1, d1, y2, m2, d2) => ({ id, name, kind, start: D.fmt(D.make(y1, m1, d1)), end: D.fmt(D.make(y2, m2, d2)), verified: false });
    if (t.m >= 8) return [mk('pd-fall', 'Fall ' + t.y, 'semester', t.y, 8, 20, t.y, 12, 12), mk('pd-winter', 'Winter break', 'break', t.y, 12, 13, t.y + 1, 1, 11), mk('pd-spring', 'Spring ' + (t.y + 1), 'semester', t.y + 1, 1, 12, t.y + 1, 5, 8)];
    return [mk('pd-spring', 'Spring ' + t.y, 'semester', t.y, 1, 12, t.y, 5, 8), mk('pd-summer', 'Summer', 'summer', t.y, 5, 9, t.y, 8, 19), mk('pd-fall', 'Fall ' + t.y, 'semester', t.y, 8, 20, t.y, 12, 12)];
  };
  // The SEMESTER horizon: from today to the last day of the chosen (or current/next) semester, and nothing else. It is never silently
  // lengthened, because every semester number (room, daily pace, one-time purchase limit) is measured against this date. What happens AFTER
  // it (rent over winter break, the wait for the next aid refund) is a separate "safety outlook" (see E.safetyOutlook), shown beside it.
  E.horizonInfo = function (plan, today) {
    const byId = plan.horizon && plan.horizon.endPeriodId ? plan.periods.find(p => p.id === plan.horizon.endPeriodId) : null;
    let period = byId && D.parse(byId.end) >= today ? byId : plan.periods.find(p => p.kind === 'semester' && D.parse(p.end) >= today) || null;
    let end, basis = 'semester', provisional = false;
    if (period) { end = D.parse(period.end); provisional = !period.verified; }
    else { end = today + plan.settings.defaultHorizonDays; basis = 'default'; provisional = true; }      // no usable semester dates: a labelled default
    return { endDay: end, days: end - today, basis, provisional, extended: false, period: period ? period.name : '' };
  };

  // Scheduled vs cautious arrival for one income. Aid/scholarship "likely" money is counted cautiousLateDays late in the cautious view.
  E.incomeArrivalDays = function (plan, inc, fromDay) {
    if (!inc || !inc.schedule || !(inc.amountCents > 0) || inc.reliability === 'uncertain') return null;
    const start = fromDay == null ? 0 : fromDay;
    const o = E.occurrences(inc.schedule, start, start + 400)[0];
    if (!o) return null;
    const aidLike = inc.type === 'aid' || inc.type === 'scholarship';
    const scheduledDay = o.day + (inc.delayDays || 0);
    const cautiousDay = scheduledDay + (aidLike && inc.reliability === 'likely' ? (plan.settings.cautiousLateDays || 0) : 0);
    return { name: inc.name, type: inc.type, scheduledDay, cautiousDay, amountCents: inc.amountCents, aidLike, differs: cautiousDay !== scheduledDay };
  };

  // Shared date strip for every tab: semester end vs after-term safety window (and scheduled vs cautious aid).
  E.planDateContext = function (plan, T, so) {
    const hz = E.horizonInfo(plan, T), H = hz.endDay;
    const outlook = so && so.ok ? so : null;
    const bridge = outlook && outlook.bridge ? outlook.bridge : null;
    let aid = null;
    for (const inc of plan.incomes) {
      const a = E.incomeArrivalDays(plan, inc, H + 1);
      if (!a || !a.aidLike) continue;
      if (!aid || a.scheduledDay < aid.scheduledDay) aid = a;
    }
    const aidScheduledDay = aid ? aid.scheduledDay : null;
    const aidCautiousDay = bridge && bridge.endedBy === 'aid' ? bridge.aidDay : (aid ? aid.cautiousDay : null);
    return {
      today: T, termEndDay: H, termName: hz.period || '', termProvisional: !!hz.provisional, termBasis: hz.basis,
      semesterRangeLabel: D.label(T) + ' → ' + D.label(H),
      bridgeStartDay: bridge ? bridge.startDay : null, bridgeEndDay: bridge ? bridge.endDay : null,
      bridgeRangeLabel: bridge ? D.label(bridge.startDay) + ' → ' + D.label(bridge.endDay) : '',
      aidName: aid ? aid.name : (bridge ? bridge.aidName : ''),
      aidScheduledDay, aidCautiousDay,
      aidLabel: aidCautiousDay != null
        ? (aidScheduledDay != null && aidScheduledDay !== aidCautiousDay
          ? (aid ? aid.name : 'Next refund') + ' scheduled ' + D.label(aidScheduledDay) + ', counted ' + D.label(aidCautiousDay) + ' in the cautious view'
          : (aid ? aid.name : 'Next refund') + ' on ' + D.label(aidCautiousDay))
        : ''
    };
  };

  /* ---------- confidence labels ---------- */
  // Plain-language status for any income / obligation / period. Keeps source, verification and reliability separate underneath.
  E.confidenceOf = function (item, todayDay) {
    const has = item && item.schedule && (item.schedule.anchor || item.schedule.day) && item.amountCents > 0;
    if (!item || !has) return { label: 'Unknown', source: item && item.source, verified: !!(item && item.verified), reliability: item && item.reliability, note: 'The amount or date is missing.' };
    const future = item.schedule.freq === 'once' && todayDay != null && D.parse(item.schedule.anchor) > todayDay;
    let label;
    if (item.source === 'detected' && !item.verified) label = 'Detected';
    else if (item.source === 'estimated' && !item.verified) label = 'Estimated';
    else if (item.verified && future && (item.type === 'aid' || item.type === 'scholarship' || item.type === 'family' || item.type === 'job')) label = 'Scheduled';
    else if (item.verified) label = 'Confirmed';
    else label = 'Estimated';
    const notes = { Confirmed: 'You verified this amount and date.', Detected: 'Found in your transactions; not confirmed yet.', Estimated: 'A rough number; not verified.', Scheduled: 'Expected on a set date but has not arrived. Not treated as guaranteed.' };
    return { label, source: item.source, verified: !!item.verified, reliability: item.reliability, note: notes[label] };
  };

  /* ---------- backup files ---------- */
  // Wrap a plan in a self-describing file. `exportedAt` is passed in by the app (the engine has no clock).
  // opts.sampleViewDay is optional and stays outside the checksummed plan, so older files still open.
  // Only a fixed sample scenario (Maya's judge dates) is written; a real plan keeps using the live date.
  E.exportPlan = function (plan, exportedAt, opts) {
    opts = opts || {};
    const data = E.normalizePlan(plan).plan;
    const file = { app: 'campus-compass', format: 'campus-compass-backup', version: 3, exportedAt: E.safeStr(exportedAt, 30), checksum: E.hash32(JSON.stringify(data)), data };
    const hinted = typeof opts.sampleViewDay === 'string' ? D.parse(opts.sampleViewDay) : null;
    const keep = hinted != null && typeof E.fixedSampleViewDay === 'function' ? E.fixedSampleViewDay(data, hinted) : null;
    if (keep != null) file.sampleViewDay = D.fmt(keep);
    return JSON.stringify(file, null, 2);
  };
  // A short fingerprint of the plan's saved content (the same data a backup file holds). Equal signatures mean a file
  // saved earlier still matches what is on screen, so the app knows whether there are unsaved changes.
  E.planSignature = function (plan) {
    try { return plan ? E.hash32(JSON.stringify(E.normalizePlan(plan).plan)) : null; } catch (e) { return null; }
  };
  // Never throws and never touches the caller's current plan: returns { ok:true, plan, warnings, from } or { ok:false, errors }.
  E.importPlan = function (text, opts) {
    try {
      if (typeof text !== 'string' || !text.trim()) return { ok: false, errors: ['That file is empty.'] };
      if (text.length > 12e6) return { ok: false, errors: ['That file is too large to be a Campus Compass backup.'] };
      let obj;
      try { obj = JSON.parse(text); } catch (e) { return { ok: false, errors: ['That file is not valid JSON, so it cannot be a Campus Compass backup.'] }; }
      if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return { ok: false, errors: ['That file does not contain a Campus Compass backup.'] };
      if (obj.format === 'campus-compass-backup' && obj.app === 'campus-compass') {
        if (obj.version !== 3 || !obj.data || typeof obj.data !== 'object') return { ok: false, errors: ['That backup is from a newer or unknown version of Campus Compass.'] };
        if (typeof obj.checksum === 'string' && obj.checksum !== E.hash32(JSON.stringify(obj.data))) return { ok: false, errors: ['That backup looks damaged (its checksum does not match). Your current data was not changed.'] };
        const r = E.normalizePlan(obj.data);
        let sampleViewDay = null;
        if (typeof obj.sampleViewDay === 'string') { const d = D.parse(obj.sampleViewDay); if (d !== null) sampleViewDay = d; }
        return { ok: true, plan: r.plan, warnings: r.warnings, from: 'v3', sampleViewDay };
      }
      if (obj.accounts && (obj.income || obj.expenses) && (obj.version === 2 || obj.version == null)) {
        const today = opts && opts.today;
        if (typeof today !== 'number') return { ok: false, errors: ['Internal error: importing an older backup needs today\'s date.'] };
        const r = E.migrateV2(obj, today);
        return { ok: true, plan: r.plan, warnings: r.notes.concat(r.warnings), from: 'v2' };
      }
      return { ok: false, errors: ['That file is not a Campus Compass backup.'] };
    } catch (e) {
      return { ok: false, errors: ['That file could not be read safely: ' + E.safeStr(e && e.message, 120)] };
    }
  };

  /* ---------- migration from the v2 prototype ---------- */
  const OLD_FREQ_PER_MONTH = { weekly: [52, 12], biweekly: [26, 12], semimonthly: [2, 1], monthly: [1, 1], semester: [1, 6], yearly: [1, 12], once: [0, 1] };
  const PHONE_RE = /phone|verizon|t-?mobile|at&t|att wireless|mint mobile|cricket|visible/i;
  function oldMonth(s, last) { const m = /^(\d{4})-(\d{2})$/.exec(String(s || '')); if (!m) return ''; const y = +m[1], mo = +m[2]; if (mo < 1 || mo > 12) return ''; return D.fmt(D.make(y, mo, last ? 31 : 1)); }
  function oldSchedule(x) {
    const date = D.parse(x.date);
    const base = { start: oldMonth(x.start, false) || undefined, end: oldMonth(x.end, true) || undefined };
    let s;
    switch (x.freq) {
      case 'once': s = { freq: 'once', anchor: x.date }; break;
      case 'weekly': case 'biweekly': s = { freq: x.freq, anchor: x.date }; break;
      case 'semimonthly': s = { freq: 'semimonthly' }; break;
      case 'semester': s = { freq: 'monthly', every: 6, anchor: x.date, day: date !== null ? D.ymd(date).d : undefined }; break;
      case 'yearly': s = { freq: 'yearly', anchor: x.date }; break;
      default: s = { freq: 'monthly', day: Math.round(Number(x.dueDay)) || (date !== null ? D.ymd(date).d : 1) };
    }
    return Object.assign(s, base);
  }
  // Turn an old v2 state (dollars, kind/amount transactions, debts, net worth…) into a v3 plan.
  // Investments, other assets and debt balances are intentionally dropped; required debt payments become bills.
  E.migrateV2 = function (old, todayDay) {
    const notes = [], note = m => { if (notes.length < 30) notes.push(m); };
    const p = old.profile || {}, a = old.accounts || {};
    const incomes = [], obligations = [], goals = [];
    const typeMap = { 'Job': 'job', 'Work-study': 'workstudy', 'Financial aid': 'aid', 'Scholarship': 'scholarship', 'Family support': 'family', 'Gig / side hustle': 'gig', 'Other': 'other' };
    for (const x of Array.isArray(old.income) ? old.income.slice(0, 60) : []) {
      if (!x || typeof x !== 'object') continue;
      const type = typeMap[x.type] || 'other';
      incomes.push({
        id: x.id, name: x.name, type, schedule: oldSchedule(x), amountCents: E.toCents(x.amount), irregular: !!(p.irregular && (type === 'job' || type === 'gig')),
        source: x.estimated ? 'estimated' : 'user', verified: !x.estimated, reliability: x.estimated ? 'uncertain' : type === 'family' ? 'likely' : 'likely'
      });
    }
    const budgetSum = {};
    for (const x of Array.isArray(old.expenses) ? old.expenses.slice(0, 150) : []) {
      if (!x || typeof x !== 'object') continue;
      let cat = x.category;
      if (cat === 'Dining') cat = 'Dining out';
      else if (cat === 'Utilities' && PHONE_RE.test(String(x.name) + ' ' + String(x.vendorKey))) cat = 'Phone';
      else if (cat === 'Education') cat = x.kind === 'variable' ? 'School supplies' : 'Tuition & fees';
      if (!E.CATEGORIES[cat]) cat = 'Other';
      if (x.kind === 'variable') {
        const f = OLD_FREQ_PER_MONTH[x.freq] || [1, 1];
        budgetSum[cat] = (budgetSum[cat] || 0) + E.divRound(E.toCents(x.amount) * f[0], f[1]);
      } else {
        obligations.push({
          id: x.id, name: x.name, category: cat, kind: cat === 'Subscriptions' ? 'subscription' : cat === 'Tuition & fees' ? 'tuition' : x.freq === 'once' ? 'oneTime' : 'bill', schedule: oldSchedule(x),
          amountCents: E.toCents(x.amount), essential: cat !== 'Subscriptions', source: 'user', verified: true, reliability: 'certain', vendorKey: x.vendorKey
        });
      }
    }
    for (const x of Array.isArray(old.debts) ? old.debts.slice(0, 60) : []) {
      if (!x || typeof x !== 'object') continue;
      const pay = Number(x.min) > 0 ? Number(x.min) : Number(x.futureMin) > 0 ? Number(x.futureMin) : 0;
      if (pay <= 0) { note('"' + E.safeStr(x.name, 40) + '" had no required payment, so it was not carried over.'); continue; }
      const sch = { freq: 'monthly', day: Math.round(Number(x.dueDay)) || 1 };
      if (/^\d{4}-\d{2}$/.test(String(x.repayStart || ''))) sch.start = oldMonth(x.repayStart, false);
      obligations.push({ id: x.id, name: String(x.name) + ' payment', category: 'Debt payment', kind: 'debt', schedule: sch, amountCents: E.toCents(pay), essential: true, source: 'user', verified: true, reliability: 'certain' });
    }
    if (Array.isArray(old.debts) && old.debts.length) note('Debt balances and payoff strategy were removed. Required monthly payments were kept as bills.');
    if (num0(a.investments) || num0(a.other)) note('Investments and other assets are no longer tracked.');
    for (const x of Array.isArray(old.goals) ? old.goals.slice(0, 40) : []) {
      if (!x || typeof x !== 'object') continue;
      if (x.type === 'debt') { note('The debt goal "' + E.safeStr(x.name, 40) + '" was not carried over.'); continue; }
      const monthly = E.toCents(x.monthly);
      goals.push({
        id: x.id, name: x.name, type: ['emergency', 'purchase', 'trip', 'savings'].indexOf(x.type) >= 0 ? x.type : 'other', targetCents: E.toCents(x.target), savedCents: E.toCents(x.saved),
        savedAsOf: D.fmt(todayDay), dueDate: x.deadline, contribution: monthly > 0 ? { amountCents: monthly, schedule: { freq: 'monthly', day: 1 } } : null
      });
    }
    const budgets = Object.keys(budgetSum).map(c => ({ category: c, approvedCents: budgetSum[c], source: 'student' }));
    const txs = [];
    for (const x of Array.isArray(old.transactions) ? old.transactions.slice(0, 8000) : []) {
      if (!x || typeof x !== 'object' || D.parse(x.date) === null) continue;
      const amt = E.toCents(Math.abs(Number(x.amount))); if (!amt) continue;
      const signed = x.kind === 'income' ? amt : -amt;
      const c = E.classify(String(x.desc || ''), signed);
      let flow = c.flow, category = c.category;
      if (flow === 'spend') { let oc = x.category === 'Dining' ? 'Dining out' : x.category === 'Education' ? 'School supplies' : x.category; if (oc === 'Utilities' && PHONE_RE.test(String(x.desc))) oc = 'Phone'; if (E.CATEGORIES[oc]) category = oc; }
      txs.push({ id: x.id, date: x.date, amountCents: signed, desc: x.desc, flow, category, source: x.src === 'demo' ? 'demo' : 'import', seq: 0 });
    }
    const periods = E.defaultPeriods(todayDay);
    note('Semester dates were guessed. Please confirm them.');
    note('Your checking balance was treated as accurate on today\'s date. Please do a check-in to confirm it.');
    const raw = {
      meta: { name: p.name, school: old.demo ? E.DEMO_SCHOOL : p.school, living: p.living, demo: old.demo ? 'v2-demo' : '' }, periods, account: { balanceCents: E.toCents(a.checking), asOf: D.fmt(todayDay), savingsCents: E.toCents(a.savings), savingsAsOf: D.fmt(todayDay), cushionCents: E.toCents(a.buffer) },
      incomes, obligations, budgets, goals, transactions: txs, ignored: old.ignored, catRules: {}, answered: old.answered, dismissed: old.dismissed
    };
    const r = E.normalizePlan(raw);
    return { plan: r.plan, warnings: r.warnings, notes };
  };
  function num0(v) { const n = Number(v); return Number.isFinite(n) ? n : 0; }

  /* ---------- sanity checks the UI can show (does not change anything) ---------- */
  E.validatePlan = function (plan, todayDay) {
    const errors = [], warnings = [];
    const anchor = D.parse(plan.account.asOf);
    if (anchor === null) errors.push({ code: 'no_balance_date', msg: 'Enter your current checking balance to start.' });
    else if (todayDay != null && anchor > todayDay) warnings.push({ code: 'balance_in_future', msg: 'Your balance is dated in the future; it will be treated as today.' });
    else if (todayDay != null && todayDay - anchor > plan.settings.staleDays) warnings.push({ code: 'stale_balance', msg: 'Your balance was last verified ' + (todayDay - anchor) + ' days ago. A quick check-in will make the numbers more reliable.' });
    for (const x of plan.incomes) if (!x.schedule) warnings.push({ code: 'income_no_date', id: x.id, msg: '"' + x.name + '" has no date, so it is not counted.' });
    for (const x of plan.obligations) if (!x.schedule) warnings.push({ code: 'bill_no_date', id: x.id, msg: '"' + x.name + '" has no due date, so it is not counted.' });
    const sv = E.savingsSummary(plan);
    if (sv.overAllocatedCents > 0) warnings.push({ code: 'goal_savings_exceed_savings', msg: 'Your goals hold ' + E.fmt(sv.allocatedCents) + ' but your savings balance is ' + E.fmt(sv.savingsNowCents) + '. Update your savings balance or the amounts saved for your goals.' });
    if (!plan.periods.length) warnings.push({ code: 'no_semester', msg: 'No semester dates yet; forecasting a default ' + plan.settings.defaultHorizonDays + ' days.' });
    return { ok: errors.length === 0, errors, warnings };
  };
})(CCE);

;
/* ===== engine/03-ledger.js ===== */
/* =========================================================================
   03 ledger — transactions: classify, parse CSV, import without double counting
   -------------------------------------------------------------------------
   Every transaction has a SIGNED amount in cents: money in is +, money out is −.
   `flow` says what KIND of movement it is, because they are treated very differently:
     spend         a purchase or bill payment            -> counts as spending
     income        a paycheck / deposit                  -> income
     aid           financial aid, scholarship, loan money-> income-like, never "recurring paycheck"
     refund        a merchant refund                     -> reduces spending in its category
     transfer      moving your own money between accounts-> NOT spending, NOT income
     card_payment  paying a credit card from checking    -> NOT spending (the card purchases are the spending)
   Every row changes the checking balance; only `spend` and `refund` rows describe spending habits.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;

  /* ---------- merchant names ---------- */
  const VK_STOP = new Set('usa us inc llc co com www the store online pos debit card purchase payment pmt pmts autopay recurring ach withdrawal checkcard visa mc sq tst to from of at for and web ppd id'.split(' '));
  E.vendorKey = function (desc) {
    let t = String(desc || '').toLowerCase();
    t = t.replace(/purchase authorized on \d+\/\d+/g, ' ').replace(/[^a-z&'\s]/g, ' ');
    return t.split(/\s+/).filter(x => x.length > 1 && !VK_STOP.has(x)).slice(0, 2).join(' ');
  };
  const tokens = s => String(s || '').toLowerCase().replace(/[^a-z0-9&\s]/g, ' ').split(/\s+/).filter(w => w.length >= 3 && !VK_STOP.has(w));
  E.namesOverlap = (a, b) => { const A = tokens(a), B = tokens(b); return A.some(w => B.indexOf(w) >= 0); };

  /* ---------- what kind of movement is this, and what category? ---------- */
  const RE = {
    cardPay: /credit card payment|card payment|capital one (online |mobile )?(payment|pmt)|discover (e-?payment|payment)|amex (e-?payment|payment)|chase credit crd|citi (card|autopay)|payment thank you|autopay.*card|barclay|synchrony/i,
    transfer: /\btransfer\b|\bxfer\b|to savings|from savings|online transfer|internal transfer|mobile transfer|\bown account\b/i,
    aid: /financial aid|fin aid|bursar|student refund|refund.*(univ|college)|(univ|college).*refund|direct loan|dept\.? of ed|ed fin|\bpell\b|\bkees\b|kheaa|scholarship|grant disbursement|work.?study/i,
    refund: /refund|return|reversal|credit adj|chargeback|cash ?back/i,
    payroll: /payroll|direct dep|dir dep|salary|paycheck|wages|\badp\b|gusto|paychex|payout|tips?\b/i,
    peer: /zelle|venmo|cash ?app|paypal.*(from|transfer)|apple cash/i
  };
  E.DESC_PATTERNS = RE;
  const CAT_RULES = [
    ['Fees', /overdraft|\bnsf\b|service charge|atm fee|late fee|finance charge|interest charge|monthly maintenance|foreign transaction|annual fee|returned item/i],
    ['Debt payment', /student loan|navient|nelnet|mohela|aidvantage|great lakes|edfinancial|loan payment|affirm|klarna|afterpay|car payment|auto loan/i],
    ['Tuition & fees', /tuition|bursar|registrar|student accounts|university billing|\bkctcs\b|course fee|lab fee|parking permit/i],
    ['Housing', /\brent\b|landlord|apartment|\bapts?\b|property (mgmt|management)|housing|\bdorm\b|residence hall|\blease\b|mortgage|meal plan/i],
    ['Insurance', /insurance|geico|state farm|progressive|allstate|farmers ins/i],
    ['Phone', /verizon|at&t|att wireless|t-?mobile|mint mobile|cricket wireless|visible wireless|\bphone\b/i],
    ['Utilities', /lg&e|louisville gas|kentucky utilities|duke energy|\bwater\b|sewer|electric|utility|utilities|spectrum|comcast|xfinity|internet|\bcable\b|\bmsd\b/i],
    ['Subscriptions', /netflix|spotify|hulu|disney ?\+?|\bhbo\b|\bmax\.com|peacock|paramount|youtube ?(premium|tv|music)|apple\.com\/bill|itunes|icloud|prime video|amazon prime|crunchyroll|audible|patreon|adobe|dropbox|google (one|storage)|microsoft 365|chatgpt|openai|subscription|membership|planet fitness|\bgym\b|fitness|peloton|new york times|nytimes/i],
    ['School supplies', /bookstore|textbook|chegg|pearson|cengage|course hero|coursera|scantron|office supplies|staples/i],
    ['Dining out', /restaurant|cafe|coffee|starbucks|dunkin|chick-?fil|mcdonald|wendy|burger|taco|chipotle|pizza|papa john|domino|subway|panera|skyline|cane'?s|raising|\bbbq\b|grill|diner|doordash|uber ?eats|grubhub|brewing|sushi|wing|\bkfc\b|popeyes|jimmy john|jersey mike|sonic|dairy queen|ice cream|bakery|boba|krispy|insomnia|waffle|pub\b|tavern/i],
    ['Groceries', /kroger|aldi|walmart (super|neighborhood)|wal-?mart|meijer|trader joe|whole foods|costco|sam'?s club|grocer|food lion|publix|save-a-lot|lidl|farmers market|supermarket|instacart/i],
    ['Transportation', /shell|speedway|thorntons|\bbp\b|exxon|marathon|chevron|sunoco|valero|\bgas\b|fuel|\buber\b|lyft|tarc|parking|\btoll|transit|valvoline|jiffy lube|autozone|o'?reilly|car wash|\bdmv\b|tire/i],
    ['Health', /pharmacy|\bcvs\b|walgreens|rite aid|clinic|medical|doctor|dental|dentist|hospital|urgent care|vision|optical|therapy|counsel|health|\brx\b/i],
    ['Personal', /salon|barber|haircut|great clips|sport clips|nail|\bspa\b|laundry|dry clean/i],
    ['Entertainment', /cinema|regal|\bamc\b|movie|theater|theatre|concert|ticketmaster|stubhub|\bsteam\b|playstation|xbox|nintendo|bowling|arcade|museum|golf|live nation|churchill downs|kings island|topgolf|fandango|eventbrite|distill|escape room/i],
    ['Travel', /airline|\bdelta\b|american air|southwest|united air|airbnb|hotel|marriott|hilton|expedia|booking\.com|vrbo|amtrak|greyhound|spirit air|frontier air|motel|resort|cruise|rental car|enterprise rent|hertz/i],
    ['Shopping', /amazon|amzn|target|best buy|walmart\.com|ebay|etsy|shein|nike|adidas|old navy|h&m|zara|american eagle|hollister|urban outfitters|kohl|tj ?maxx|marshalls|\bross\b|ulta|sephora|bath & body|dollar (tree|general)|family dollar|five below|home depot|lowe'?s|ikea|apple store|gamestop|michaels|hobby lobby|temu|aliexpress|\bstore\b|\bshop\b|\bmall\b/i]
  ];
  function categoryOf(desc, rules) {
    const key = E.vendorKey(desc);
    if (rules && key && Object.prototype.hasOwnProperty.call(rules, key) && E.CATEGORIES[rules[key]]) return rules[key];
    for (const r of CAT_RULES) if (r[1].test(desc)) return r[0];
    return 'Other';
  }
  E.categoryOf = categoryOf;

  // -> { flow, category, review }   (review = "we are guessing; the student may want to check")
  E.classify = function (desc, signedCents, catRules) {
    const t = String(desc || '');
    if (signedCents < 0) {
      if (RE.cardPay.test(t)) return { flow: 'card_payment', category: 'Debt payment', review: false };
      if (RE.transfer.test(t)) return { flow: 'transfer', category: '', review: false };
      const c = categoryOf(t, catRules);
      return { flow: 'spend', category: c, review: c === 'Other' };
    }
    if (RE.transfer.test(t) || RE.cardPay.test(t)) return { flow: 'transfer', category: '', review: false };
    if (RE.aid.test(t)) return { flow: 'aid', category: '', review: false };
    if (RE.refund.test(t)) return { flow: 'refund', category: categoryOf(t, catRules), review: false };
    if (RE.payroll.test(t)) return { flow: 'income', category: '', review: false };
    return { flow: 'income', category: '', review: true };          // an unexplained deposit: do not assume it is spendable income
  };

  /* ---------- reading bank CSV files ---------- */
  function parseCSV(str) {
    const rows = []; let row = [], field = '', q = false;
    str = String(str).replace(/^\uFEFF/, '');
    for (let i = 0; i < str.length; i++) {
      const ch = str[i];
      if (ch === '"') { if (q && str[i + 1] === '"') { field += '"'; i++; } else q = !q; }
      else if (ch === ',' && !q) { row.push(field); field = ''; }
      else if ((ch === '\n' || ch === '\r') && !q) { if (ch === '\r' && str[i + 1] === '\n') i++; row.push(field); if (row.some(v => v.trim())) rows.push(row); row = []; field = ''; }
      else field += ch;
    }
    row.push(field); if (row.some(v => v.trim())) rows.push(row);
    return rows;
  }
  E.parseCSV = parseCSV;
  function findHeader(rows) {
    const norm = h => String(h || '').toLowerCase().replace(/[^a-z0-9\/ ]/g, ' ').replace(/\s+/g, ' ').trim();
    for (let r = 0; r < Math.min(rows.length, 25); r++) {
      const h = rows[r].map(norm);
      const idx = (...exact) => { for (const e of exact) { const i = h.indexOf(e); if (i >= 0) return i; } return -1; };
      const has = (re, skip) => h.findIndex((x, i) => re.test(x) && !(skip && skip.indexOf(i) >= 0));
      let date = idx('date', 'transaction date', 'trans date', 'posted date', 'posting date', 'post date'); if (date < 0) date = has(/date/);
      let desc = idx('description', 'merchant', 'payee', 'name', 'details', 'transaction description', 'memo', 'narrative'); if (desc < 0) desc = has(/descr|merchant|payee/);
      let amt = idx('amount', 'transaction amount', 'amt'); if (amt < 0) amt = has(/^amount|amount$/);
      const debit = has(/^(debit|debits|withdrawal|withdrawals|money out|paid out)$|withdraw/, [amt]);
      const credit = has(/^(credit|credits|deposit|deposits|money in|paid in)$|deposit/, [amt, debit]);
      const type = idx('type', 'transaction type', 'dr/cr'), cat = idx('category');
      if (date >= 0 && desc >= 0 && (amt >= 0 || debit >= 0 || credit >= 0)) return { row: r, date, desc, amt, debit, credit, type, cat, headers: rows[r] };
    }
    return null;
  }
  // Reads a statement and returns a PREVIEW (nothing is saved). The caller lets the student review mapping/sign/categories.
  // opts: { signMode:'auto'|'neg'|'pos', dateOrder:'auto'|'mdy'|'dmy', mapping:{date,desc,amt,debit,credit,type,cat} (column numbers) }
  E.parseStatement = function (text, opts) {
    opts = opts || {};
    const rows = parseCSV(text);
    if (rows.length < 2) throw new Error('That file looks empty. A statement needs a header row plus at least one transaction.');
    let hd = findHeader(rows);
    if (opts.mapping) { const m = opts.mapping; hd = Object.assign({ row: hd ? hd.row : 0, headers: rows[hd ? hd.row : 0], amt: -1, debit: -1, credit: -1, type: -1, cat: -1 }, hd || {}, m); }
    if (!hd || hd.date == null || hd.date < 0 || hd.desc == null || hd.desc < 0 || (hd.amt < 0 && hd.debit < 0 && hd.credit < 0)) throw new Error('Could not find Date, Description, and Amount columns. Check that those headers exist (separate Debit/Credit columns also work), or choose the columns yourself.');
    const data = rows.slice(hd.row + 1, hd.row + 1 + 12000);
    // date order: a first part above 12 means day-first; a second part above 12 means month-first
    let dmy = opts.dateOrder === 'dmy', ambiguous = false;
    if (!opts.dateOrder || opts.dateOrder === 'auto') {
      let a12 = false, b12 = false, anyAmb = false;
      for (const r of data) { const m = /^(\d{1,2})[\/.-](\d{1,2})[\/.-]\d{2,4}$/.exec(String(r[hd.date] || '').trim()); if (m) { if (+m[1] > 12) a12 = true; if (+m[2] > 12) b12 = true; if (+m[1] <= 12 && +m[2] <= 12 && m[1] !== m[2]) anyAmb = true; } }
      dmy = a12 && !b12; ambiguous = !a12 && !b12 && anyAmb;
    }
    const bad = { date: 0, desc: 0, amount: 0 }, parsed = [];
    for (const r of data) {
      const d = D.parseLoose(r[hd.date], dmy), desc = String(r[hd.desc] || '').replace(/\s+/g, ' ').trim();
      let a = null;
      if (hd.amt >= 0) a = E.parseMoney(r[hd.amt]);
      else {
        const out = E.parseMoney(r[hd.debit]), inc = hd.credit >= 0 ? E.parseMoney(r[hd.credit]) : null;
        if (out && out !== 0) a = -Math.abs(out); else if (inc && inc !== 0) a = Math.abs(inc);
      }
      if (d === null) { bad.date++; continue; }
      if (!desc) { bad.desc++; continue; }
      if (a === null || a === 0) { bad.amount++; continue; }
      parsed.push({ day: d, desc: desc.slice(0, 120), a, type: hd.type >= 0 ? String(r[hd.type] || '').toLowerCase() : '', src: hd.cat >= 0 ? String(r[hd.cat] || '') : '' });
    }
    if (!parsed.length) throw new Error('No usable rows were found. Check that dates look like 03/15/2026 and amounts are numbers.');
    let mode = 'columns', note = hd.amt >= 0 ? '' : 'Used separate Debit / Credit columns.';
    if (hd.amt >= 0) {
      const neg = parsed.filter(p => p.a < 0).length, pos = parsed.length - neg;
      const sm = opts.signMode || 'auto';
      let expenseNeg = sm === 'neg' ? true : sm === 'pos' ? false : (neg && pos) ? neg >= pos : neg > 0;
      mode = expenseNeg ? 'negative' : 'positive';
      if (sm === 'auto') note = neg && pos ? (expenseNeg ? 'Negative amounts look like spending.' : 'Positive amounts look like spending (like a credit-card export).') : expenseNeg ? 'All amounts are negative, so they were treated as spending.' : 'All amounts are positive, so they were treated as spending. If these are deposits, switch the setting.';
      const typeUseful = hd.type >= 0 && neg === 0 && parsed.some(p => /credit|deposit|payment|refund|return|debit|sale|purchase/.test(p.type));
      if (typeUseful && sm === 'auto') { mode = 'type'; note = 'The Type column was used to tell spending from deposits.'; }
      for (const p of parsed) {
        if (mode === 'type') { const inflow = /credit|deposit|refund|return|payment/.test(p.type); p.signed = inflow ? Math.abs(p.a) : -Math.abs(p.a); if (/^payment/.test(p.type)) p.forceTransfer = true; }
        else p.signed = expenseNeg ? p.a : -p.a;
      }
    } else for (const p of parsed) p.signed = p.a;
    const out = parsed.map(p => ({ date: D.fmt(p.day), desc: p.desc, amountCents: p.signed, srcCategory: p.src, forceTransfer: !!p.forceTransfer }));
    const ds = out.map(r => r.date).sort();
    return {
      rows: out, skipped: bad, total: data.length, note, mode, first: ds[0], last: ds[ds.length - 1], dateOrder: dmy ? 'dmy' : 'mdy', ambiguousDates: ambiguous,
      mapping: { date: hd.date, desc: hd.desc, amt: hd.amt, debit: hd.debit, credit: hd.credit, type: hd.type, cat: hd.cat }, headers: hd.headers,
      totalOutCents: E.sum(out.filter(r => r.amountCents < 0), r => -r.amountCents), totalInCents: E.sum(out.filter(r => r.amountCents > 0), r => r.amountCents)
    };
  };

  /* ---------- the ledger ---------- */
  // Rows that count: duplicates that were matched to a bank row are hidden (they are kept so a delete can restore them).
  E.activeTxs = plan => plan.transactions.filter(t => !t.matchedTo);
  E.cashTxs = plan => plan.transactions.filter(t => !t.matchedTo && t.account === 'checking');
  const fingerprint = t => t.date + '|' + t.amountCents + '|' + t.account + '|' + E.vendorKey(t.desc);
  E.fingerprint = fingerprint;

  // Does this transaction look like payment of a bill/obligation the student already listed?
  E.obligationLike = function (plan, t) {
    const vk = E.vendorKey(t.desc);
    return plan.obligations.some(o => (o.vendorKey && vk && o.vendorKey === vk) || (o.vendorKey && E.namesOverlap(o.vendorKey, t.desc)) || E.namesOverlap(o.name, t.desc));
  };

  // Add statement rows to the ledger. Re-importing the same file adds nothing. Returns a NEW plan; the old one is untouched.
  // opts: { account:'checking'|'card', batch, today (day number) }
  E.importTransactions = function (plan, rows, opts) {
    opts = opts || {};
    const p = E.clone(plan), account = opts.account === 'card' ? 'card' : 'checking', today = opts.today;
    const have = {};
    for (const t of p.transactions) if (t.source !== 'manual') have[fingerprint(t)] = (have[fingerprint(t)] || 0) + 1;
    const seen = {}, existingIds = new Set(p.transactions.map(t => t.id)), added = [], res = { duplicates: 0, skippedFuture: 0, linked: [], suggestions: [], flowCounts: {}, review: 0 };
    for (const r of rows) {
      const day = D.parse(r.date);
      if (day === null || !Number.isSafeInteger(r.amountCents) || r.amountCents === 0) continue;
      if (typeof today === 'number' && day > today) { res.skippedFuture++; continue; }
      let c = r.forceTransfer ? { flow: 'transfer', category: '', review: false } : E.classify(r.desc, r.amountCents, p.catRules), overridden = false;
      // The student's own decision for this row (from the import review) beats the automatic guess, but only if it makes sense for the sign of the amount.
      const okFlows = r.amountCents < 0 ? ['spend', 'transfer', 'card_payment'] : ['income', 'aid', 'refund', 'transfer'];
      if (r.overrideFlow && okFlows.indexOf(r.overrideFlow) >= 0) {
        const cat = (r.overrideFlow === 'spend' || r.overrideFlow === 'refund') ? (E.CATEGORIES[r.overrideCategory] ? r.overrideCategory : (c.category || categoryOf(r.desc, p.catRules))) : r.overrideFlow === 'card_payment' ? 'Debt payment' : '';
        c = { flow: r.overrideFlow, category: cat, review: false }; overridden = true;
      } else if (r.overrideCategory && E.CATEGORIES[r.overrideCategory] && c.flow === 'spend') { c = { flow: 'spend', category: r.overrideCategory, review: false }; overridden = true; }
      if (account === 'card') {                           // a card statement: purchases are spending; payments on the card are transfers
        if (r.amountCents > 0 && c.flow !== 'refund') { c.flow = 'transfer'; c.category = ''; }
      }
      const tx = { id: '', date: r.date, amountCents: r.amountCents, desc: E.safeStr(r.desc, 120, 'Transaction'), flow: c.flow, category: c.category, account, source: 'import', batch: E.safeStr(opts.batch, 30), seq: 0, matchedTo: '', locked: overridden && c.flow === 'spend', review: c.review };
      const k = fingerprint(tx);
      seen[k] = (seen[k] || 0) + 1;
      if (seen[k] <= (have[k] || 0)) { res.duplicates++; continue; }
      tx.id = E.newId(p, 'tx', existingIds); tx.seq = ++p.seq;
      p.transactions.push(tx); added.push(tx);
      res.flowCounts[tx.flow] = (res.flowCounts[tx.flow] || 0) + 1; if (tx.review) res.review++;
    }
    // link manually-logged purchases to the bank rows that now cover them (so nothing is counted twice)
    const manual = p.transactions.filter(t => t.source === 'manual' && !t.matchedTo && t.account === account);
    const usedManual = new Set();
    for (const tx of added) {
      let best = null;
      for (const m of manual) {
        if (usedManual.has(m.id) || m.amountCents !== tx.amountCents) continue;
        const gap = Math.abs(D.parse(m.date) - D.parse(tx.date));
        if (gap > 5) continue;
        const sure = gap <= 3 && (!m.desc || m.desc === 'Transaction' || E.namesOverlap(m.desc, tx.desc) || (m.category && m.category === tx.category));
        if (!best || gap < best.gap) best = { m, gap, sure };
      }
      if (best) {
        usedManual.add(best.m.id);
        if (best.sure) { best.m.matchedTo = tx.id; if (best.m.goalId && tx.flow === 'transfer') tx.goalId = best.m.goalId; if (!tx.locked && best.m.category && tx.flow === 'spend' && best.m.locked) { tx.category = best.m.category; tx.locked = true; } res.linked.push({ manualId: best.m.id, importId: tx.id }); }
        else res.suggestions.push({ manualId: best.m.id, importId: tx.id, gapDays: best.gap });
      }
    }
    res.added = added.length;
    return Object.assign(res, { plan: p });
  };
  // Confirm or reject a suggested manual<->bank match.
  // A goal the student confirmed on the typed entry moves to the bank row that replaces it.
  E.linkManual = function (plan, manualId, importId) {
    const p = E.clone(plan), m = p.transactions.find(t => t.id === manualId), b = p.transactions.find(t => t.id === importId);
    if (m && b) { m.matchedTo = importId; if (m.goalId && !b.goalId && b.flow === 'transfer') b.goalId = m.goalId; }
    return p;
  };

  // direction 'out' (default): amountCents is a positive amount spent. direction 'in': money received.
  E.addManualTx = function (plan, t, today) {
    const p = E.clone(plan), amt = Math.abs(Math.round(Number(t.amountCents)));
    if (!Number.isSafeInteger(amt) || amt <= 0) return { ok: false, error: 'Enter an amount above $0.', plan };
    const day = t.date ? D.parse(t.date) : today;
    if (day === null || day === undefined) return { ok: false, error: 'That date is not valid.', plan };
    if (typeof today === 'number' && day > today) return { ok: false, error: 'Purchases can only be logged for today or earlier.', plan };
    const dirIn = t.direction === 'in', signed = dirIn ? amt : -amt, desc = E.safeStr(t.desc, 120);
    let flow, category;
    if (dirIn) { flow = oneOf(t.flow, ['income', 'aid', 'refund', 'transfer'], 'income'); category = flow === 'refund' && E.CATEGORIES[t.category] ? t.category : ''; }
    else {
      flow = oneOf(t.flow, ['spend', 'transfer', 'card_payment'], 'spend');
      category = flow === 'spend' ? (E.CATEGORIES[t.category] ? t.category : (desc ? categoryOf(desc, p.catRules) : 'Other')) : flow === 'card_payment' ? 'Debt payment' : '';
    }
    const tx = { id: E.newId(p, 'tx', new Set(p.transactions.map(x => x.id))), date: D.fmt(day), amountCents: signed, desc: desc || 'Transaction', flow, category, account: 'checking', source: 'manual', batch: '', seq: 0, matchedTo: '', locked: !!E.CATEGORIES[t.category], review: false };
    tx.seq = ++p.seq;
    p.transactions.push(tx);
    return { ok: true, plan: p, tx };
  };
  function oneOf(v, list, d) { return list.indexOf(v) >= 0 ? v : d; }

  // patch may contain: date (ISO), amountCents (signed), desc, category, flow, account
  E.editTx = function (plan, id, patch) {
    const p = E.clone(plan), t = p.transactions.find(x => x.id === id);
    if (!t) return { ok: false, error: 'That transaction no longer exists.', plan };
    if (patch.date !== undefined) { if (D.parse(patch.date) === null) return { ok: false, error: 'That date is not valid.', plan }; t.date = patch.date; }
    if (patch.amountCents !== undefined) { const a = Math.round(Number(patch.amountCents)); if (!Number.isSafeInteger(a) || a === 0) return { ok: false, error: 'Enter an amount other than $0.', plan }; t.amountCents = a; }
    if (patch.desc !== undefined) t.desc = E.safeStr(patch.desc, 120, 'Transaction') || 'Transaction';
    if (patch.flow !== undefined && E.FLOWS.indexOf(patch.flow) >= 0) t.flow = patch.flow;
    if (patch.account !== undefined && (patch.account === 'checking' || patch.account === 'card')) t.account = patch.account;
    if (patch.category !== undefined && (E.CATEGORIES[patch.category] || patch.category === '')) { t.category = patch.category; t.locked = true; t.review = false; }
    return { ok: true, plan: p, tx: t };
  };
  // Deleting a bank row re-activates any manual entry that had been linked to it.
  E.deleteTx = function (plan, id) {
    const p = E.clone(plan), n = p.transactions.length;
    p.transactions = p.transactions.filter(t => t.id !== id);
    for (const t of p.transactions) if (t.matchedTo === id) t.matchedTo = '';
    return { ok: p.transactions.length < n, plan: p };
  };
  // "Always categorise Starbucks as Dining out": remembers the rule and re-labels unlocked rows from that merchant.
  E.setCategoryRule = function (plan, desc, category) {
    const p = E.clone(plan), key = E.vendorKey(desc);
    if (!key || !E.CATEGORIES[category]) return { plan: p, changed: 0 };
    p.catRules[key] = category;
    let changed = 0;
    for (const t of p.transactions) if (t.flow === 'spend' && !t.locked && E.vendorKey(t.desc) === key && t.category !== category) { t.category = category; changed++; }
    return { plan: p, changed };
  };
})(CCE);

;
/* ===== engine/04-baseline.js ===== */
/* =========================================================================
   04 baseline — learn the student's real habits from their transactions
   -------------------------------------------------------------------------
   * Recurring-charge detection (bills / subscriptions) — DETECTED, never auto-confirmed.
   * Paycheck detection (frequency, typical and low amounts).
   * Spending baseline per category, with unusual one-off purchases kept out.
   * Budget recommendations. They are suggestions only: `approvedCents` changes
     ONLY through setBudget / acceptRecommendations (the student's action).
   Bills that are listed (or detected) as recurring are removed from the everyday
   baseline so the same money is never counted in two places.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const SUB_WORDS = /netflix|spotify|hulu|disney|hbo|\bmax\b|peacock|paramount|youtube|apple|icloud|prime|audible|patreon|adobe|dropbox|google|microsoft|chatgpt|openai|crunchyroll|fitness|gym|peloton|subscription|membership|insurance|verizon|at&t|t-mobile|spectrum|xfinity|comcast|lg&e|\brent\b|loan/i;
  const habit = c => E.catKind(c) !== 'bill';                       // essential + flexible categories are "habits", not bills

  function cadenceOf(gaps) {
    const med = E.median(gaps);
    if (med >= 6 && med <= 8) return { c: 'weekly', step: 7, tol: 2 };
    if (med >= 13 && med <= 16) return { c: 'biweekly', step: 14, tol: 2 };
    if (med >= 27 && med <= 34) return { c: 'monthly', step: 30.4, tol: 4 };
    if (med >= 355 && med <= 375) return { c: 'yearly', step: 365, tol: 10 };
    return null;
  }
  function nextAfter(lastDay, cad, today) {
    if (cad.c === 'weekly' || cad.c === 'biweekly') { let n = lastDay; while (n < today) n += cad.step; return n; }
    const ms = cad.c === 'yearly' ? 12 : 1, dom = D.ymd(lastDay).d;
    let k = 1, n = D.addMonths(lastDay, ms, dom);
    while (n < today && k < 400) { k++; n = D.addMonths(lastDay, k * ms, dom); }
    return n;
  }
  const dayOf = t => D.parse(t.date);

  /* ---------- recurring bills & subscriptions (outflows) ---------- */
  // Returns candidates; each says how sure we are and why. `matched` = id of a bill the student already listed.
  E.detectRecurring = function (plan, today) {
    const groups = {};
    for (const t of E.activeTxs(plan)) {
      if (t.amountCents >= 0 || (t.flow !== 'spend' && t.flow !== 'card_payment') || dayOf(t) > today) continue;
      const k = E.vendorKey(t.desc); if (!k) continue;
      (groups[t.flow + '|' + k] = groups[t.flow + '|' + k] || []).push(t);
    }
    const out = [];
    for (const gk of Object.keys(groups)) {
      const arr = groups[gk]; if (arr.length < 2) continue;
      const key = gk.slice(gk.indexOf('|') + 1), flow = gk.split('|')[0];
      const sorted = arr.slice().sort((a, b) => dayOf(a) - dayOf(b));
      const days = sorted.map(dayOf), gaps = [];
      for (let i = 1; i < days.length; i++) gaps.push(days[i] - days[i - 1]);
      const cad = cadenceOf(gaps); if (!cad) continue;
      if ((cad.c === 'weekly' || cad.c === 'biweekly') && sorted.length < 3) continue;
      const fit = gaps.filter(g => Math.abs(g - cad.step) <= cad.tol).length / gaps.length;
      if (fit < 0.6) continue;
      const amts = sorted.map(t => -t.amountCents), med = E.median(amts), last = sorted[sorted.length - 1];
      const cat = last.category || (flow === 'card_payment' ? 'Debt payment' : 'Other');
      const varTol = cat === 'Utilities' ? 0.3 : 0.15;
      const stable = amts.filter(a => Math.abs(a - med) <= Math.max(200, varTol * med)).length / amts.length;
      if (stable < 0.7) continue;
      const lastAmt = amts[amts.length - 1], nearlyIdentical = amts.every(a => Math.abs(a - lastAmt) <= Math.max(50, 0.02 * a));
      if (flow === 'spend' && habit(cat) && !(cad.c === 'monthly' && sorted.length >= 3 && nearlyIdentical)) continue;      // habits are not bills
      const lastDay = days[days.length - 1];
      if (today - lastDay > cad.step * 1.6 + 5) continue;                                                              // stopped a while ago
      const next = nextAfter(lastDay, cad, today);
      const pts = (sorted.length >= 4 ? 2 : sorted.length === 3 ? 1 : 0) + (SUB_WORDS.test(last.desc) ? 1 : 0) + (fit === 1 && nearlyIdentical ? 1 : 0);
      const confidence = pts >= 3 ? 'high' : pts >= 2 ? 'medium' : 'low';
      const amountCents = cat === 'Utilities' || !nearlyIdentical ? Math.round(E.median(amts.slice(-3))) : lastAmt;
      const reason = 'Seen ' + sorted.length + ' times, about ' + (cad.c === 'weekly' ? 'every week' : cad.c === 'biweekly' ? 'every 2 weeks' : cad.c === 'monthly' ? 'every month' : 'every year') + (nearlyIdentical ? ', same amount each time' : ', similar amounts');
      const sch = { freq: cad.c === 'yearly' ? 'yearly' : cad.c, anchor: D.fmt(next) };
      if (cad.c === 'monthly') sch.day = D.ymd(lastDay).d;
      const o = plan.obligations.find(x => (x.vendorKey && x.vendorKey === key) || E.namesOverlap(x.name, key) || E.namesOverlap(x.vendorKey, key) ||
        (x.category === cat && x.schedule && x.schedule.freq === sch.freq && Math.abs(x.amountCents - amountCents) <= Math.max(100, amountCents * 0.08) && x.schedule.day && Math.abs(x.schedule.day - D.ymd(next).d) <= 3));
      out.push({
        key, flow, name: E.safeStr(last.desc.replace(/\s*[#*]?\s*\d{3,}.*$/, ''), 48) || key, category: cat, cadence: cad.c, amountCents, nextDay: next, schedule: sch, count: sorted.length, confidence, reason,
        txIds: sorted.map(t => t.id), matched: o ? o.id : '', ignored: plan.ignored.indexOf('out|' + key) >= 0, source: 'detected', verified: false,
        priceChange: amts.length > 1 && cat !== 'Utilities' && Math.abs(lastAmt - amts[amts.length - 2]) / amts[amts.length - 2] > 0.03 ? { fromCents: amts[amts.length - 2], toCents: lastAmt } : null
      });
    }
    return out.sort((a, b) => a.nextDay - b.nextDay);
  };

  /* ---------- paychecks (inflows) ---------- */
  E.detectIncome = function (plan, today) {
    const groups = {};
    for (const t of E.cashTxs(plan)) {
      if (t.flow !== 'income' || t.amountCents <= 0 || dayOf(t) > today) continue;
      const k = E.vendorKey(t.desc); if (!k) continue;
      (groups[k] = groups[k] || []).push(t);
    }
    const out = [];
    for (const key of Object.keys(groups)) {
      const arr = groups[key].sort((a, b) => dayOf(a) - dayOf(b)); if (arr.length < 3) continue;
      const days = arr.map(dayOf), gaps = []; for (let i = 1; i < days.length; i++) gaps.push(days[i] - days[i - 1]);
      const cad = cadenceOf(gaps); if (!cad || cad.c === 'yearly') continue;
      const recent = arr.slice(-6).map(t => t.amountCents), med = Math.round(E.median(recent)), lo = Math.min.apply(null, recent), hi = Math.max.apply(null, recent);
      const variation = med > 0 ? (hi - lo) / med : 0;
      const last = arr[arr.length - 1], next = nextAfter(days[days.length - 1], cad, today + 1);
      const sch = { freq: cad.c, anchor: D.fmt(next) }; if (cad.c === 'monthly') sch.day = D.ymd(days[days.length - 1]).d;
      const inc = plan.incomes.find(i => E.namesOverlap(i.name, last.desc) || (i.schedule && i.schedule.freq === cad.c && Math.abs(i.amountCents - med) <= Math.max(500, med * 0.15)));
      out.push({ key, name: E.safeStr(last.desc, 48), cadence: cad.c, typicalCents: med, lowCents: lo, highCents: hi, variation, irregular: variation > 0.25, count: arr.length, nextDay: next, schedule: sch, matched: inc ? inc.id : '', source: 'detected', verified: false });
    }
    return out;
  };

  /* ---------- everyday spending baseline ---------- */
  E.baseline = function (plan, today, det) {
    det = det || E.detectRecurring(plan, today);
    const skip = new Set();
    for (const r of det) if (!r.ignored) for (const id of r.txIds) skip.add(id);
    const act = E.activeTxs(plan).filter(t => dayOf(t) <= today);
    const res = { today, coverageDays: 0, windowStart: null, windowEnd: null, staleDays: null, status: 'provisional', txCount: 0, categories: {}, essentialMonthlyCents: 0, flexibleMonthlyCents: 0, unusual: [], cardPaymentsCents: 0, hasCardStatement: act.some(t => t.account === 'card'), cardSpendingHidden: false };
    if (!act.length) return res;
    const all = act.map(dayOf), firstDay = Math.min.apply(null, all), lastDay = Math.max.apply(null, all);
    const wEnd = today - lastDay <= 3 ? today : lastDay, wStart = Math.max(firstDay, wEnd - 55);
    res.windowStart = wStart; res.windowEnd = wEnd; res.coverageDays = wEnd - wStart + 1; res.staleDays = today - lastDay;
    const inWin = act.filter(t => { const d = dayOf(t); return d >= wStart && d <= wEnd; });
    res.cardPaymentsCents = E.sum(inWin.filter(t => t.flow === 'card_payment' && t.account === 'checking'), t => -t.amountCents);
    const cats = {};
    for (const t of inWin) {
      if ((t.flow !== 'spend' && t.flow !== 'refund') || !t.category || !habit(t.category) || skip.has(t.id) || E.obligationLike(plan, t)) continue;
      (cats[t.category] = cats[t.category] || []).push(t);
    }
    const days = Math.max(7, res.coverageDays);
    for (const c of Object.keys(cats)) {
      const spend = cats[c].filter(t => t.flow === 'spend'), refunds = E.sum(cats[c].filter(t => t.flow === 'refund' && t.amountCents > 0), t => t.amountCents);
      const amts = spend.map(t => -t.amountCents), med = E.median(amts);
      const isUnusual = t => { const a = -t.amountCents; return a >= 30000 || (spend.length >= 3 && a >= Math.max(10000, 4 * med)); };
      const unusual = spend.filter(isUnusual), usual = spend.filter(t => !isUnusual(t));
      for (const t of unusual) res.unusual.push({ id: t.id, date: t.date, desc: t.desc, amountCents: -t.amountCents, category: c });
      const usualTotal = Math.max(0, E.sum(usual, t => -t.amountCents) - refunds), total = Math.max(0, E.sum(spend, t => -t.amountCents) - refunds);
      const daily = usualTotal / days;
      const weeks = [0, 0, 0, 0, 0, 0, 0, 0];
      let wkend = 0, last28 = 0, prev28 = 0;
      for (const t of usual) { const age = wEnd - dayOf(t), a = -t.amountCents; if (age >= 0 && age < 56) weeks[Math.floor(age / 7)] += a; const w = D.dow(dayOf(t)); if (w === 0 || w === 6) wkend += a; if (age < 28) last28 += a; else if (age < 56) prev28 += a; }
      const monthly = Math.round(daily * 30.4375), spendDays = spend.map(dayOf);
      res.categories[c] = {
        firstDay: spendDays.length ? Math.min.apply(null, spendDays) : null, lastDay: spendDays.length ? Math.max.apply(null, spendDays) : null, usualCount: usual.length,
        category: c, kind: E.catKind(c), txCount: spend.length, totalCents: total, usualCents: usualTotal, unusualCents: total - usualTotal, dailyCents: daily, weeklyCents: Math.round(daily * 7), monthlyCents: monthly,
        weeklySeries: weeks.slice(0, Math.min(8, Math.ceil(res.coverageDays / 7))).reverse(), weekendShare: usualTotal > 0 ? wkend / (E.sum(usual, t => -t.amountCents)) : 0,
        trendPct: res.coverageDays >= 56 && prev28 > 0 ? Math.round((last28 - prev28) / prev28 * 100) : null
      };
      res.txCount += spend.length;
      if (E.catKind(c) === 'essential') res.essentialMonthlyCents += monthly; else res.flexibleMonthlyCents += monthly;
    }
    res.status = res.coverageDays >= 28 && res.txCount >= 8 ? 'estimated' : res.coverageDays >= 14 && res.txCount >= 3 ? 'limited' : 'provisional';
    const outflow = E.sum(inWin.filter(t => t.amountCents < 0 && t.account === 'checking'), t => -t.amountCents);
    res.cardSpendingHidden = !res.hasCardStatement && outflow > 0 && res.cardPaymentsCents / outflow > 0.25;
    return res;
  };

  /* ---------- budgets: approved vs recommended vs actual ---------- */
  const roundTo5 = c => Math.round(c / 500) * 500;
  // Category-specific EVIDENCE. The overall 14-day / 3-purchase thresholds are only the starting guideline; what a category's history can support
  // depends on how often that kind of thing is normally bought.
  //   strong    enough to treat as the student's habit (and to suggest a budget)       frequent: >= 28 days and >= 6 purchases
  //   moderate  usable habit and suggestion, flagged as limited                        frequent: >= 14 days and >= 3 purchases
  //   thin      a FORWARD-ONLY cautious estimate, always labelled provisional           frequent: anything with at least one ordinary purchase
  //   none      nothing is assumed. Infrequent categories (textbooks, travel, health, fees) are NEVER given an automatic monthly rate, however many
  //             purchases there are: they come in lumps. They are budgeted only by the student, or as dated one-time costs.
  // Rent, tuition, utilities and other bill categories are never habits at all; they come from listed bills or confirmed recurring charges.
  const MIN_CAT_TX = 3, MIN_COVERAGE_DAYS = 14;
  E.MIN_CATEGORY_TX = MIN_CAT_TX;
  E.INFREQUENT_CATEGORIES = ['School supplies', 'Travel', 'Health', 'Fees'];
  E.categoryEvidence = function (category, h, base) {
    const none = (why) => ({ level: 'none', txCount: h ? h.txCount : 0, why });
    if (!h || !(h.monthlyCents > 0) || !h.usualCount) return none(h && h.txCount ? 'Only unusually large purchases so far, which are not treated as a habit.' : 'No purchases yet.');
    const cov = base.coverageDays, n = h.usualCount, infreq = E.INFREQUENT_CATEGORIES.indexOf(category) >= 0;
    if (infreq) return none('Purchases like this come in lumps (textbooks at the start of term, a trip, a doctor visit), so ' + n + ' of them over ' + cov + ' days is not turned into a monthly rate. Plan them as one-time costs or set your own budget.');
    if (cov >= 28 && n >= 6) return { level: 'strong', txCount: n, why: n + ' purchases over ' + cov + ' days.' };
    if (cov >= MIN_COVERAGE_DAYS && n >= MIN_CAT_TX) return { level: 'moderate', txCount: n, why: n + ' purchases over ' + cov + ' days.' };
    return { level: 'thin', txCount: n, why: 'Only ' + n + ' purchase' + (n === 1 ? '' : 's') + ' over ' + cov + ' day' + (cov === 1 ? '' : 's') + '.' };
  };
  const budgetRow = (plan, c) => plan.budgets.find(b => b.category === c);

  // Suggestions only. Never changes the plan. A suggestion is offered only when the category has 'moderate' or 'strong' evidence.
  // `thinMonthlyCents` shows what the few purchases we have would imply, clearly separate from a suggestion.
  E.recommendBudgets = function (plan, today, base) {
    base = base || E.baseline(plan, today);
    const rows = [];
    for (const c of Object.keys(E.CATEGORIES)) {
      if (!habit(c)) continue;
      const b = budgetRow(plan, c), h = base.categories[c];
      if (!b && !h) continue;
      const ev = E.categoryEvidence(c, h, base), enough = ev.level === 'moderate' || ev.level === 'strong';
      const recommended = enough ? Math.max(500, roundTo5(h.monthlyCents)) : null;
      rows.push({
        category: c, kind: E.catKind(c), approvedCents: b ? b.approvedCents : null, recommendedCents: recommended, historyMonthlyCents: h ? h.monthlyCents : null,
        thinMonthlyCents: ev.level === 'thin' ? Math.max(500, roundTo5(h.monthlyCents)) : null, evidence: ev.level, evidenceWhy: ev.why,
        basis: h ? 'history' : 'estimate', confidence: ev.level === 'none' ? 'provisional' : ev.level === 'thin' ? 'provisional' : ev.level === 'moderate' ? 'limited' : base.status,
        differs: !!(b && b.approvedCents != null && recommended != null && Math.abs(recommended - b.approvedCents) >= Math.max(1000, b.approvedCents * 0.15))
      });
    }
    return rows;
  };
  // Stores fresh recommendations next to (never over) the approved budgets. Returns a new plan.
  E.refreshRecommendations = function (plan, today) {
    const p = E.clone(plan), base0 = E.baseline(p, today), rows = E.recommendBudgets(p, today, base0);
    for (const r of rows) {
      let b = budgetRow(p, r.category);
      if (!b) { b = { category: r.category, approvedCents: null, recommendedCents: null, source: 'history' }; p.budgets.push(b); }
      b.recommendedCents = r.recommendedCents;      // null unless this category has enough evidence of its own
    }
    return p;
  };
  // The student's own number. This is the only normal way approvedCents changes (besides acceptRecommendations).
  E.setBudget = function (plan, category, monthlyCents) {
    const p = E.clone(plan);
    if (!E.CATEGORIES[category] || !habit(category) || !Number.isSafeInteger(monthlyCents) || monthlyCents < 0) return { ok: false, plan };
    let b = budgetRow(p, category);
    if (!b) { b = { category, approvedCents: null, recommendedCents: null, source: 'student' }; p.budgets.push(b); }
    b.approvedCents = monthlyCents; b.source = 'student';
    return { ok: true, plan: p };
  };
  // Student taps "Use this" on one or more suggestions.
  E.acceptRecommendations = function (plan, categories) {
    const p = E.clone(plan);
    for (const c of categories) { const b = budgetRow(p, c); if (b && b.recommendedCents != null) { b.approvedCents = b.recommendedCents; b.source = 'accepted'; } }
    return p;
  };
  // What the forecast actually uses for each category: approved, else recommended, else history (moderate/strong evidence), else a THIN estimate, else nothing.
  //   basis 'thin' is a forward-only cautious estimate: the forecast reserves it for today and later days, and NEVER back-fills it over days before
  //   there was any evidence. Every row says where it came from (basis) and how much evidence stands behind it (evidence).
  E.effectiveBudgets = function (plan, today, base) {
    base = base || E.baseline(plan, today);
    const out = [];
    for (const c of Object.keys(E.CATEGORIES)) {
      if (!habit(c)) continue;
      const b = budgetRow(plan, c), h = base.categories[c], ev = E.categoryEvidence(c, h, base);
      let monthly = 0, basis = 'none', evidence = 'none';
      if (b && b.approvedCents != null) { monthly = b.approvedCents; basis = 'approved'; evidence = b.source === 'thin' && (ev.level === 'thin' || ev.level === 'none') ? 'thin' : 'student'; }       // approving a thin estimate does not make the evidence behind it any stronger
      else if (b && b.recommendedCents != null) { monthly = b.recommendedCents; basis = 'recommended'; evidence = ev.level !== 'none' ? ev.level : 'suggested'; }
      else if (ev.level === 'moderate' || ev.level === 'strong') { monthly = roundTo5(h.monthlyCents); basis = 'history'; evidence = ev.level; }
      else if (ev.level === 'thin') { monthly = Math.max(500, roundTo5(h.monthlyCents)); basis = 'thin'; evidence = 'thin'; }
      if (monthly > 0 || basis === 'approved') out.push({ category: c, kind: E.catKind(c), monthlyCents: monthly, basis, evidence, evidenceWhy: basis === 'approved' ? (evidence === 'thin' ? 'You approved an estimate that rests on very few purchases.' : 'Your own number.') : ev.why, forwardOnly: evidence === 'thin' });
    }
    return out;
  };
  // Planned vs actual for the calendar month containing `today` (actual = logged/imported spending in that category so far).
  E.budgetStatus = function (plan, today, base) {
    base = base || E.baseline(plan, today);
    const eff = E.effectiveBudgets(plan, today, base), ms = D.monthStart(today), me = D.monthEnd(today), frac = (today - ms + 1) / (me - ms + 1);
    const act = E.activeTxs(plan).filter(t => { const d = dayOf(t); return d >= ms && d <= today && !E.obligationLike(plan, t); });
    return eff.map(e => {
      const spent = Math.max(0, E.sum(act.filter(t => t.category === e.category && t.flow === 'spend'), t => -t.amountCents) - E.sum(act.filter(t => t.category === e.category && t.flow === 'refund' && t.amountCents > 0), t => t.amountCents));
      const expectedByNow = Math.round(e.monthlyCents * frac);
      const status = e.monthlyCents === 0 ? (spent > 0 ? 'over' : 'on') : spent > e.monthlyCents ? 'over' : spent > expectedByNow * 1.15 && spent > expectedByNow + 500 ? 'ahead' : spent < expectedByNow * 0.6 ? 'under' : 'on';
      return { category: e.category, kind: e.kind, plannedCents: e.monthlyCents, basis: e.basis, spentCents: spent, expectedByNowCents: expectedByNow, remainingCents: e.monthlyCents - spent, status };
    });
  };
})(CCE);

;
/* ===== engine/05-forecast.js ===== */
/* =========================================================================
   05 forecast — one dated cash-flow timeline, from today to the end of the semester
   -------------------------------------------------------------------------
   THE RULES (every other part of the app reads this timeline):

   1. The student's verified balance is the ANCHOR: the balance at the END of its date.
      Everything dated BEFORE the anchor date is already inside it.
      Items dated ON the anchor date are AMBIGUOUS (they may or may not have happened yet), so:
        - a bill / required payment / savings transfer dated on the anchor date is treated as
          STILL TO BE PAID ("unconfirmed") unless a bank row or the student says it is already out;
        - income dated on the anchor date is treated as ALREADY RECEIVED (not added again) but is
          listed as "unconfirmed". Both choices are the cautious direction. Neither is silent: each
          appears in `occurrences` / `pending` so the screen can ask the student.
      A manually logged purchase on the anchor date recorded AFTER the check-in is counted.
   2. Between the anchor and today we RECONSTRUCT the balance. Three kinds of numbers go in, and they
      are kept apart in open.components:
        RECORDED   real transactions the student logged or imported after the anchor
        ASSUMED    scheduled bills/paychecks that should have happened but have no matching
                   transaction (a bill is assumed paid; a paycheck is assumed received in the
                   EXPECTED case only. The cautious case does not count an unlogged paycheck)
        ESTIMATED  everyday spending that was probably never logged (rule 3)
      Assumed and estimated amounts are NEVER written to the ledger (plan.transactions). They exist
      only inside this calculation and disappear when the student confirms them, imports the real
      rows, or checks in with their real balance.
   3. Estimated everyday spending is a FLOOR, not an addition: for each category, over the days since
      the anchor, the balance reflects max(logged, typical). Logging $10 of a $20 typical day
      shrinks the estimate by $10 and leaves the total unchanged; logging $50 removes the estimate
      and the balance reflects the $50. So logging can never make the same dollar count twice.
   4. From today forward, each day applies: scheduled income, bills, savings transfers and the
      daily share of essential spending (and, optionally, planned flexible spending).
      Balances are END-OF-DAY. Income and bills on the same day net out (see FORECAST_LIMITS).
   5. SCENARIOS.  'expected': likely+certain income at its typical amount, bills as entered.
                  'cautious': income at its LOW amount (irregular, or an unverified estimate of
                  work pay: 70%); "likely" aid/scholarship money arrives late; uncertain bills are
                  included; unlogged paychecks since the last balance are not counted. Uncertain
                  income is never counted in either scenario (it is reported as upside).
   6. Savings are unavailable unless the student opts in, and even then only savings NOT allocated to goals
      become spendable. Goal contributions are always outflows. A goal's contributions stop once its
      CONFIRMED progress (14-goals) plus the transfers this forecast already counts reach the target.
   Bills (listed or detected) and everyday category budgets never overlap: see 04-baseline.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const dayOf = t => D.parse(t.date);
  const habit = c => E.catKind(c) !== 'bill';
  const kindOf = type => type === 'income' ? 'income' : type === 'savings' ? 'savings' : 'bill';

  E.FORECAST_LIMITS = [
    'Balances are end-of-day. If a bill is charged in the morning and a paycheck arrives that evening, the account may be overdrawn briefly even though the end-of-day balance is positive. Campus Compass warns about these days but cannot see the order inside a day.',
    'Bills are assumed to be charged on their due date. Banks sometimes post them a day or two later or earlier, and weekend and holiday posting varies.',
    'Everything dated on the day of your verified balance is uncertain. Bills are counted as still to be paid, and income is counted as already received, until you confirm either way.',
    'Pending card or debit transactions that have not posted are not in your balance. Log them as purchases.',
    'Estimates (everyday spending you did not log, bills assumed paid) are labelled as estimates and are replaced by real numbers when you log, import or check in.'
  ];

  const estimatedWork = inc => inc.source === 'estimated' && !inc.verified && (inc.type === 'job' || inc.type === 'workstudy' || inc.type === 'gig');
  // What the CAUTIOUS scenario counts for one paycheck: the low amount if known, otherwise a fraction of the typical amount when the pay is irregular or only an unverified guess.
  E.cautiousIncomeCents = (plan, inc) => inc.lowCents != null ? inc.lowCents : (inc.irregular || estimatedWork(inc)) ? Math.round(inc.amountCents * plan.settings.irregularLowFactorPct / 100) : inc.amountCents;
  E.cautiousReason = (plan, inc) => inc.lowCents != null ? 'lowest recent amount' : inc.irregular ? 'irregular pay: ' + plan.settings.irregularLowFactorPct + '% of typical' : estimatedWork(inc) ? 'unverified estimate: ' + plan.settings.irregularLowFactorPct + '% of typical' : 'same as expected';
  E.occurrenceKey = (kind, id, day) => kind + '|' + id + '|' + D.fmt(day);

  /* ---------- reconciling scheduled income with real deposits ---------- */
  // A deposit and a scheduled paycheck are "the same income" only on EVIDENCE. Amount alone is never enough for regular pay. The evidence is:
  //   identity  the deposit description names the employer / income (or a payer the student already confirmed)
  //   keyword   it reads like pay (PAYROLL, DIRECT DEP, ...) or is flagged as financial aid
  //   date      it lands near the scheduled date (a wider window when identity is known, to allow for delayed deposits)
  //   amount    close to the usual amount (irregular pay is allowed to vary much more)
  //   account   only deposits to the checking account can be pay (card, savings and transfer rows never are)
  // 'high' confidence links the two (the paycheck is then counted once, as the real deposit).
  // 'possible' does NOT guess: the real deposit counts as cash, the scheduled paycheck is put ON HOLD (not counted) so it can never be counted twice,
  // and the student is asked. Either way the same money is never in the forecast twice.
  const PAY_RE = /payroll|direct dep|dir dep|salary|paycheck|wages|\badp\b|gusto|paychex|stipend|work.?study/i;      // deliberately NOT 'ACH credit' or 'PPD': almost every deposit is one
  const ID_STOP = new Set('job work pay paycheck income payroll wages salary student aid gig side hustle other family support money deposit direct dep ach credit the and inc llc university univ college state dept department company corp'.split(' '));
  const ID_ALIASES = { kentucky: ['uky', 'uk'], louisville: ['uofl'], western: ['wku'], eastern: ['eku'], northern: ['nku'], morehead: ['msu'], campus: [], kctcs: ['kctcs'] };
  const words = str => String(str || '').toLowerCase().replace(/[^a-z0-9&\s]/g, ' ').split(/\s+/).filter(w => w.length >= 2 && !/^\d+$/.test(w));
  E.incomeIdentityTokens = function (inc) {
    const out = new Set();
    for (const w of words([inc.name, inc.employer].concat(inc.payerHints || []).join(' '))) {
      if (w.length < 3 || ID_STOP.has(w)) continue;
      out.add(w); for (const a of ID_ALIASES[w] || []) out.add(a);
    }
    return out;
  };
  function incomeMatch(e, t, ids) {
    if (t.amountCents <= 0 || (t.flow !== 'income' && t.flow !== 'aid')) return null;
    const aidEv = e.itype === 'aid' || e.itype === 'scholarship';
    const gap = Math.abs(dayOf(t) - e.nominal), ratio = Math.abs(t.amountCents - e.refCents) / Math.max(1, e.refCents);
    const identity = words(t.desc).some(w => ids.has(w)), keyword = PAY_RE.test(t.desc) || (aidEv && t.flow === 'aid');
    const win = aidEv ? 10 : ((identity || keyword || ratio <= 0.02) ? (e.freq === 'weekly' ? 4 : 10) : 4);      // a late deposit is only looked for further out when there is real evidence
    if (gap > win) return null;
    const tolHigh = e.looseAmount ? 0.6 : 0.12, tolPoss = e.looseAmount ? 1 : 0.5;
    let level = null;
    if (identity && ratio <= 0.6) level = 'high';
    else if (keyword && ratio <= tolHigh) level = 'high';
    else if (ratio <= 0.02 && gap <= 3) level = 'high';
    else if (ratio <= 0.02) level = 'possible';                                               // exactly the usual amount, but late or undescribed: ask
    else if (identity && ratio <= 1.2) level = 'possible';
    else if (keyword && ratio <= tolPoss) level = 'possible';
    else if (ratio <= 0.12 && gap <= 2 && t.flow === 'income') level = 'possible';
    else if (ratio <= 0.6 && gap <= 4 && t.flow === 'income' && t.review) level = 'possible';        // an UNEXPLAINED deposit near payday: ask, do not add it on top
    if (!level) return null;
    const why = [];
    if (identity) why.push('the description names this employer'); if (keyword) why.push('it reads like pay');
    why.push(gap === 0 ? 'it arrived on the scheduled day' : 'it arrived ' + gap + ' day' + (gap === 1 ? '' : 's') + (dayOf(t) > e.nominal ? ' after' : ' before') + ' the scheduled day');
    why.push(ratio <= 0.02 ? 'the amount is the same' : 'the amount is ' + Math.round(ratio * 100) + '% ' + (t.amountCents > e.refCents ? 'above' : 'below') + ' the usual');
    return { level, identity, keyword, gap, ratio, why, score: (level === 'high' ? 100 : 0) + (identity ? 30 : 0) + (keyword ? 15 : 0) - ratio * 20 - gap };
  }

  E.metricsOf = function (days, cushion) {
    let min = Infinity, minDay = null, firstBelow = null, firstNeg = null;
    for (const d of days) {
      if (d.bal < min) { min = d.bal; minDay = d.day; }
      if (firstBelow === null && d.bal < cushion) firstBelow = d.day;
      if (firstNeg === null && d.bal < 0) firstNeg = d.day;
    }
    return { minCents: min, minDay, firstBelowCushionDay: firstBelow, firstNegativeDay: firstNeg, endCents: days.length ? days[days.length - 1].bal : 0, shortfallCents: Math.max(0, cushion - min), belowZeroCents: Math.max(0, -min) };
  };

  /* ---------- periods: every weekly, monthly and semester number is a sum of the SAME daily rows ---------- */
  // Real calendar periods overlapping [from, to], clipped to it. unit 'week' uses startsOn (0 = Sunday, 1 = Monday); unit 'month' uses calendar months.
  E.calendarPeriods = function (from, to, unit, startsOn) {
    const out = [];
    if (from > to) return out;
    let s = unit === 'week' ? D.weekStart(from, startsOn) : D.monthStart(from);
    while (s <= to) {
      const e = unit === 'week' ? s + 6 : D.monthEnd(s), a = Math.max(s, from), b = Math.min(e, to);
      out.push({ key: unit === 'week' ? 'W' + D.fmt(s) : D.monthKey(s), unit, startDay: a, endDay: b, days: b - a + 1, fullStartDay: s, fullEndDay: e, clipped: a !== s || b !== e });
      s = e + 1;
    }
    return out;
  };
  // Totals of the daily rows dated in [from, to]: money in and out, the balance before the first day, and the end and lowest balances.
  // Returns null when no daily row falls in the range (for example a past week: the forecast has no rows before today).
  E.sumDays = function (days, from, to) {
    let r = null;
    for (const d of days) {
      if (d.day < from || d.day > to) continue;
      if (!r) r = { startDay: d.day, endDay: d.day, days: 0, inc: 0, obl: 0, sav: 0, ess: 0, flx: 0, pur: 0, net: 0, startBal: d.bal - d.inc + d.obl + d.sav + d.ess + d.flx + d.pur, endBal: d.bal, minBal: d.bal, minDay: d.day };
      r.endDay = d.day; r.days++; r.inc += d.inc; r.obl += d.obl; r.sav += d.sav; r.ess += d.ess; r.flx += d.flx; r.pur += d.pur; r.endBal = d.bal;
      if (d.bal < r.minBal) { r.minBal = d.bal; r.minDay = d.day; }
    }
    if (r) r.net = r.inc - r.obl - r.sav - r.ess - r.flx - r.pur;
    return r;
  };

  // opts: { today (required), scenario, flex:'none'|'budget'|'baseline', det, base, endDay (override the planning horizon), extraEvents:[{day, amountCents(+in/−out), label}] }
  E.forecast = function (plan, opts) {
    const T = opts.today, scenario = opts.scenario || plan.settings.scenario, cautious = scenario === 'cautious', flexMode = opts.flex || 'none';
    const anchorDay = D.parse(plan.account.asOf);
    if (anchorDay === null) return { ok: false, error: 'no_balance', scenario };
    const A0 = Math.min(anchorDay, T), C = plan.account.cushionCents, hz = E.horizonInfo(plan, T), H = opts.endDay != null ? Math.max(T, opts.endDay) : hz.endDay, N = H - T;
    const det = opts.det || E.detectRecurring(plan, T), base = opts.base || E.baseline(plan, T, det), eff = E.effectiveBudgets(plan, T, base);
    const uncounted = [], events = [];
    const push = (e) => { e.key = e.type + '|' + (e.id || e.name) + '|' + e.nominal; events.push(e); };
    const resolutions = plan.resolutions || [], resMap = {};
    for (const r of resolutions) resMap[r.key] = r.status;
    const placeDay = A0 < T ? A0 + 1 : T;       // where an outstanding item dated on/before the balance date is placed

    // Days on/before the balance date that need a decision for one scheduled item: the balance date itself (ambiguous) and anything the student marked "not yet".
    const pastDays = (kind, id, sch) => {
      const set = new Set(E.occurrences(sch, A0, A0).map(o => o.day));
      for (const r of resolutions) {
        const a = r.key.indexOf('|'), b = r.key.lastIndexOf('|');
        if (r.key.slice(0, a) !== kind || r.key.slice(a + 1, b) !== id) continue;
        const nd = D.parse(r.key.slice(b + 1)); if (nd !== null && nd <= A0) set.add(nd);
      }
      return Array.from(set).sort((x, y) => x - y);
    };

    /* ----- scheduled money (what SHOULD happen after the anchor) ----- */
    for (const inc of plan.incomes) {
      if (!inc.schedule || inc.amountCents <= 0) continue;
      const occ = E.occurrences(inc.schedule, A0 + 1, H);
      if (inc.reliability === 'uncertain') { for (const o of occ) uncounted.push({ type: 'income', id: inc.id, name: inc.name, day: o.day, amountCents: inc.amountCents, reason: 'uncertain' }); continue; }
      const late = inc.delayDays + (cautious && inc.reliability === 'likely' && (inc.type === 'aid' || inc.type === 'scholarship') ? plan.settings.cautiousLateDays : 0);
      const mk = nominal => ({ type: 'income', id: inc.id, name: inc.name, itype: inc.type, nominal, delay: late, sign: 1, amountCents: cautious ? E.cautiousIncomeCents(plan, inc) : inc.amountCents, refCents: inc.amountCents, looseAmount: !!(inc.irregular || inc.lowCents != null || estimatedWork(inc)), freq: inc.schedule.freq, category: '', reliability: inc.reliability, source: inc.source, verified: inc.verified });
      for (const o of occ) push(mk(o.day));
      for (const nd of pastDays('income', inc.id, inc.schedule)) {
        const res = resMap[E.occurrenceKey('income', inc.id, nd)];
        if (res === 'unpaid') push(Object.assign(mk(nd), { past: true, resolved: 'unpaid', forceDay: Math.max(T, nd + late) }));   // "has not arrived yet"
        else push(Object.assign(mk(nd), { past: true, ambiguous: true, skipCash: true, delay: 0 }));                                  // assumed already in the balance
      }
    }
    const outflow = (base0, kind, sch) => {
      for (const o of E.occurrences(sch, A0 + 1, H)) push(Object.assign({}, base0, { nominal: o.day }));
      for (const nd of pastDays(kind, base0.id, sch)) {
        const res = resMap[E.occurrenceKey(kind, base0.id, nd)];
        push(Object.assign({}, base0, { nominal: nd, past: true, forceDay: placeDay, ambiguous: res !== 'unpaid', resolved: res === 'unpaid' ? 'unpaid' : '' }));   // still to be paid until confirmed
      }
    };
    for (const ob of plan.obligations) {
      if (!ob.schedule || ob.amountCents <= 0) continue;
      if (ob.reliability === 'uncertain' && !cautious) { for (const o of E.occurrences(ob.schedule, A0 + 1, H)) uncounted.push({ type: 'bill', id: ob.id, name: ob.name, day: o.day, amountCents: ob.amountCents, reason: 'uncertain' }); continue; }
      outflow({ type: 'bill', id: ob.id, name: ob.name, delay: 0, sign: -1, amountCents: cautious && ob.highCents != null ? ob.highCents : ob.amountCents, refCents: ob.amountCents, category: ob.category, vendorKey: ob.vendorKey, reliability: ob.reliability, source: ob.source, verified: ob.verified, kind: ob.kind }, 'bill', ob.schedule);
    }
    for (const r of det) {            // recurring charges found in transactions but not yet confirmed as bills
      if (r.ignored || r.matched) continue;
      const rel = r.confidence === 'high' ? 'likely' : 'uncertain';
      if (rel === 'uncertain' && !cautious) { for (const o of E.occurrences(r.schedule, A0 + 1, H)) uncounted.push({ type: 'bill', id: 'det:' + r.key, name: r.name, day: o.day, amountCents: r.amountCents, reason: 'detected-low-confidence' }); continue; }
      outflow({ type: 'detected', id: 'det:' + r.key, name: r.name, delay: 0, sign: -1, amountCents: r.amountCents, refCents: r.amountCents, category: r.category, vendorKey: r.key, reliability: rel, source: 'detected', verified: false }, 'bill', r.schedule);
    }
    // Amounts are capped to what is left of each goal AFTER matching (below), so a confirmed transfer is never subtracted twice.
    const goalLeft = {};
    for (const g of plan.goals) {
      if (!g.contribution || g.status !== 'active') continue;
      goalLeft[g.id] = g.targetCents > 0 ? E.goalProgress(plan, g).remainingCents : Infinity;
      if (goalLeft[g.id] <= 0) continue;
      const sav = [];
      for (const nd of pastDays('savings', g.id, g.contribution.schedule)) sav.push({ nominal: nd, past: true });
      for (const o of E.occurrences(g.contribution.schedule, A0 + 1, H)) sav.push({ nominal: o.day, past: false });
      for (const s of sav) {
        const res = s.past ? resMap[E.occurrenceKey('savings', g.id, s.nominal)] : undefined;
        const e = { type: 'savings', id: g.id, name: g.name, nominal: s.nominal, delay: 0, sign: -1, amountCents: g.contribution.amountCents, refCents: g.contribution.amountCents, category: '', reliability: 'certain', source: 'user', verified: true };
        if (s.past) Object.assign(e, { past: true, forceDay: placeDay, ambiguous: res !== 'unpaid', resolved: res === 'unpaid' ? 'unpaid' : '' });
        push(e);
      }
    }
    // The student said a scheduled item from the elapsed days has NOT happened yet.
    for (const e of events) {
      if (e.past || e.nominal > T) continue;
      if (resMap[E.occurrenceKey(kindOf(e.type), e.id, e.nominal)] !== 'unpaid') continue;
      e.resolved = 'unpaid';
      if (e.type === 'income') e.forceDay = Math.max(T, e.nominal + (e.delay || 0));   // still to arrive: never assumed received
    }

    /* ----- what really happened since the anchor ----- */
    const acctSeq = plan.account.seq;
    const cash = E.cashTxs(plan), post = cash.filter(t => { const d = dayOf(t); return d <= T && (d > A0 || (d === A0 && t.source === 'manual' && t.seq > acctSeq)); });
    const postIds = new Set(post.map(t => t.id));
    const reflected = cash.filter(t => { const d = dayOf(t); return !postIds.has(t.id) && d <= A0 && d >= A0 - 6; });      // already inside the balance, but good evidence that a bill was paid
    const used = new Set();
    for (const e of events.slice().sort((a, b) => a.nominal - b.nominal)) {         // match scheduled BILLS to the real transactions that already cover them
      if (e.nominal > T + 4 || e.resolved || e.type === 'income') continue;
      const cands = e.ambiguous ? post.concat(reflected) : post;
      let best = null;
      for (const t of cands) {
        if (used.has(t.id)) continue;
        if (e.sign > 0 ? (t.amountCents <= 0 || (t.flow !== 'income' && t.flow !== 'aid')) : (t.amountCents >= 0 || (e.type === 'savings' ? t.flow !== 'transfer' : (t.flow !== 'spend' && t.flow !== 'card_payment')))) continue;
        if (e.type === 'savings' && t.goalId && t.goalId !== e.id) continue;
        const gap = Math.abs(dayOf(t) - e.nominal), win = e.type === 'income' && (e.itype === 'aid' || e.itype === 'scholarship') ? 10 : 4;
        if (gap > win) continue;
        const ratio = Math.abs(Math.abs(t.amountCents) - e.refCents) / Math.max(1, e.refCents);
        const named = E.namesOverlap(e.name, t.desc) || (e.vendorKey && (E.vendorKey(t.desc) === e.vendorKey || E.namesOverlap(e.vendorKey, t.desc))) || (e.type === 'savings' && t.goalId === e.id);
        // An equal amount alone is NOT enough when the transaction is already labelled as a different everyday category (a $40 grocery run is not the $40 phone bill).
        const conflict = e.sign < 0 && e.category && t.category && t.category !== 'Other' && t.category !== e.category && habit(t.category);
        // Irregular or estimated pay varies, so a deposit within the expected window and within 60% of the typical amount is accepted without a name match.
        const ok = (ratio <= 0.12 && (named || (e.category && t.category === e.category) || (ratio <= 0.02 && !conflict))) || (named && ratio <= 0.6) || (e.looseAmount && ratio <= 0.6);
        if (!ok) continue;
        const score = gap + ratio * 20 - (named ? 5 : 0);
        if (!best || score < best.score) best = { t, score };
      }
      if (best) { used.add(best.t.id); e.matched = best.t.id; }
    }
    // scheduled INCOME: score every (paycheck, deposit) pair, then assign best pairs first so each deposit is used at most once (two jobs, two deposits, same day)
    const decisionMap = {}; for (const d of plan.matchDecisions || []) decisionMap[d.key] = d;
    const idsOf = {}; for (const inc of plan.incomes) idsOf[inc.id] = E.incomeIdentityTokens(inc);
    const pairs = [];
    for (const e of events) {
      if (e.type !== 'income' || e.nominal > T + 4 || e.resolved) continue;
      const dec = decisionMap[E.occurrenceKey('income', e.id, e.nominal)];
      for (const t of (e.ambiguous ? post.concat(reflected) : post)) {
        if (dec && dec.txId === t.id) { if (dec.decision === 'different') continue; pairs.push({ e, t, m: { level: 'high', score: 1e6, forced: true, why: ['you confirmed it'] } }); continue; }
        const m = incomeMatch(e, t, idsOf[e.id] || new Set()); if (m) pairs.push({ e, t, m });
      }
    }
    pairs.sort((x, y) => y.m.score - x.m.score || (x.e.nominal - y.e.nominal));
    const usedDep = new Set(), doneInc = new Set(), matchQuestions = [];
    for (const pr of pairs) {
      if (usedDep.has(pr.t.id) || doneInc.has(pr.e)) continue;
      usedDep.add(pr.t.id); doneInc.add(pr.e); used.add(pr.t.id);
      if (pr.m.level === 'high') pr.e.matched = pr.t.id;
      else { pr.e.possible = pr.t.id; matchQuestions.push({ kind: 'deposit_match', incomeId: pr.e.id, name: pr.e.name, nominal: pr.e.nominal, expectedCents: pr.e.refCents, txId: pr.t.id, txDesc: pr.t.desc, txDate: pr.t.date, txCents: pr.t.amountCents, why: pr.m.why }); }
    }
    // Cap goal contributions in date order. A transfer already linked to the goal is inside its confirmed progress, so it uses nothing up;
    // any other covered or assumed transfer has left checking and uses up its amount. Contributions past the target are dropped.
    const txById = {}; for (const t of plan.transactions) txById[t.id] = t;
    const dropped = new Set();
    for (const e of events.filter(x => x.type === 'savings').sort((a, b) => a.nominal - b.nominal)) {
      const t = e.matched ? txById[e.matched] : null;
      if (t && t.goalId === e.id) continue;
      const amt = Math.min(t ? -t.amountCents : e.amountCents, goalLeft[e.id]);
      if (!t) { if (amt <= 0) { dropped.add(e); continue; } e.amountCents = amt; }
      goalLeft[e.id] -= Math.max(0, amt);
    }
    for (let i = events.length - 1; i >= 0; i--) if (dropped.has(events[i])) events.splice(i, 1);
    for (const e of events) e.day = e.forceDay != null ? e.forceDay : e.nominal + (e.delay || 0);

    const savingsSplit = E.savingsSummary(plan);
    let open = plan.account.balanceCents + savingsSplit.spendableCents;
    const comp = { anchorCents: open, spendableSavingsCents: savingsSplit.spendableCents, allocatedSavingsCents: savingsSplit.allocatedCents, loggedCents: 0, recordedCents: 0, assumedIncomeCents: 0, assumedBillsCents: 0, assumedSavingsCents: 0, unloggedSpendingCents: 0, unloggedBy: [], estimatedNetCents: 0 };
    for (const t of post) { open += t.amountCents; comp.loggedCents += t.amountCents; }
    comp.recordedCents = comp.loggedCents;
    const assumed = [], pending = [];
    for (const e of events) {
      if (e.matched || e.possible) continue;       // a possible match: the deposit is already in the balance as cash, so the scheduled paycheck is on hold
      if (!e.resolved && (e.type === 'income' || e.type === 'bill') && (e.nominal <= T - 1 || e.ambiguous)) pending.push({ type: e.type, id: e.id, name: e.name, nominal: e.nominal, amountCents: e.amountCents, delayedTo: e.day > T - 1 && !e.ambiguous ? e.day : null, onBalanceDate: !!e.ambiguous });
      if (e.skipCash) continue;
      if (e.day <= T - 1) {
        if (e.type === 'income' && cautious) { uncounted.push({ type: 'income', id: e.id, name: e.name, day: e.nominal, amountCents: e.amountCents, reason: 'unconfirmed_deposit' }); continue; }
        open += e.sign * e.amountCents; assumed.push(e);
        if (e.type === 'income') comp.assumedIncomeCents += e.amountCents; else if (e.type === 'savings') comp.assumedSavingsCents += e.amountCents; else comp.assumedBillsCents += e.amountCents;
      }
    }
    // everyday spending that was probably never logged: balance reflects max(logged, typical)
    const actualBy = {}, todayBy = {};
    for (const t of post) {
      if (used.has(t.id) || (t.flow !== 'spend' && t.flow !== 'refund') || !t.category || !habit(t.category) || E.obligationLike(plan, t)) continue;
      const d = dayOf(t), amt = -t.amountCents;
      if (d <= T - 1) actualBy[t.category] = (actualBy[t.category] || 0) + amt; else if (d === T) todayBy[t.category] = (todayBy[t.category] || 0) + amt;
    }
    if (A0 < T - 1) {
      // Estimates fill in days since the verified balance, but NEVER days before the evidence existed, and a 'thin' estimate is forward-only (never back-filled).
      // The student's own approved numbers are their statement about every day, so those may cover all elapsed days.
      for (const b of eff) {
        if (b.forwardOnly) continue;
        const from = b.basis === 'approved' ? A0 + 1 : (base.windowStart === null ? T : Math.max(A0 + 1, base.windowStart));
        let est = 0; for (let d = from; d <= T - 1; d++) est += E.dailyShare(b.monthlyCents, d);
        const logged = actualBy[b.category] || 0, top = Math.max(0, est - logged);
        if (est > 0) comp.unloggedBy.push({ category: b.category, typicalCents: est, loggedCents: logged, estimatedCents: top });
        if (top > 0) { open -= top; comp.unloggedSpendingCents += top; }
      }
    }
    comp.estimatedNetCents = comp.assumedIncomeCents - comp.assumedBillsCents - comp.assumedSavingsCents - comp.unloggedSpendingCents;

    /* ----- paid / assumed / unpaid / scheduled: one label for every scheduled item ----- */
    for (const e of events) {
      let s;
      if (e.matched) s = { status: e.type === 'income' ? 'received' : 'paid', group: 'paid', counted: false };
      else if (e.possible) s = { status: 'match_unconfirmed', group: 'assumed', counted: false, treatedAs: 'a deposit may be this paycheck: counted once, as the deposit' };
      else if (e.skipCash) s = { status: 'unconfirmed', group: 'assumed', counted: false, treatedAs: 'received' };
      else if (e.resolved === 'unpaid') s = e.type === 'income' ? { status: 'awaiting', group: 'unpaid', counted: e.day <= H } : { status: 'overdue', group: 'unpaid', counted: true };
      else if (e.ambiguous) s = { status: 'unconfirmed', group: 'unpaid', counted: true, treatedAs: 'unpaid' };
      else if (e.nominal <= T - 1 && e.day <= T - 1) s = e.type === 'income' ? (cautious ? { status: 'unconfirmed_deposit', group: 'assumed', counted: false, treatedAs: 'not received' } : { status: 'assumed_received', group: 'assumed', counted: true }) : { status: 'assumed_paid', group: 'assumed', counted: true };
      else if (e.nominal === T && T > A0 && e.type !== 'income') s = { status: 'due_today', group: 'unpaid', counted: true };
      else s = { status: 'scheduled', group: 'scheduled', counted: e.day <= H };
      e.status = s.status; e.group = s.group; e.counted = s.counted; e.treatedAs = s.treatedAs || '';
    }
    const occurrences = events.map(e => ({ type: e.type, kind: kindOf(e.type), id: e.id, name: e.name, nominal: e.nominal, day: e.day, amountCents: e.amountCents, status: e.status, group: e.group, counted: e.counted, treatedAs: e.treatedAs, txId: e.matched || e.possible || '' }))
      .sort((a, b) => a.nominal - b.nominal || (a.name < b.name ? -1 : 1));
    for (const p of pending) { const o = occurrences.find(x => x.id === p.id && x.nominal === p.nominal); p.status = o ? o.status : ''; }

    /* ----- forward timeline ----- */
    const byDay = {};
    for (const e of events) if (!e.matched && !e.possible && !e.skipCash && e.day >= T && e.day <= H) (byDay[e.day] = byDay[e.day] || []).push(e);
    const extras = (opts.extraEvents || []).map(x => ({ type: 'purchase', id: 'extra', name: x.label || 'Planned purchase', day: Math.max(T, Math.min(H, x.day)), sign: x.amountCents >= 0 ? 1 : -1, amountCents: Math.abs(x.amountCents), category: x.category || '' }));
    for (const x of extras) (byDay[x.day] = byDay[x.day] || []).push(x);
    let flexRows = [];
    if (flexMode === 'budget') flexRows = eff.filter(b => b.kind === 'flexible');
    else if (flexMode === 'baseline') flexRows = Object.keys(base.categories).filter(c => base.categories[c].kind === 'flexible').map(c => ({ category: c, monthlyCents: base.categories[c].monthlyCents }));
    const essRows = eff.filter(b => b.kind === 'essential');
    const days = [], loopEvents = [], intradayDips = [];
    let bal = open, sav = savingsSplit.savingsNowCents;
    for (let i = 0; i <= N; i++) {
      const day = T + i, row = { i, day, bal: 0, inc: 0, obl: 0, sav: 0, ess: 0, flx: 0, pur: 0 }, prev = bal;
      for (const e of byDay[day] || []) {
        const a = e.sign * e.amountCents;
        if (e.type === 'income') row.inc += a; else if (e.type === 'savings') { row.sav -= a; sav += e.amountCents; } else if (e.type === 'purchase') { if (a >= 0) row.inc += a; else row.pur -= a; } else row.obl -= a;
        loopEvents.push({ day, type: e.type, itype: e.itype, id: e.id, name: e.name, amountCents: a, category: e.category, reliability: e.reliability, source: e.source, verified: e.verified, status: e.status || 'scheduled' });
      }
      for (const b of essRows) { let r = E.dailyShare(b.monthlyCents, day); if (i === 0) r = Math.max(0, r - (todayBy[b.category] || 0)); row.ess += r; }
      for (const b of flexRows) { let r = E.dailyShare(b.monthlyCents, day); if (i === 0) r = Math.max(0, r - (todayBy[b.category] || 0)); row.flx += r; }
      bal += row.inc - row.obl - row.sav - row.ess - row.flx - row.pur;
      row.bal = bal; row.savingsBal = sav; days.push(row);
      // End-of-day netting hides this: required payments come due the same day money arrives, and the account would dip below $0 if they were charged first.
      const lowIntra = prev - row.obl - row.sav - row.pur;
      if (row.inc > 0 && lowIntra < 0 && row.bal >= 0) intradayDips.push({ day, lowCents: lowIntra, incomeCents: row.inc, outflowCents: row.obl + row.sav + row.pur });
    }
    // monthly roll-up (calendar months inside the planning window)
    const mm = [], idx = {};
    for (const d of days) {
      const k = D.monthKey(d.day);
      if (idx[k] === undefined) { idx[k] = mm.length; mm.push({ key: k, startDay: d.day, endDay: d.day, inc: 0, obl: 0, sav: 0, ess: 0, flx: 0, pur: 0, startBal: d.bal - d.inc + d.obl + d.sav + d.ess + d.flx + d.pur, endBal: 0, minBal: Infinity, minDay: d.day, partial: false }); }
      const m = mm[idx[k]];
      m.inc += d.inc; m.obl += d.obl; m.sav += d.sav; m.ess += d.ess; m.flx += d.flx; m.pur += d.pur; m.endBal = d.bal; m.endDay = d.day;
      if (d.bal < m.minBal) { m.minBal = d.bal; m.minDay = d.day; }
    }
    for (const m of mm) { m.net = m.inc - m.obl - m.sav - m.ess - m.flx - m.pur; m.status = m.minBal < 0 ? 'short' : m.minBal < C ? 'tight' : 'ok'; m.partial = m.startDay !== D.monthStart(m.startDay) || m.endDay !== D.monthEnd(m.startDay); }
    // weekly roll-up (calendar weeks starting on the student's chosen day, clipped to the planning window), from the same rows as the months
    const weeks = E.calendarPeriods(T, H, 'week', plan.settings.weekStartsOn).map(p => {
      const s = E.sumDays(days, p.startDay, p.endDay);
      return Object.assign(p, s, { status: s.minBal < 0 ? 'short' : s.minBal < C ? 'tight' : 'ok' });
    });
    const pressure = loopEvents.filter(e => e.amountCents < 0 && (e.type === 'bill' || e.type === 'detected')).sort((a, b) => a.amountCents - b.amountCents).slice(0, 6).map(e => ({ name: e.name, day: e.day, amountCents: -e.amountCents, category: e.category, reliability: e.reliability }));
    const warnings = [];
    if (hz.provisional) warnings.push('Semester dates have not been confirmed.');
    if (T - anchorDay > plan.settings.staleDays) warnings.push('Your balance was last verified ' + (T - anchorDay) + ' days ago.');
    if (base.status === 'provisional' && !eff.length) warnings.push('No spending history or budget yet, so everyday spending is not included.');
    if (anchorDay > T) warnings.push('Your balance is dated in the future and was treated as today.');
    const amb = occurrences.filter(o => o.status === 'unconfirmed');
    if (amb.length) warnings.push(amb.length + ' item' + (amb.length > 1 ? 's are' : ' is') + ' dated on your balance date. Bills are counted as still to be paid and income as already received until you confirm.');
    if (intradayDips.length) warnings.push('On ' + D.label(intradayDips[0].day) + ', ' + E.fmt(intradayDips[0].outflowCents) + ' of required payments is due the same day money arrives. If the payments post first, your account could dip below $0 for a few hours.');
    return {
      ok: true, scenario, flex: flexMode, today: T, endDay: H, N, horizon: hz, cushionCents: C, anchorDay, staleDays: Math.max(0, T - anchorDay),
      open: { cents: open, components: comp }, days, events: loopEvents, occurrences, assumed, pending, matchQuestions, uncounted, months: mm, weeks, metrics: E.metricsOf(days, C), pressure, budgetsUsed: eff, base, det, warnings, intradayDips
    };
  };

  /* ---------- confirm what happened to a scheduled item ---------- */
  // o: { type:'bill'|'income'|'savings', id, nominal:'YYYY-MM-DD' (the scheduled date),
  //      status:'paid'|'unpaid'|'clear', amountCents?, date? (when it really happened; default = scheduled date) }
  //  'paid'   turns the assumption into a REAL recorded transaction the student can see, edit and delete.
  //           If it happened on or before the balance date it is "already in the balance" (no cash effect, but it
  //           proves the item was paid). If it happened after the balance date it is counted.
  //  'unpaid' remembers "not paid / not received yet": a bill stays owed; income is not counted until it arrives.
  //  'clear'  forgets an earlier 'unpaid'.
  E.resolveOccurrence = function (plan, o, today) {
    const kind = o && o.type, list = kind === 'income' ? plan.incomes : kind === 'savings' ? plan.goals : kind === 'bill' ? plan.obligations : null;
    const item = list && list.find(x => x.id === o.id);
    if (!item) return { ok: false, error: 'That item no longer exists.', plan };
    const nd = D.parse(o.nominal);
    if (nd === null) return { ok: false, error: 'That date is not valid.', plan };
    if (typeof today === 'number' && nd > today) return { ok: false, error: 'You can only confirm items that are due today or earlier.', plan };
    const key = E.occurrenceKey(kind, item.id, nd), p = E.clone(plan);
    p.resolutions = (p.resolutions || []).filter(r => r.key !== key);
    if (o.status === 'clear') return { ok: true, plan: p };
    if (o.status === 'unpaid') { p.resolutions.push({ key, status: 'unpaid' }); p.resolutions = p.resolutions.slice(-400); return { ok: true, plan: p }; }
    if (o.status !== 'paid') return { ok: false, error: 'Unknown answer.', plan };
    const when = o.date ? D.parse(o.date) : nd;
    if (when === null) return { ok: false, error: 'That date is not valid.', plan };
    const amount = o.amountCents != null ? Math.abs(Math.round(o.amountCents)) : (kind === 'savings' ? item.contribution && item.contribution.amountCents : item.amountCents);
    const spec = kind === 'income' ? { direction: 'in', flow: item.type === 'aid' || item.type === 'scholarship' ? 'aid' : 'income', category: '' }
      : kind === 'savings' ? { direction: 'out', flow: 'transfer', category: '' } : { direction: 'out', flow: 'spend', category: item.category };
    const r = E.addManualTx(p, Object.assign({ amountCents: amount, desc: item.name, date: D.fmt(when) }, spec), today);
    if (!r.ok) return { ok: false, error: r.error, plan };
    if (kind === 'savings') r.tx.goalId = item.id;           // the student confirmed it: this is now real progress toward the goal
    const anchor = D.parse(r.plan.account.asOf);
    if (anchor !== null && when <= anchor) r.tx.seq = Math.min(r.tx.seq, r.plan.account.seq);     // happened before the balance was verified: already inside it
    return { ok: true, plan: r.plan, tx: r.tx };
  };

  /* ---------- "is this deposit that scheduled paycheck?" ---------- */
  // o: { incomeId, nominal:'YYYY-MM-DD' (the scheduled date), txId, decision:'same'|'different'|'clear' }
  // 'same'       links them (the paycheck is counted once, as the real deposit) and remembers the payer, so the next one matches without asking.
  // 'different'  keeps the deposit as its own income and puts the scheduled paycheck back (it is expected unless it also arrives).
  // Never changes the balance or invents a transaction. Returns a new plan.
  E.confirmDepositMatch = function (plan, o) {
    const inc = plan.incomes.find(x => x.id === (o && o.incomeId));
    if (!inc) return { ok: false, error: 'That income no longer exists.', plan };
    const nd = D.parse(o.nominal); if (nd === null) return { ok: false, error: 'That date is not valid.', plan };
    const key = E.occurrenceKey('income', inc.id, nd), p = E.clone(plan);
    p.matchDecisions = (p.matchDecisions || []).filter(d => d.key !== key);
    if (o.decision === 'clear') return { ok: true, plan: p };
    const tx = p.transactions.find(t => t.id === o.txId);
    if (!tx || tx.amountCents <= 0) return { ok: false, error: 'That deposit no longer exists.', plan };
    if (o.decision !== 'same' && o.decision !== 'different') return { ok: false, error: 'Unknown answer.', plan };
    p.matchDecisions.push({ key, txId: tx.id, decision: o.decision });
    p.matchDecisions = p.matchDecisions.slice(-400);
    if (o.decision === 'same') {
      const pi = p.incomes.find(x => x.id === inc.id), hint = E.vendorKey(tx.desc);
      if (hint && pi.payerHints.indexOf(hint) < 0 && !words(tx.desc).some(w => E.incomeIdentityTokens(pi).has(w))) pi.payerHints = pi.payerHints.concat([hint]).slice(-6);
    }
    return { ok: true, plan: p };
  };
})(CCE);

;
/* ===== engine/06-capacity.js ===== */
/* =========================================================================
   06 capacity — "how much can I spend?" answered three different ways, from ONE timeline
   -------------------------------------------------------------------------
   Let bal(k) be the projected end-of-day balance k days from today when ONLY commitments are
   included (income, bills, savings transfers, essential spending — no flexible spending).
   Let C be the student's safety cushion and U(k) = bal(k) − C   ("room" on day k).

   1. IMMEDIATE AFFORDABILITY  "Can I spend $X right now?"
        Spending X today lowers every later balance by X, so it is safe only if
        X ≤ min over all days k of U(k).  This is a one-time lump, not a pace.

   2. SUSTAINABLE PACE  "How much per day can I keep spending?"
        Let S(k) be total flexible spending through day k. A plan is safe if S(k) ≤ U(k)
        for every day (spending never uses the cushion or an upcoming bill).
        The fairest such plan is the LARGEST LEVEL spending path under that ceiling:
        the greatest convex curve below the points (k+1, U(k)) — i.e. the lower convex hull.
        Its first slope is  min over k of U(k)/(k+1)  (the "tightest day" sets today's pace);
        after a payday or refund the pace may step UP, never down. Daily amounts are
        floor(S(k+1)) − floor(S(k)), so they add up exactly and never overshoot the ceiling.

   3. MONTHLY FLEXIBLE ALLOWANCE  "How much flexible spending does my plan support this month?"
        The sum of the daily pace over the rest of the month, plus what was already spent
        this month. Today ≤ week ≤ month ≤ semester, always, because they are sums of the
        same daily pace over nested windows.

   If commitments alone already push a balance below the cushion on some day, spending room
   up to that day is $0 and the plan is flagged as NOT SAFE: a positive amount is never
   called safe while a shortfall exists.

   END-OF-TERM RESERVE (optional, off by default).
   A student can keep money for the weeks after the term ends. It is the sum of
     - a FIXED amount the student chooses, and
     - a BRIDGE: how far the balance would FALL below its end-of-term level (counting rent, other bills,
       essentials and any paychecks that continue) before the next financial-aid refund arrives
       (or before reserveBridgeMaxDays if no refund is scheduled).
   The reserve only changes the LAST day's room: U(N) = bal(N) − cushion − reserve. Because pace and
   lump capacity are both computed from the same room numbers, both respect it.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const dayOf = t => D.parse(t.date);

  // Spending the student has chosen to treat as "flexible" in [from, to]. Bills and detected recurring charges are excluded
  // because they are already reserved as commitments.
  E.flexSpent = function (plan, from, to, skipIds) {
    let spend = 0, refund = 0;
    for (const t of E.activeTxs(plan)) {
      const d = dayOf(t);
      if (d < from || d > to || !t.category || E.catKind(t.category) !== 'flexible' || (skipIds && skipIds.has(t.id)) || E.obligationLike(plan, t)) continue;
      if (t.flow === 'spend') spend += -t.amountCents; else if (t.flow === 'refund' && t.amountCents > 0) refund += t.amountCents;
    }
    return Math.max(0, spend - refund);
  };
  const detSkip = det => { const s = new Set(); for (const r of det || []) if (!r.ignored) for (const id of r.txIds) s.add(id); return s; };

  function lowerHull(pts) {
    const h = [];
    for (const p of pts) {
      while (h.length >= 2) {
        const a = h[h.length - 2], b = h[h.length - 1];
        if ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) <= 0) h.pop(); else break;
      }
      h.push(p);
    }
    return h;
  }
  E.lowerHull = lowerHull;

  // The largest outflow between two days (used to say WHAT is limiting spending).
  function driver(fc, k0, k1, endLabel) {
    let best = null;
    for (const e of fc.events) {
      if (e.day < fc.today + k0 || e.day > fc.today + k1 || e.amountCents >= 0 || e.type === 'purchase') continue;
      if (!best || e.amountCents < best.amountCents) best = e;
    }
    if (best) return { kind: best.type === 'savings' ? 'savings' : 'bill', day: best.day, label: best.name, amountCents: -best.amountCents };
    if (k1 >= fc.N) return { kind: 'horizon_end', day: fc.endDay, label: 'the end of your semester', amountCents: 0 };
    return { kind: 'essentials', day: fc.today + k1, label: 'your everyday essentials', amountCents: 0 };
  }

  // The three questions this module answers. They share one timeline but are different questions, so the screen must not mix them up.
  E.MEANINGS = {
    immediate: { question: 'What is the most I could spend on ONE purchase right now?', means: 'A single payment up to this amount still leaves your balance at or above your cushion on every day through the end of the term.', notMeans: 'It is not a number to spend every day. Spending it all today leaves nothing for tomorrow.' },
    pace: { question: 'How much can I spend per day, spread evenly, and stay at or above my cushion?', means: 'Spending about this much each day keeps you at or above your cushion through the end of the term, and uses up the room by then.', notMeans: 'It is not what you can spend in one go. A large one-time purchase is limited by your lowest upcoming balance instead.' },
    monthly: { question: 'How much everyday spending does my plan support this month?', means: 'What you have spent this month plus the pace for the rest of the month.', notMeans: 'It is not a budget by itself. Your approved category budgets are your decisions and are compared with it.' }
  };

  // How far the balance falls AFTER the term, before the next aid/scholarship refund (or reserveBridgeMaxDays when none is scheduled).
  // Pure arithmetic on the same forecast; it never reads or changes the reserve setting. opts: { today, scenario, fc, det, base }
  function computeBridge(plan, opts) {
    const st = plan.settings, T = opts.today, scenario = opts.scenario || st.scenario;
    const fc = opts.fc || E.forecast(plan, { today: T, scenario, flex: 'none', det: opts.det, base: opts.base });
    if (!fc.ok) return null;
    const H = fc.endDay, N = fc.N, maxEnd = H + st.reserveBridgeMaxDays;
    const long = E.forecast(plan, { today: T, scenario, flex: 'none', det: opts.det || fc.det, base: opts.base || fc.base, endDay: maxEnd });
    if (!long.ok) return null;
    let aid = null;
    for (const e of long.events) if (e.type === 'income' && e.amountCents > 0 && e.day > H && (e.itype === 'aid' || e.itype === 'scholarship') && (aid === null || e.day < aid.day)) aid = e;
    const windowEnd = aid ? Math.min(maxEnd, aid.day - 1) : maxEnd;
    const balEnd = long.days[N].bal;
    let low = balEnd, lowDay = H, bills = 0, ess = 0, inc = 0;
    const items = [];
    for (let i = N + 1; i <= windowEnd - T && i < long.days.length; i++) {
      const r = long.days[i]; bills += r.obl + r.sav; ess += r.ess; inc += r.inc;
      if (r.bal < low) { low = r.bal; lowDay = r.day; }
    }
    for (const e of long.events) if (e.day > H && e.day <= windowEnd && e.amountCents < 0 && e.type !== 'purchase') items.push({ name: e.name, day: e.day, amountCents: -e.amountCents });
    const drawdown = Math.max(0, balEnd - low);
    return { startDay: H + 1, endDay: Math.max(H, windowEnd), days: Math.max(0, windowEnd - H), endedBy: aid ? 'aid' : 'limit', aidName: aid ? aid.name : '', aidDay: aid ? aid.day : null, lowDay, drawdownCents: drawdown, billsCents: bills, essentialsCents: ess, incomeCents: inc, endBalanceCents: balEnd, items };
  }

  // Optional money to keep for AFTER the term: a fixed amount plus a "bridge" to the next financial aid refund. Everything it needs comes from the same forecast.
  // It is applied ONLY when the student has turned it on (settings.reserveFixedCents / settings.reserveBridge). Nothing here ever turns it on.
  // opts: { today, scenario, fc (commitments timeline for the term), det, base }
  E.endReserve = function (plan, opts) {
    const st = plan.settings, fixed = st.reserveFixedCents || 0;
    const out = { enabled: fixed > 0 || !!st.reserveBridge, fixedCents: fixed, bridgeCents: 0, totalCents: fixed, bridge: null };
    if (!st.reserveBridge) return out;
    const b = computeBridge(plan, opts);
    if (!b) return out;
    out.bridgeCents = b.drawdownCents; out.totalCents = fixed + b.drawdownCents; out.bridge = Object.assign({}, b);
    delete out.bridge.items;
    return out;
  };
  E.HORIZON_EXPLAIN = {
    semester: 'The SEMESTER forecast runs from today to the last day of your term. Your room, daily pace and one-time purchase limit are all measured against that date and nothing else.',
    safety: 'The SAFETY outlook looks past the end of the term, to the next financial aid refund. It never changes your semester numbers. It shows what you will still have to pay between terms, so you can decide whether to set some money aside.'
  };
  // The financial-SAFETY outlook: what the weeks after the term will cost, shown separately from the semester forecast.
  // `recommend` is advice only. The reserve is applied only after the student chooses it (E.setReserve).
  E.safetyOutlook = function (plan, opts) {
    const st = plan.settings, T = opts.today, scenario = opts.scenario || st.scenario;
    const fc = opts.fc || E.forecast(plan, { today: T, scenario, flex: 'none', det: opts.det, base: opts.base });
    if (!fc.ok) return { ok: false, error: fc.error };
    const b = computeBridge(plan, { today: T, scenario, fc, det: opts.det, base: opts.base }), reserve = opts.reserve || E.endReserve(plan, { today: T, scenario, fc, det: opts.det, base: opts.base });
    const applied = reserve.totalCents, need = b ? b.drawdownCents : 0, gap = Math.max(0, need - applied);
    const C = fc.cushionCents, safetyEnd = Math.max(b ? b.endDay : fc.endDay, T + st.safetyHorizonDays);
    const dates = typeof E.planDateContext === 'function' ? E.planDateContext(plan, T, { ok: true, bridge: b }) : null;
    const untilAid = b && b.endedBy === 'aid'
      ? (dates && dates.aidScheduledDay != null && dates.aidCautiousDay != null && dates.aidScheduledDay !== dates.aidCautiousDay
        ? 'your next refund (' + b.aidName + ', scheduled ' + D.label(dates.aidScheduledDay) + '; counted ' + D.label(dates.aidCautiousDay) + ' in the cautious view)'
        : 'your next refund (' + b.aidName + ', ' + D.label(b.aidDay) + ')')
      : (b ? 'the ' + b.days + '-day limit, because no refund is scheduled' : 'the weeks after the term');
    return {
      ok: true, scenario, semesterEndDay: fc.endDay, safetyEndDay: safetyEnd, bridge: b, needsBetweenTermsCents: need, appliedReserveCents: applied, reserveEnabled: reserve.enabled,
      recommend: need > 0 && gap > 0, recommendedCents: need, gapCents: gap, dates,
      // if the student spends ALL the room the semester forecast shows, they reach the end of term with just the cushion (plus any reserve they chose)
      ifAllRoomSpent: { endOfTermCents: C + applied, lowCents: C + applied - need, lowDay: b ? b.lowDay : fc.endDay, belowCushionCents: gap, belowZeroCents: Math.max(0, gap - C) },
      explain: E.HORIZON_EXPLAIN,
      summary: need <= 0 ? 'Nothing you have listed is due between this term and your next refund, so there is nothing to earmark.'
        : 'After the term ends you still have about ' + E.fmt(need) + ' of bills and essentials until ' + untilAid + '.'
          + (applied >= need ? ' You have earmarked ' + E.fmt(applied) + ' in your plan, which covers it (not moved to another account).' : applied > 0 ? ' You have earmarked ' + E.fmt(applied) + ' in your plan (not moved to another account), which leaves ' + E.fmt(gap) + ' uncovered.' : ' None of it is earmarked right now, so spending all of your gross semester room would leave you about ' + E.fmt(gap) + ' short after the term.')
    };
  };
  // The student accepts the recommendation (the ONLY way a recommended reserve becomes part of the plan). Returns a new plan.
  E.acceptReserveRecommendation = function (plan, today, scenario) {
    const so = E.safetyOutlook(plan, { today, scenario: scenario || 'cautious' });
    if (!so.ok || !so.recommend) return { ok: false, error: 'There is nothing to set aside.', plan };
    return E.setReserve(plan, { bridge: true });
  };
  // The student's decision. Returns a new plan; nothing else ever changes these settings.
  E.setReserve = function (plan, r) {
    const p = E.clone(plan);
    if (r.fixedCents !== undefined) { const c = Math.round(Number(r.fixedCents)); if (!Number.isSafeInteger(c) || c < 0 || c > 1e9) return { ok: false, error: 'Enter an amount of $0 or more.', plan }; p.settings.reserveFixedCents = c; }
    if (r.bridge !== undefined) p.settings.reserveBridge = !!r.bridge;
    if (r.bridgeMaxDays !== undefined) { const n = Math.round(Number(r.bridgeMaxDays)); if (!Number.isFinite(n) || n < 14 || n > 180) return { ok: false, error: 'Choose between 14 and 180 days.', plan }; p.settings.reserveBridgeMaxDays = n; }
    return { ok: true, plan: p };
  };

  // "Show the math" lines for the window ending on day index k.
  function explainWindow(fc, openStart, k, U, divisor, reserveCents) {
    let inc = 0, obl = 0, sav = 0, ess = 0, pur = 0;
    for (let i = 0; i <= k; i++) { const d = fc.days[i]; inc += d.inc; obl += d.obl; sav += d.sav; ess += d.ess; pur += d.pur; }
    const date = D.label(fc.today + k);
    const lines = [
      { label: 'Spendable balance at the start of today', cents: openStart },
      { label: 'Income expected through ' + date, cents: inc },
      { label: 'Bills and required payments through ' + date, cents: -obl },
      { label: 'Savings transfers through ' + date, cents: -sav },
      { label: 'Everyday essentials set aside through ' + date, cents: -ess },
    ];
    if (pur) lines.push({ label: 'Planned purchase', cents: -pur });
    lines.push({ label: 'Safety cushion you keep', cents: -fc.cushionCents });
    if (reserveCents) lines.push({ label: 'Money you are keeping for after the term', cents: -reserveCents });
    lines.push({ label: 'Room to spend through ' + date, cents: U, total: true });
    if (divisor) lines.push({ label: 'Spread over ' + divisor + (divisor === 1 ? ' day' : ' days'), cents: Math.floor(U / divisor), total: true });
    return lines;
  }

  // opts: { today, scenario, fc (optional pre-built commitments timeline), det, base }
  E.capacity = function (plan, opts) {
    const T = opts.today, scenario = opts.scenario || plan.settings.scenario;
    const det = opts.det || E.detectRecurring(plan, T), base = opts.base || E.baseline(plan, T, det);
    const fc = opts.fc || E.forecast(plan, { today: T, scenario, flex: 'none', det, base });
    if (!fc.ok) return { ok: false, error: fc.error };
    const C = fc.cushionCents, N = fc.N, skip = detSkip(det);
    const spentToday = E.flexSpent(plan, T, T, skip), openStart = fc.open.cents + spentToday;
    const reserve = opts.reserve || E.endReserve(plan, { today: T, scenario, fc, det, base }), R = reserve.totalCents;
    const U0 = fc.days.map(d => d.bal + spentToday - C);          // room by day (commitments only), from the START of today
    const Ucur0 = fc.days.map(d => d.bal - C);                    // room by day, from RIGHT NOW (after today's logged spending)
    const U = U0.slice(), Ucur = Ucur0.slice(); U[N] -= R; Ucur[N] -= R;     // the optional reserve applies on the last day only
    let kLast = -1, kFirst = -1, minU0 = Infinity;
    for (let k = 0; k <= N; k++) { if (U[k] < 0) { kLast = k; if (kFirst < 0) kFirst = k; } if (U0[k] < minU0) minU0 = U0[k]; }
    const kFirstBill = U0.findIndex(x => x < 0), kLastBill = U0.reduce((m, x, k) => x < 0 ? k : m, -1);
    const shortfall = { exists: kFirstBill >= 0, firstDay: kFirstBill >= 0 ? fc.today + kFirstBill : null, lastDay: kLastBill >= 0 ? fc.today + kLastBill : null, maxCents: Math.max(0, -minU0) };
    const reserveShort = !shortfall.exists && R > 0 && U[N] < 0;

    // --- sustainable pace profile
    const x0 = kLast + 1, pts = [[x0, 0]];
    for (let k = kLast + 1; k <= N; k++) pts.push([k + 1, U[k]]);
    const verts = lowerHull(pts), S = new Array(N + 2).fill(0);
    for (let v = 0; v < verts.length - 1; v++) {
      const a = verts[v], b = verts[v + 1];
      for (let x = a[0]; x <= b[0]; x++) S[x] = Math.floor((a[1] * (b[0] - a[0]) + (x - a[0]) * (b[1] - a[1])) / (b[0] - a[0]));
    }
    const daily = []; for (let k = 0; k <= N; k++) daily.push(S[k + 1] - S[k]);
    const window = (kEnd) => S[Math.min(N, kEnd) + 1] - S[0];

    // --- what is limiting the pace today
    let limitedBy, paceExact = 0, kStar = null;
    if (shortfall.exists) limitedBy = { kind: 'shortfall', day: shortfall.firstDay, label: driver(fc, 0, kFirstBill, '').label, amountCents: shortfall.maxCents };
    else if (reserveShort) limitedBy = { kind: 'reserve', day: fc.endDay, label: 'the money you are keeping for after the term', amountCents: -U[N] };
    else if (verts.length >= 2) { kStar = verts[1][0] - 1; paceExact = verts[1][1] / verts[1][0]; limitedBy = driver(fc, 0, kStar); limitedBy.paceDay = fc.today + kStar; if (kStar === N && R > 0 && limitedBy.kind === 'horizon_end') limitedBy.label = 'the end of your term, plus the ' + E.fmt(R) + ' you are keeping for after it'; }
    else limitedBy = { kind: 'none', day: fc.today, label: '', amountCents: 0 };
    const explainPace = kStar !== null ? explainWindow(fc, openStart, kStar, U[kStar], kStar + 1, kStar === N ? R : 0) : null;

    // --- periods (spent counts flexible spending only; allowance = spent so far + room remaining)
    const ms = D.monthStart(T), meEff = Math.min(D.monthEnd(T), fc.endDay), startsOn = plan.settings.weekStartsOn;
    const wsClip = Math.max(D.weekStart(T, startsOn), ms), weEff = Math.min(D.weekEnd(T, startsOn), meEff);
    const period = (fromDay, endDay) => {
      const before = fromDay <= T - 1 ? E.flexSpent(plan, fromDay, T - 1, skip) : 0, room = window(endDay - T);
      return { endDay, spentCents: before + spentToday, allowanceCents: before + room, remainingCents: room - spentToday };
    };
    const today = { allowanceCents: daily[0], spentCents: spentToday, remainingCents: daily[0] - spentToday };
    const week = Object.assign(period(wsClip, weEff), { startDay: wsClip });
    const month = Object.assign(period(ms, meEff), { startDay: ms });
    const semester = { endDay: fc.endDay, remainingCents: S[N + 1] - spentToday, allowanceCents: S[N + 1] };

    // --- immediate lump-sum capacity from the CURRENT position
    let minCur = Infinity, kMin = 0;
    for (let k = 0; k <= N; k++) if (Ucur[k] < minCur) { minCur = Ucur[k]; kMin = k; }
    let minCur0 = Infinity; for (let k = 0; k <= N; k++) if (Ucur0[k] < minCur0) minCur0 = Ucur0[k];
    const immediate = { cents: Math.max(0, minCur), withoutReserveCents: Math.max(0, minCur0), limitedBy: minCur < 0 ? { kind: minCur0 < 0 ? 'shortfall' : 'reserve', day: fc.today + kMin, label: minCur0 < 0 ? driver(fc, 0, kMin).label : 'the money you are keeping for after the term', amountCents: -minCur } : (kMin === N && R > 0 && minCur0 > minCur ? { kind: 'reserve', day: fc.endDay, label: 'the money you are keeping for after the term', amountCents: R } : driver(fc, 0, kMin)), lowDay: fc.today + kMin,
      explain: explainWindow(fc, fc.open.cents, kMin, minCur, 0, kMin === N ? R : 0), meaning: E.MEANINGS.immediate };

    return {
      ok: true, scenario, today: T, cushionCents: C, endDay: fc.endDay, safe: !shortfall.exists, reserveShort, shortfall, reserve,
      immediate, pace: { dailyCents: daily[0], exactCentsPerDay: paceExact, limitedBy, explain: explainPace, meaning: E.MEANINGS.pace, segments: verts.length >= 2 ? verts.slice(1).map((v, i) => ({ throughDay: fc.today + v[0] - 1, ratePerDayCents: (v[1] - verts[i][1]) / (v[0] - verts[i][0]) })) : [] },
      todayLimit: today, week, month, semester, profile: { daily, cumulative: S, roomByDay: U }, openStartCents: openStart, fc
    };
  };

  /* ---------- "Can I afford this?" ---------- */
  // opts: { today, amountCents, day (default today), category (optional; lets a purchase use money already budgeted for that category) }
  E.affordability = function (plan, opts) {
    const T = opts.today, amount = Math.max(0, Math.round(opts.amountCents || 0)), det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det);
    const C = plan.account.cushionCents;
    const fcA = (scenario, flex, extra) => E.forecast(plan, { today: T, scenario, flex, det, base, extraEvents: extra });
    const probe = fcA('cautious', 'none', []);
    if (!probe.ok) return { ok: false, error: probe.error };
    const day = E.clamp(opts.day == null ? T : opts.day, T, probe.endDay);
    // part of the purchase that is already inside the category's monthly budget (so it is not counted twice)
    let funded = 0, catKind = opts.category ? E.catKind(opts.category) : null;
    if (opts.category && day <= D.monthEnd(T) && (catKind === 'essential' || catKind === 'flexible')) {
      const row = E.budgetStatus(plan, T, base).find(r => r.category === opts.category);
      if (row) funded = Math.min(amount, Math.max(0, row.remainingCents));
    }
    const extraA = catKind === 'essential' ? amount - funded : amount, extraB = (catKind === 'essential' || catKind === 'flexible') ? amount - funded : amount;
    const ev = x => (x > 0 ? [{ day, amountCents: -x, label: 'This purchase' }] : []);
    const aCau0 = probe, aExp0 = fcA('expected', 'none', []);
    const aCau = fcA('cautious', 'none', ev(extraA)), aExp = fcA('expected', 'none', ev(extraA));
    const bCau0 = fcA('cautious', 'budget', []), bCau = fcA('cautious', 'budget', ev(extraB));
    const m = f => f.metrics;
    const cap = E.capacity(plan, { today: T, scenario: 'cautious', fc: probe, det, base }), R = cap.reserve.totalCents;
    const usesReserve = R > 0 ? Math.max(0, Math.min(amount, C + R - m(aCau).endCents)) : 0;
    const alreadyShort = { cautious: m(aCau0).minCents < C, expected: m(aExp0).minCents < C };
    let verdict = 'affordable'; const reasons = [];
    const riskyExp = m(aExp).minCents < C, negCau = m(aCau).minCents < 0;
    if (amount === 0) reasons.push('Enter an amount above $0.');
    else if (riskyExp || negCau) {
      verdict = 'risky';
      if (riskyExp) reasons.push(alreadyShort.expected ? 'Your bills and essentials already leave you short before this purchase.' : 'After this purchase your balance would fall to ' + E.fmt(m(aExp).minCents) + ' on ' + D.label(m(aExp).minDay) + ', below your ' + E.fmt(C) + ' cushion, even if everything arrives on time.');
      else reasons.push('In the cautious case your balance would go below $0 on ' + D.label(m(aCau).firstNegativeDay) + '.');
    } else if (m(aCau).minCents < C || m(bCau).minCents < C) {
      verdict = 'tight';
      if (m(aCau).minCents < C) reasons.push(alreadyShort.cautious ? 'If income is lower or aid arrives late, you are already short without this purchase.' : 'If income is lower or aid arrives late, this would take you below your cushion on ' + D.label(m(aCau).minDay) + '.');
      else reasons.push('It fits your bills, but you would need to cut about ' + E.fmt(C - m(bCau).minCents) + ' from your planned flexible spending before ' + D.label(m(bCau).minDay) + '.');
    } else if (usesReserve > 0) {
      verdict = 'tight';
      reasons.push('It keeps you above your cushion, but it would use about ' + E.fmt(usesReserve) + ' of the ' + E.fmt(R) + ' you are keeping for after the term.');
    } else reasons.push('Your lowest projected balance stays at or above your ' + E.fmt(C) + ' cushion in both the expected and cautious cases, even after planned spending.');
    // earliest day the purchase fits (checked against bills AND planned flexible spending, cautious case)
    const bs = bCau0.days, suffix = new Array(bs.length); let mn = Infinity;
    for (let i = bs.length - 1; i >= 0; i--) { mn = Math.min(mn, bs[i].bal); suffix[i] = mn; }
    let earliest = null;
    for (let i = 0; i < bs.length; i++) { const need = bs[i].day <= D.monthEnd(T) ? extraB : amount; if (suffix[i] - need >= C) { earliest = bs[i].day; break; } }
    const goalImpact = plan.goals.filter(g => g.contribution).map(g => { const mo = E.monthlyEquivalent(g.contribution.schedule, g.contribution.amountCents); return { id: g.id, name: g.name, monthsOfContributions: mo > 0 ? Math.round(amount / mo * 10) / 10 : null }; });
    const mk = f => ({ minCents: m(f).minCents, minDay: m(f).minDay, firstBelowCushionDay: m(f).firstBelowCushionDay, firstNegativeDay: m(f).firstNegativeDay, shortfallCents: m(f).shortfallCents });
    return {
      ok: true, amountCents: amount, day, category: opts.category || '', fundedByBudgetCents: funded, verdict, reasons, alreadyShort,
      cautious: mk(aCau), expected: mk(aExp), plannedCautious: mk(bCau), earliestSafeDay: earliest, waitDays: earliest === null ? null : earliest - T,
      lumpCapacityCents: cap.immediate.cents, reserveCents: R, usesReserveCents: usesReserve, limitedBy: cap.immediate.limitedBy, todayRemainingCents: cap.todayLimit.remainingCents, withinTodayPace: amount <= cap.todayLimit.remainingCents && cap.safe, goalImpact,
      afterPurchase: { cautiousMinCents: m(aCau).minCents, expectedMinCents: m(aExp).minCents }
    };
  };

  /* ---------- monthly flexible budget ---------- */
  // Splits `total` cents across weights so the parts add up to EXACTLY total (largest-remainder method).
  E.allocate = function (total, weights) {
    const keys = Object.keys(weights), sum = E.sum(keys, k => Math.max(0, weights[k]));
    const out = {};
    if (total <= 0 || sum <= 0) { for (const k of keys) out[k] = 0; return out; }
    let given = 0; const rem = [];
    for (const k of keys) { const exact = total * Math.max(0, weights[k]) / sum, f = Math.floor(exact); out[k] = f; given += f; rem.push([k, exact - f]); }
    rem.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1));
    for (let i = 0; given < total && i < rem.length; i++, given++) out[rem[i][0]]++;
    return out;
  };
  // Does the student's approved flexible budget fit what the plan supports this month? Suggestions are never applied automatically.
  E.monthlyPlan = function (plan, opts) {
    const T = opts.today, det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det), cap = E.capacity(plan, { today: T, scenario: opts.scenario, det, base });
    if (!cap.ok) return { ok: false, error: cap.error };
    const status = E.budgetStatus(plan, T, base), flex = status.filter(r => r.kind === 'flexible'), planned = E.sum(flex, r => r.plannedCents);
    const supported = cap.month.allowanceCents, wants = {};
    for (const r of flex) { const h = base.categories[r.category]; wants[r.category] = h && h.monthlyCents > 0 ? h.monthlyCents : r.plannedCents; }
    const desired = E.sum(Object.keys(wants), k => wants[k]), target = Math.min(supported, desired), alloc = E.allocate(target, wants);
    const over = planned > supported;
    const suggestions = over ? flex.map(r => ({ category: r.category, fromCents: r.plannedCents, toCents: alloc[r.category] || 0, reason: 'Your plan supports ' + E.fmt(supported) + ' of flexible spending this month, but your budgets add up to ' + E.fmt(planned) + '.' })).filter(s => s.toCents !== s.fromCents) : [];
    return { ok: true, scenario: cap.scenario, month: cap.month, supportedFlexibleCents: supported, plannedFlexibleCents: planned, gapCents: supported - planned, status: over ? 'over_capacity' : 'fits', categories: status, suggestions, safe: cap.safe };
  };
})(CCE);

;
/* ===== engine/07-scenarios.js ===== */
/* =========================================================================
   07 scenarios — stress tests, "what would this change do?", weekly check-ins, one-call snapshot
   -------------------------------------------------------------------------
   Every claim about the effect of a change comes from RE-RUNNING the forecast on a copy of the
   plan with that change applied. Nothing here is a rule of thumb, and nothing here edits the
   student's real plan.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;

  E.STRESS_TESTS = [
    { id: 'aidLate', label: 'Financial aid arrives 2 weeks late', params: { days: 14 } },
    { id: 'workCut', label: 'Work hours drop by 25%', params: { pct: 25 } },
    { id: 'surprise', label: 'A surprise $300 expense', params: { amountCents: 30000 } },
    { id: 'rentIncrease', label: 'Rent goes up by $50 a month', params: { amountCents: 5000 } },
    { id: 'cutFlex', label: 'Flexible spending drops by 20%', params: { pct: 20 } }
  ];

  // Returns { plan, assumptions } — a modified COPY. `change.today` is needed by the types that read the current budget.
  E.applyChange = function (plan, change) {
    let p = E.clone(plan);
    const assumptions = [], T = change.today;
    const monthlyOf = c => { const r = E.effectiveBudgets(p, T).find(b => b.category === c); return r ? r.monthlyCents : 0; };
    const setApproved = (cat, cents) => { let b = p.budgets.find(x => x.category === cat); if (!b) { b = { category: cat, approvedCents: null, recommendedCents: null, source: 'student' }; p.budgets.push(b); } b.approvedCents = Math.max(0, cents); };
    switch (change.type) {
      case 'aidLate': {
        const n = Math.max(0, Math.round(change.days || 0));
        for (const i of p.incomes) if (i.type === 'aid' || i.type === 'scholarship') i.delayDays += n;
        assumptions.push('Every financial aid and scholarship deposit arrives ' + n + ' days later than scheduled.');
        break;
      }
      case 'workCut': {
        const f = 100 - E.clamp(Math.round(change.pct || 0), 0, 100);
        for (const i of p.incomes) if (i.type === 'job' || i.type === 'workstudy' || i.type === 'gig') { i.amountCents = Math.round(i.amountCents * f / 100); if (i.lowCents != null) i.lowCents = Math.round(i.lowCents * f / 100); }
        assumptions.push('Paychecks from jobs, work-study and gigs are ' + (100 - f) + '% smaller from now on.');
        break;
      }
      case 'surprise': {
        let day = change.day ? D.parse(change.day) : T; const amt = Math.round(change.amountCents || 0);
        if (day === null) day = T;
        // Anything dated on or before the balance date is already inside the verified balance, so a hypothetical expense must land AFTER it.
        const anchor = D.parse(p.account.asOf); if (anchor !== null && day <= anchor) day = anchor + 1;
        p.obligations.push({ id: 'stress-' + p.obligations.length, name: change.label || 'Unexpected expense', category: 'Other', kind: 'oneTime', schedule: { freq: 'once', anchor: D.fmt(day) }, amountCents: amt, highCents: null, essential: true, source: 'user', verified: true, reliability: 'certain', vendorKey: '', note: '' });
        assumptions.push('An unexpected ' + E.fmt(amt) + ' expense on ' + D.label(day === null ? T : day) + '.');
        break;
      }
      case 'rentIncrease': {
        const inc = change.amountCents != null ? Math.round(change.amountCents) : null;
        for (const o of p.obligations) if (o.category === 'Housing' && (!change.id || o.id === change.id)) { const add = inc != null ? inc : Math.round(o.amountCents * (change.pct || 0) / 100); o.amountCents += add; if (o.highCents != null) o.highCents += add; }
        assumptions.push('Housing payments go up by ' + (inc != null ? E.fmt(inc) : (change.pct || 0) + '%') + ' per payment.');
        break;
      }
      case 'delayOneTime': {
        const o = p.obligations.find(x => x.id === change.id);
        if (o && o.schedule && o.schedule.anchor && o.schedule.freq === 'once') { const n = Math.round(change.days || 0); o.schedule.anchor = D.fmt(D.parse(o.schedule.anchor) + n); assumptions.push('"' + o.name + '" is paid ' + n + ' days later.'); }
        break;
      }
      case 'cutBudget': {
        const cat = change.category, cur = monthlyOf(cat);
        const delta = change.weeklyCents != null ? Math.round(change.weeklyCents * 30.4375 / 7) : Math.round(change.monthlyCents || 0);     // negative = spend less
        setApproved(cat, cur + delta);
        assumptions.push((delta < 0 ? 'Spend ' : 'Spend ') + E.fmt(Math.abs(delta)) + ' per month ' + (delta < 0 ? 'less' : 'more') + ' on ' + cat + ' (about ' + E.fmt(Math.abs(Math.round(delta * 7 / 30.4375))) + ' per week).');
        break;
      }
      case 'cutFlex': {
        const f = 100 - E.clamp(Math.round(change.pct || 0), 0, 100);
        for (const b of E.effectiveBudgets(p, T)) if (b.kind === 'flexible') setApproved(b.category, Math.round(b.monthlyCents * f / 100));
        assumptions.push('Every flexible category (dining out, fun, shopping…) is cut by ' + (100 - f) + '%.');
        break;
      }
      case 'cancelObligation': {
        const o = p.obligations.find(x => x.id === change.id);
        if (o) { p.obligations = p.obligations.filter(x => x.id !== change.id); assumptions.push('"' + o.name + '" is cancelled.'); }
        break;
      }
      case 'pauseGoal': {
        const g = p.goals.find(x => x.id === change.id);
        if (g) { g.contribution = null; assumptions.push('Saving for "' + g.name + '" is paused.'); }
        break;
      }
      // goal changes use the same writer as E.applyGoalPlan (14-goals), so what is tested here is exactly what would be applied
      case 'goalContribution': case 'goalDeadline': case 'goalPriority': case 'goalPlan': {
        const choice = change.type === 'goalPlan' ? (change.choice || {})
          : { goals: [change.type === 'goalContribution' ? { id: change.id, amountCents: Math.max(0, Math.round(change.amountCents || 0)), schedule: change.schedule }
            : change.type === 'goalDeadline' ? { id: change.id, dueDate: change.dueDate || '' } : { id: change.id, priority: E.clamp(Math.round(change.priority || 1), 1, 99) }] };
        for (const c of choice.goals || []) {
          const g = p.goals.find(x => x.id === c.id); if (!g) continue;
          if (c.amountCents !== undefined) assumptions.push(c.amountCents > 0 ? 'Save ' + E.fmt(c.amountCents) + ' per transfer for "' + g.name + '".' : 'No more transfers for "' + g.name + '".');
          if (c.dueDate !== undefined) assumptions.push('"' + g.name + '" is due ' + (c.dueDate ? D.label(D.parse(c.dueDate)) : 'with no deadline') + '.');
          if (c.priority !== undefined && c.priority !== g.priority) assumptions.push('"' + g.name + '" has priority ' + c.priority + '.');
        }
        if (choice.discretionary && choice.discretionary.weeklyCents != null) assumptions.push('Discretionary spending is ' + E.fmt(choice.discretionary.weeklyCents) + ' a week.');
        p = E.writeGoalChoice(p, choice, T);
        break;
      }
      default: break;
    }
    return { plan: p, assumptions };
  };

  function summarize(plan, T, flex) {
    const det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det), out = {};
    for (const s of ['cautious', 'expected']) {
      const fc = E.forecast(plan, { today: T, scenario: s, flex, det, base });
      if (!fc.ok) return null;
      const m = fc.metrics;
      out[s] = { endCents: m.endCents, minCents: m.minCents, minDay: m.minDay, firstBelowCushionDay: m.firstBelowCushionDay, firstNegativeDay: m.firstNegativeDay, shortfallCents: m.shortfallCents, belowZeroCents: m.belowZeroCents };
    }
    out.endDay = E.horizonInfo(plan, T).endDay;
    return out;
  }
  // Compare the plan before and after a change. flex:'budget' includes the student's planned flexible spending.
  E.evaluateChange = function (plan, change, opts) {
    const T = opts.today, flex = opts.flex || 'budget';
    const c = Object.assign({}, change, { today: T }), applied = E.applyChange(plan, c);
    const before = summarize(plan, T, flex), after = summarize(applied.plan, T, flex);
    if (!before || !after) return { ok: false, error: 'no_balance' };
    const d = k => ({ endCents: after[k].endCents - before[k].endCents, minCents: after[k].minCents - before[k].minCents, shortfallCents: after[k].shortfallCents - before[k].shortfallCents });
    const gs = pl => E.goalStatus(pl, T).goals.map(g => ({ id: g.goalId, name: g.name, completionDay: g.completionDay, onTrack: g.onTrack, currentCents: g.currentContributionCents, requiredCents: g.required ? g.required.perContributionCents : null }));
    const g0 = gs(plan), g1 = gs(applied.plan);
    const goals = g1.map(a => { const b = g0.find(x => x.id === a.id) || { completionDay: null, onTrack: false, currentCents: 0, requiredCents: null }; return { id: a.id, name: a.name, completionDay: { before: b.completionDay, after: a.completionDay }, onTrack: { before: b.onTrack, after: a.onTrack }, contributionCents: { before: b.currentCents, after: a.currentCents } }; });
    return { ok: true, type: change.type, assumptions: applied.assumptions, before, after, delta: { cautious: d('cautious'), expected: d('expected') }, goals, horizonEndDay: before.endDay, verified: true, flex };
  };
  E.stressTest = function (plan, testId, opts) {
    const t = E.STRESS_TESTS.find(x => x.id === testId);
    if (!t) return { ok: false, error: 'unknown_test' };
    const r = E.evaluateChange(plan, Object.assign({ type: t.id }, t.params, opts.params || {}), opts);
    r.label = t.label;
    return r;
  };

  /* ---------- weekly check-in ---------- */
  // The student types their real balance. We compare it with what the forecast predicted, explain the gap,
  // and make the real balance the new anchor. Transactions dated on/before the check-in date are, from now on,
  // treated as already inside the balance, so nothing is counted twice.
  E.checkIn = function (plan, opts) {
    const T = opts.today, actual = Math.round(opts.balanceCents);
    if (!Number.isSafeInteger(actual) || Math.abs(actual) > 1e9) return { ok: false, error: 'Enter a balance as a number.', plan };
    const fc = E.forecast(plan, { today: T, scenario: 'expected', flex: 'none' });
    if (!fc.ok) return { ok: false, error: 'Set your starting balance first.', plan };
    // The student types the balance they see RIGHT NOW. The comparable forecast number is the reconstructed balance before any of today's
    // still-scheduled items, i.e. what has been recorded, assumed or estimated up to this moment.
    const projected = fc.open.cents, comp = fc.open.components;
    const diff = actual - projected, unlogged = comp.unloggedSpendingCents;
    const p = E.clone(plan);
    // Income due today that has not been matched to a deposit stays "not arrived yet" after the check-in (it is not silently assumed to be in the new balance).
    const keep = fc.occurrences.filter(o => o.nominal === T && o.kind === 'income' && o.status === 'scheduled' && !o.txId);
    for (const o of keep) { const key = E.occurrenceKey('income', o.id, o.nominal); if (!p.resolutions.some(r => r.key === key)) p.resolutions.push({ key, status: 'unpaid' }); }
    p.resolutions = p.resolutions.slice(-400);
    p.account.balanceCents = actual; p.account.asOf = D.fmt(T); p.account.seq = ++p.seq;
    p.checkIns = (p.checkIns || []).concat([{ date: D.fmt(T), actualCents: actual, projectedCents: projected }]).slice(-200);
    let insight;
    if (Math.abs(diff) <= 100) insight = 'Right on track: your real balance is within $1 of the forecast.';
    else if (diff < 0) insight = 'You have ' + E.fmt(-diff) + ' less than forecast' + (unlogged > 0 ? '. We had assumed ' + E.fmt(unlogged) + ' of everyday spending you did not log, so you likely spent about ' + E.fmt(unlogged - diff) + ' in total since your last check-in.' : '. This is probably spending that was not logged, or a bill that cost more than expected.');
    else insight = 'You have ' + E.fmt(diff) + ' more than forecast' + (unlogged > 0 ? ', which suggests you spent less than the ' + E.fmt(unlogged) + ' we assumed.' : '. Money may have arrived that was not in the plan, or a bill was lower or skipped.');
    return {
      ok: true, plan: p, projectedCents: projected, actualCents: actual, diffCents: diff, insight,
      explain: { anchorCents: comp.anchorCents, recordedCents: comp.recordedCents, loggedCents: comp.loggedCents, assumedIncomeCents: comp.assumedIncomeCents, assumedBillsCents: comp.assumedBillsCents, assumedSavingsCents: comp.assumedSavingsCents, unloggedSpendingCents: unlogged, unloggedBy: comp.unloggedBy },
      impliedUnloggedSpendCents: Math.max(0, unlogged - diff), pending: fc.pending, priorStaleDays: fc.staleDays
    };
  };

  /* ---------- how much should anyone trust today's numbers? ---------- */
  E.planConfidence = function (plan, snap) {
    const reasons = [];
    const fc = snap.cautious.fc, base = snap.base;
    let level = 'good';
    const down = to => { const order = ['good', 'estimated', 'limited', 'provisional']; if (order.indexOf(to) > order.indexOf(level)) level = to; };
    if (fc.staleDays > plan.settings.staleDays) { reasons.push('Your balance was last confirmed ' + fc.staleDays + ' days ago. A check-in would make today\'s numbers more reliable.'); down('limited'); }
    if (base.status === 'provisional') {
      const approved = plan.budgets.some(b => b.approvedCents != null);
      if (base.coverageDays > 0) reasons.push('Only ' + base.coverageDays + ' day' + (base.coverageDays === 1 ? '' : 's') + ' of transactions: too few to estimate your everyday spending, so ' + (approved ? 'only the budgets you entered are included' : 'it is NOT included yet') + '. Add your own budget estimates or import more history.');
      else reasons.push(approved ? 'Everyday spending comes from your estimates, not from transaction history.' : 'We have no spending history or budget yet, so everyday spending is missing.');
      down(approved ? 'estimated' : 'provisional');
    }
    else if (base.status === 'limited') { reasons.push('Spending estimates come from only ' + base.coverageDays + ' days of history.'); down('estimated'); }
    if (fc.horizon.provisional) { reasons.push('Semester dates have not been confirmed.'); down('estimated'); }
    const unverified = plan.incomes.filter(i => !i.verified && i.reliability !== 'uncertain' && i.schedule);
    if (unverified.length) { reasons.push(unverified.length + ' income item' + (unverified.length > 1 ? 's are' : ' is') + ' not verified yet (' + unverified.map(i => i.name).slice(0, 2).join(', ') + ').'); down('estimated'); }
    if (fc.pending.length) { reasons.push(fc.pending.length + ' expected payment' + (fc.pending.length > 1 ? 's have' : ' has') + ' no matching transaction yet. Did it happen?'); down('estimated'); }
    if (fc.uncounted.length) { reasons.push('Some uncertain money is not counted (' + [...new Set(fc.uncounted.map(u => u.name))].slice(0, 2).join(', ') + '). That is upside, not a promise.'); }
    const det = fc.det.filter(r => !r.ignored && !r.matched);
    if (det.length) reasons.push(det.length + ' recurring charge' + (det.length > 1 ? 's were' : ' was') + ' detected but not confirmed. They are included as estimates.');
    if (base.cardSpendingHidden) { reasons.push('Most of your outflow is credit-card payments. Import the card statement so categories are accurate.'); down('estimated'); }
    return { level, reasons, provisional: level === 'provisional' };
  };

  /* ---------- how each income is treated, and how much it moves the recommendation ---------- */
  // One row per scheduled income. `impact` is how much that income adds to the CAUTIOUS numbers (the ones that drive warnings), found by
  // re-running the same model without it. For income that is not counted, `upsideIfReliable` is what it WOULD add if it turned out to be reliable.
  E.incomeTreatment = function (plan, T) {
    const det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det);
    const run = pl => { const c = E.capacity(pl, { today: T, scenario: 'cautious', det, base }); return c.ok ? { paceCents: c.todayLimit.allowanceCents, immediateCents: c.immediate.cents, semesterCents: c.semester.allowanceCents, lowestCents: c.fc.metrics.minCents } : null; };
    const whole = run(plan), diff = (a, b) => ({ paceCents: a.paceCents - b.paceCents, immediateCents: a.immediateCents - b.immediateCents, semesterCents: a.semesterCents - b.semesterCents, lowestCents: a.lowestCents - b.lowestCents });
    if (!whole) return { ok: false, error: 'no_balance', rows: [] };
    const rows = [];
    for (const inc of plan.incomes) {
      if (!inc.schedule || inc.amountCents <= 0) continue;
      const counted = inc.reliability !== 'uncertain', aidLike = inc.type === 'aid' || inc.type === 'scholarship';
      const lateDays = counted ? inc.delayDays + (inc.reliability === 'likely' && aidLike ? plan.settings.cautiousLateDays : 0) : 0;
      const cautiousAmt = counted ? E.cautiousIncomeCents(plan, inc) : 0;
      const row = { id: inc.id, name: inc.name, type: inc.type, reliability: inc.reliability, verified: inc.verified, source: inc.source,
        expected: { counted, amountCents: counted ? inc.amountCents : 0, delayDays: counted ? inc.delayDays : 0 },
        cautious: { counted, amountCents: cautiousAmt, delayDays: lateDays, reason: counted ? E.cautiousReason(plan, inc) : 'uncertain income is never counted' }, impact: null, upsideIfReliable: null, explain: '' };
      const mutate = f => { const q = E.clone(plan); f(q.incomes.find(x => x.id === inc.id)); return E.normalizePlan(q).plan; };
      if (counted) {
        const without = run(E.normalizePlan(Object.assign(E.clone(plan), { incomes: plan.incomes.filter(x => x.id !== inc.id) })).plan);
        row.impact = without ? diff(whole, without) : null;
        row.explain = (inc.verified ? 'Counted at ' + E.fmt(inc.amountCents) + ' per payment in the expected case. ' : 'Counted at ' + E.fmt(inc.amountCents) + ' per payment in the expected case, but you have not verified it. ')
          + (cautiousAmt !== inc.amountCents ? 'The cautious case counts ' + E.fmt(cautiousAmt) + ' (' + row.cautious.reason + '). ' : 'The cautious case counts the same amount. ')
          + (lateDays > inc.delayDays ? 'It assumes the money arrives ' + plan.settings.cautiousLateDays + ' days late. ' : '')
          + (row.impact ? 'Without it, today\'s cautious pace would be ' + E.fmt(Math.max(0, row.impact.paceCents)) + ' a day lower.' : '');
      } else {
        const withIt = run(mutate(x => { x.reliability = 'likely'; }));
        row.upsideIfReliable = withIt ? diff(withIt, whole) : null;
        row.explain = 'Not counted in either case because it is uncertain. It is upside, not a promise.' + (row.upsideIfReliable ? ' If it did arrive, today\'s cautious pace would rise by about ' + E.fmt(Math.max(0, row.upsideIfReliable.paceCents)) + ' a day.' : '');
      }
      rows.push(row);
    }
    return { ok: true, whole, rows };
  };

  /* ---------- one call that gives every screen (and Finley) the same numbers ---------- */
  // opts.det / opts.base: reuse an existing detect/baseline (purchase preview freezes estimates so a
  // hypothetical transaction cannot invent or inflate recurring category spend).
  E.snapshot = function (plan, today, opts) {
    opts = opts || {};
    const det = opts.det || E.detectRecurring(plan, today), base = opts.base || E.baseline(plan, today, det);
    const build = scenario => {
      const fc = E.forecast(plan, { today, scenario, flex: 'none', det, base });
      if (!fc.ok) return fc;
      return { fc, capacity: E.capacity(plan, { today, scenario, fc, det, base }), planned: E.forecast(plan, { today, scenario, flex: 'budget', det, base }) };
    };
    const cautious = build('cautious'), expected = build('expected');
    if (!cautious.fc || !cautious.fc.ok) return { ok: false, error: 'no_balance' };
    const snap = { ok: true, today, det, base, cautious, expected, headline: plan.settings.scenario === 'expected' ? expected : cautious };
    snap.budgetStatus = E.budgetStatus(plan, today, base);
    snap.recommendations = E.recommendBudgets(plan, today, base);
    snap.confidence = E.planConfidence(plan, snap);
    return snap;
  };
})(CCE);

;
/* ===== engine/08-safeguards.js ===== */
/* =========================================================================
   08 safeguards — how much to trust the numbers, and what each number is made of
   -------------------------------------------------------------------------
   Two promises this module keeps for every screen:

   1. NEVER A MISLEADINGLY GENEROUS NUMBER.
      E.trust() decides whether a spending allowance can be shown at all.
        needs_info   something essential is missing (no food estimate, unknown housing cost). No allowance is shown.
                     The student is asked ONE targeted question that fixes it.
        provisional  there is an estimate, but it rests on thin evidence, unconfirmed dates, or open questions.
                     The number is shown labelled "provisional" and says why.
        estimated    reasonable evidence, a few things unconfirmed.
        confident    verified balance, strong evidence, nothing open.
      No level ever says "safe to spend" or "guaranteed". The forecast is a plan built on stated assumptions.

   2. EVERY DOLLAR HAS A LABEL.
      E.transparency() splits the plan into four separate layers so they are never blended:
        actual     things that really happened (recorded transactions)
        reserved   money held back on purpose (cushion, bills, essentials, an optional end-of-term reserve)
        expected   things we are ASSUMING (income not yet arrived, bills assumed paid, unlogged spending)
        projected  the resulting cash balance, with its lowest point
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;

  E.TRUST_LEVELS = ['needs_info', 'provisional', 'estimated', 'confident'];
  E.TRUST_WORDING = {
    needs_info: { badge: 'Needs one answer', allowance: null, summary: 'We need one more answer before we can show a spending amount that is not misleading.' },
    provisional: { badge: 'Provisional', allowance: 'Provisional daily pace', summary: 'A starting estimate built on limited information. It will change as you add real transactions.' },
    estimated: { badge: 'Estimated', allowance: 'Estimated daily pace', summary: 'A reasonable estimate. A few things are still unconfirmed.' },
    confident: { badge: 'Confirmed', allowance: 'Daily pace', summary: 'Based on information you have confirmed. It is still a forecast, not a guarantee.' }
  };

  // The targeted questions that can unblock a plan. `kind` tells the screen which input to draw.
  const QUESTIONS = {
    groceries: { id: 'groceries', kind: 'amount', category: 'Groceries', label: 'Groceries', why: 'Food is your biggest everyday cost and we have no purchases or estimate for it. Without it, any "room to spend" would quietly leave food out.', question: 'About how much do you spend on groceries in a typical month?', choices: [15000, 25000, 35000, 45000] },
    housing: { id: 'housing', kind: 'housing', label: 'Housing', why: 'Rent is usually the largest bill. Without it, your room to spend would look much bigger than it really is.', question: 'Do you pay rent or a housing bill?' }
  };
  E.QUESTIONS = QUESTIONS;

  // snap is optional (pass the result of E.snapshot to avoid recomputing)
  E.trust = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    if (!snap || !snap.ok) {
      return { ok: false, level: 'blocked', badge: 'Needs your balance', showAllowance: false, guaranteed: false, missing: [{ id: 'balance', kind: 'balance', label: 'Checking balance', why: 'Everything starts from what is in your checking account today.', question: 'What is your checking balance right now?' }], reasons: [], labels: [], questions: [], wording: { badge: 'Needs your balance', allowance: null, summary: 'Enter your checking balance to begin.' } };
    }
    const base = snap.base, eff = E.effectiveBudgets(plan, T, base), fc = snap.cautious.fc, cap = snap.cautious.capacity;
    const missing = [], reasons = [], labels = [];
    const groc = eff.find(b => b.category === 'Groceries');
    if (!groc) missing.push(QUESTIONS.groceries);
    const hasHousing = plan.obligations.some(o => o.category === 'Housing' && o.schedule && o.amountCents > 0) || snap.det.some(r => !r.ignored && r.category === 'Housing');
    if (!hasHousing && plan.meta.living !== 'Living with family' && plan.meta.living !== 'On campus' && plan.answered.indexOf('no_housing_cost') < 0) missing.push(QUESTIONS.housing);

    let level = missing.length ? 'needs_info' : snap.confidence.level === 'good' ? 'confident' : snap.confidence.level === 'estimated' ? 'estimated' : 'provisional';
    const down = to => { if (level === 'needs_info') return; if (E.TRUST_LEVELS.indexOf(to) < E.TRUST_LEVELS.indexOf(level)) level = to; };
    // Thin evidence about an ESSENTIAL (food, transportation) changes how much room is shown, so it caps the trust level.
    // Thin evidence about a flexible category does not change the room (flexible budgets are what the room is spent on), so it is labelled but does not cap it.
    const thin = eff.filter(b => b.evidence === 'thin' && b.kind === 'essential'), thinFlex = eff.filter(b => b.evidence === 'thin' && b.kind !== 'essential');
    if (thin.length) {
      down('provisional');
      labels.push({ id: 'thin', text: 'Provisional: ' + thin.map(b => b.category).join(', ') + ' ' + (thin.length === 1 ? 'is' : 'are') + ' estimated from very few purchases. The estimate only applies from today forward.' });
    }
    if (thinFlex.length) labels.push({ id: 'thin_flex', text: thinFlex.map(b => b.category).join(', ') + ' ' + (thinFlex.length === 1 ? 'rests' : 'rest') + ' on very few purchases. It does not change your room, only how you might spend it.' });
    const generic = plan.budgets.filter(b => b.approvedCents != null && b.source === 'generic' && b.approvedCents > 0).map(b => b.category);
    if (generic.length) labels.push({ id: 'generic', text: generic.join(', ') + ' use' + (generic.length === 1 ? 's' : '') + ' a generic starter amount you approved. It is a plan, not a measurement of your spending.' });
    if (groc && groc.basis === 'recommended' && groc.evidence === 'suggested') { down('provisional'); labels.push({ id: 'suggested', text: 'Groceries uses a suggested amount you have not approved yet.' }); }
    if (base.status === 'provisional' && !missing.length && !thin.length && !plan.budgets.some(b => b.approvedCents != null)) down('provisional');
    if (fc.horizon.provisional) labels.push({ id: 'dates', text: 'Semester dates are a guess until you confirm them. The semester numbers end on ' + D.label(fc.endDay) + '.' });
    if (snap.cautious.fc.matchQuestions && snap.cautious.fc.matchQuestions.length) { down('estimated'); labels.push({ id: 'match', text: snap.cautious.fc.matchQuestions.length + ' deposit' + (snap.cautious.fc.matchQuestions.length > 1 ? 's' : '') + ' might be a scheduled paycheck. Until you confirm, the money is counted once, as the deposit.' }); }
    for (const r of snap.confidence.reasons) reasons.push(r);
    if (fc.staleDays > plan.settings.staleDays) down('provisional');
    if (cap && cap.ok && !cap.safe) labels.push({ id: 'short', text: 'Your listed bills and essentials already use up your cushion. Spending room is $0 until that changes.' });

    const questions = missing.map(m => Object.assign({ blocking: true }, m));
    for (const q of (fc.matchQuestions || [])) questions.push(Object.assign({ blocking: false, id: 'match:' + q.incomeId + ':' + D.fmt(q.nominal) }, q));
    const showAllowance = level !== 'needs_info' && !!(cap && cap.ok);
    const w = E.TRUST_WORDING[level];
    return { ok: true, level, badge: w.badge, showAllowance, guaranteed: false, allowanceLabel: showAllowance ? w.allowance : null, summary: w.summary, missing, reasons, labels, questions, estimates: eff.map(b => ({ category: b.category, basis: b.basis, evidence: b.evidence, monthlyCents: b.monthlyCents, forwardOnly: !!b.forwardOnly, why: b.evidenceWhy })), wording: w };
  };

  // Answers to the targeted questions. Each returns a NEW plan and records exactly what the student said.
  //   groceries: v = cents per month           (the student's own number is their approved budget)
  //   housing:   v = { amountCents, day }  or  { none: true }
  E.answerQuestion = function (plan, id, v) {
    const p = E.clone(plan);
    if (id === 'groceries') {
      const c = Math.round(Number(v));
      if (!Number.isSafeInteger(c) || c < 0 || c > 1e7) return { ok: false, error: 'Enter a monthly amount of $0 or more.', plan };
      return E.setBudget(p, 'Groceries', c);
    }
    if (id === 'housing') {
      if (v && v.none) { if (p.answered.indexOf('no_housing_cost') < 0) p.answered.push('no_housing_cost'); return { ok: true, plan: p }; }
      const a = Math.round(Number(v && v.amountCents)), day = Math.round(Number(v && v.day));
      if (!Number.isSafeInteger(a) || a <= 0 || a > 1e7) return { ok: false, error: 'Enter your monthly rent as an amount above $0.', plan };
      if (!(day >= 1 && day <= 31)) return { ok: false, error: 'Enter the day of the month rent is due (1 to 31).', plan };
      p.obligations = p.obligations.filter(o => !(o.category === 'Housing' && o.source === 'estimated'));
      p.obligations.push({ id: E.newId(p, 'ob', new Set(p.obligations.map(o => o.id))), name: E.safeStr(v.name, 60, 'Rent') || 'Rent', category: 'Housing', kind: 'bill', schedule: { freq: 'monthly', day }, amountCents: a, highCents: null, essential: true, source: 'user', verified: true, reliability: 'certain', vendorKey: '', note: '' });
      return { ok: true, plan: E.normalizePlan(p).plan };
    }
    return { ok: false, error: 'Unknown question.', plan };
  };

  /* ---------- the four layers ---------- */
  E.transparency = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    if (!snap || !snap.ok) return { ok: false };
    const scenario = plan.settings.scenario === 'expected' ? snap.expected : snap.cautious, fc = scenario.fc, cap = scenario.capacity, comp = fc.open.components;
    const sum = k => { let s = 0; for (const d of fc.days) s += d[k]; return s; };
    const monthStart = D.monthStart(T);
    let monthSpent = 0; const byCat = {};
    for (const t of E.activeTxs(plan)) {
      const d = D.parse(t.date); if (d < monthStart || d > T || t.flow !== 'spend') continue;
      monthSpent += -t.amountCents; byCat[t.category || 'Other'] = (byCat[t.category || 'Other'] || 0) + -t.amountCents;
    }
    const eff = E.effectiveBudgets(plan, T, snap.base), reserveLines = [];
    for (const b of eff.filter(x => x.kind === 'essential')) reserveLines.push({ label: b.category + ' (set aside each day)', basis: b.basis, evidence: b.evidence, forwardOnly: b.forwardOnly });
    const reserved = {
      cushionCents: fc.cushionCents, billsToTermEndCents: sum('obl'), savingsTransfersCents: sum('sav'), essentialsToTermEndCents: sum('ess'), endOfTermReserveCents: cap && cap.reserve ? cap.reserve.totalCents : 0,
      essentialLines: reserveLines, note: 'Held back on purpose. None of it is counted as spendable.'
    };
    const expected = {
      incomeNotYetArrivedCents: sum('inc'), assumedIncomeCents: comp.assumedIncomeCents, assumedBillsCents: comp.assumedBillsCents, assumedSavingsCents: comp.assumedSavingsCents, unloggedSpendingCents: comp.unloggedSpendingCents, unloggedBy: comp.unloggedBy,
      notCounted: fc.uncounted.map(u => ({ name: u.name, cents: u.amountCents, reason: u.reason })), note: 'Assumptions, not facts. Each one is replaced by a real number when you log, import or check in.'
    };
    const actual = { monthSpendingCents: monthSpent, monthByCategory: Object.keys(byCat).map(c => ({ category: c, cents: byCat[c] })).sort((a, b) => b.cents - a.cents), recordedSinceBalanceCents: comp.recordedCents, transactionCount: E.activeTxs(plan).length, note: 'Only transactions you logged or imported.' };
    const projected = { scenario: fc.scenario, balanceNowCents: fc.open.cents, lowestCents: fc.metrics.minCents, lowestDay: fc.metrics.minDay, endOfTermCents: fc.metrics.endCents, termEndDay: fc.endDay, note: 'What the model thinks your checking balance will be if the assumptions above hold.' };
    const trust = E.trust(plan, T, snap);
    const room = { semesterCents: cap ? cap.semester.allowanceCents : 0, dailyPaceCents: cap ? cap.todayLimit.allowanceCents : 0, oneTimeCents: cap ? cap.immediate.cents : 0, safe: cap ? cap.safe : false, shown: trust.showAllowance, label: trust.allowanceLabel, level: trust.level };
    return { ok: true, actual, reserved, expected, projected, room, trust, safety: E.safetyOutlook(plan, { today: T, scenario: scenario.fc.scenario, fc, base: snap.base, det: snap.det }) };
  };
})(CCE);

;
/* ===== engine/09-import-review.js ===== */
/* =========================================================================
   09 import review — a bank file never enters the plan without the student's confirmation
   -------------------------------------------------------------------------
   Step 1  E.reviewStatement(plan, text, opts)   READ ONLY. Returns everything the student must check:
             mapping     which column was read as Date / Description / Amount (and how to change it)
             direction   which sign means spending vs deposits, and which account the file is from
             dates       whether 03/04 means March 4 or April 3 (only when it is genuinely ambiguous)
             attention   rows the engine could not classify with confidence:
                           unexplained deposits, possible transfers between the student's own accounts,
                           Zelle / Venmo style payments, and spending with no clear category
             duplicates and future-dated rows that will be skipped
   Step 2  E.applyStatementReview(plan, review, decisions, today)
             refuses to add anything until every required confirmation is true
             (the 'attention' confirmation is satisfied by deciding every flagged row, or by the student
             explicitly accepting the suggested handling for all of them), then imports using the
             student's decisions, which override the automatic classification.
   Nothing here changes the plan unless applyStatementReview succeeds, and it returns a NEW plan.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const RE = () => E.DESC_PATTERNS;

  // What the student can pick for a flagged row. Each option is (flow, category).
  const OPTIONS = {
    unexplained_deposit: [
      { id: 'income', label: 'Pay or other income', flow: 'income' },
      { id: 'aid', label: 'Financial aid or scholarship', flow: 'aid' },
      { id: 'refund', label: 'A refund', flow: 'refund' },
      { id: 'transfer', label: 'My own money moving between accounts', flow: 'transfer' }
    ],
    peer_in: [
      { id: 'income', label: 'Money someone gave or paid me', flow: 'income' },
      { id: 'refund', label: 'Someone paying me back', flow: 'refund' },
      { id: 'transfer', label: 'My own money', flow: 'transfer' }
    ],
    peer_out: [
      { id: 'spend', label: 'Spending (choose a category)', flow: 'spend', needsCategory: true },
      { id: 'rent', label: 'Rent or housing', flow: 'spend', category: 'Housing' },
      { id: 'transfer', label: 'My own money', flow: 'transfer' }
    ],
    possible_transfer: [
      { id: 'transfer', label: 'Moving my own money (not spending or income)', flow: 'transfer' },
      { id: 'asis', label: 'No, these are separate', flow: null }
    ],
    uncategorized: [{ id: 'spend', label: 'Choose a category', flow: 'spend', needsCategory: true }, { id: 'transfer', label: 'Not spending (own account)', flow: 'transfer' }]
  };
  E.IMPORT_OPTIONS = OPTIONS;

  const groupOf = flow => flow === 'spend' ? 'spending' : flow === 'income' ? 'income' : flow;

  E.reviewStatement = function (plan, text, opts) {
    opts = opts || {};
    let parsed;
    try { parsed = E.parseStatement(text, { mapping: opts.mapping, signMode: opts.signMode, dateOrder: opts.dateOrder }); }
    catch (e) { return { ok: false, error: String(e && e.message || 'That file could not be read.') }; }
    const today = opts.today;
    // account: a credit-card export usually lists purchases as POSITIVE numbers
    const cardLike = /^Positive amounts look like spending/.test(parsed.note || '');      // mixed signs with positive = spending: the shape of a credit-card export (the student confirms)
    const account = opts.account === 'card' || opts.account === 'checking' ? opts.account : (cardLike ? 'card' : 'checking');
    const have = {}; for (const t of plan.transactions) if (t.source !== 'manual') { const k = E.fingerprint(t); have[k] = (have[k] || 0) + 1; }
    const seen = {};
    const rows = parsed.rows.map((r, idx) => {
      const day = D.parse(r.date);
      const c = r.forceTransfer ? { flow: 'transfer', category: '', review: false } : E.classify(r.desc, r.amountCents, plan.catRules);
      if (account === 'card' && r.amountCents > 0 && c.flow !== 'refund') { c.flow = 'transfer'; c.category = ''; }
      const row = { idx, date: r.date, desc: r.desc, amountCents: r.amountCents, flow: c.flow, category: c.category, group: groupOf(c.flow), flags: [], status: 'ok' };
      const k = E.fingerprint({ date: r.date, amountCents: r.amountCents, account, desc: r.desc });
      seen[k] = (seen[k] || 0) + 1;
      if (seen[k] <= (have[k] || 0)) row.status = 'duplicate';
      else if (typeof today === 'number' && day > today) row.status = 'future';
      return row;
    });
    // flags that need a human
    const live = rows.filter(r => r.status === 'ok');
    for (const r of live) {
      const t = r.desc, inc = r.amountCents > 0;
      if (RE().peer.test(t) && (r.flow === 'income' || r.flow === 'spend')) r.flags.push(inc ? 'peer_in' : 'peer_out');
      else if (r.flow === 'income' && c0(r, plan)) r.flags.push('unexplained_deposit');
      else if (r.flow === 'spend' && r.category === 'Other') r.flags.push('uncategorized');
    }
    // equal and opposite amounts a few days apart are usually the student's own money moving
    for (const a of live) {
      if (a.amountCents >= 0 || a.flow !== 'spend' || Math.abs(a.amountCents) < 2000) continue;
      const b = live.find(x => x !== a && x.flow === 'income' && x.amountCents === -a.amountCents && Math.abs(D.parse(x.date) - D.parse(a.date)) <= 3);
      if (b) { if (a.flags.indexOf('possible_transfer') < 0) a.flags.push('possible_transfer'); if (b.flags.indexOf('possible_transfer') < 0) b.flags.push('possible_transfer'); a.pair = b.idx; b.pair = a.idx; }
    }
    const attention = [];
    for (const r of live) {
      if (!r.flags.length) continue;
      const kind = r.flags.indexOf('possible_transfer') >= 0 ? 'possible_transfer' : r.flags[0];
      r.attentionKind = kind;
      const opt = OPTIONS[kind] || [];
      const suggested = kind === 'possible_transfer' ? 'transfer' : kind === 'unexplained_deposit' ? 'income' : kind === 'peer_in' ? 'income' : kind === 'peer_out' ? 'spend' : 'spend';
      attention.push({ idx: r.idx, kind, date: r.date, desc: r.desc, amountCents: r.amountCents, pairIdx: r.pair != null ? r.pair : null, question: QUESTION_TEXT[kind](r), options: opt, suggested, currentFlow: r.flow, currentCategory: r.category });
    }
    const counts = { total: rows.length, spending: 0, income: 0, aid: 0, refund: 0, transfer: 0, card_payment: 0, duplicate: 0, future: 0 };
    for (const r of rows) { if (r.status === 'duplicate') counts.duplicate++; else if (r.status === 'future') counts.future++; else counts[r.group] = (counts[r.group] || 0) + 1; }
    const spendingCents = E.sum(live.filter(r => r.flow === 'spend'), r => -r.amountCents), incomeCents = E.sum(live.filter(r => r.flow === 'income' || r.flow === 'aid'), r => r.amountCents), movedCents = E.sum(live.filter(r => r.flow === 'transfer' || r.flow === 'card_payment'), r => Math.abs(r.amountCents));
    const first = parsed.first, last = parsed.last, coverageDays = first && last ? D.parse(last) - D.parse(first) + 1 : 0;

    const required = [{ id: 'mapping', label: 'Columns' }, { id: 'direction', label: 'Spending vs deposits' }];
    if (parsed.ambiguousDates) required.push({ id: 'dates', label: 'Date format' });
    if (attention.length) required.push({ id: 'attention', label: 'Rows to check' });
    const allPositive = /All amounts are positive/.test(parsed.note || '');
    return {
      ok: true, account, accountSuggested: cardLike ? 'card' : 'checking', rows, attention, counts, coverageDays, first, last, required,
      mapping: { detected: parsed.mapping, headers: parsed.headers, options: parsed.headers.map((h, i) => ({ index: i, header: String(h || '').slice(0, 40) })), sample: rows.slice(0, 3).map(r => ({ date: r.date, desc: r.desc, amountCents: r.amountCents })) },
      direction: { mode: parsed.mode, note: parsed.note, risky: allPositive || (parsed.mode === 'positive'), spendingSample: live.filter(r => r.amountCents < 0).slice(0, 3).map(r => ({ desc: r.desc, amountCents: r.amountCents })), depositSample: live.filter(r => r.amountCents > 0).slice(0, 3).map(r => ({ desc: r.desc, amountCents: r.amountCents })), signMode: opts.signMode || 'auto' },
      dates: { order: parsed.dateOrder, ambiguous: !!parsed.ambiguousDates },
      totals: { spendingCents, incomeCents, movedCents }, skipped: parsed.skipped, readFrom: { dateOrder: parsed.dateOrder, signMode: opts.signMode || 'auto' }
    };
  };
  // an unexplained deposit = classify() said "income, review"
  function c0(r, plan) { const c = E.classify(r.desc, r.amountCents, plan.catRules); return c.flow === 'income' && c.review; }
  const QUESTION_TEXT = {
    unexplained_deposit: r => 'A deposit of ' + E.fmt(r.amountCents) + ' ("' + r.desc + '") has no clear source. What was it?',
    peer_in: r => E.fmt(r.amountCents) + ' came in from a person-to-person app ("' + r.desc + '"). What was it?',
    peer_out: r => E.fmt(-r.amountCents) + ' went out through a person-to-person app ("' + r.desc + '"). What was it for?',
    possible_transfer: r => E.fmt(Math.abs(r.amountCents)) + ' went ' + (r.amountCents < 0 ? 'out' : 'in') + ' and the same amount went ' + (r.amountCents < 0 ? 'in' : 'out') + ' within 3 days. Is this you moving your own money?',
    uncategorized: r => E.fmt(-r.amountCents) + ' at "' + r.desc + '" did not match a category. Which one fits?'
  };

  // decisions: { confirmed: { mapping:true, direction:true, dates:true, attention:true }, rows: { [idx]: { option:'transfer' | ..., category?:'Groceries' } } }
  // Returns { ok:false, missing:[ids] } until every required confirmation is true. Never changes the plan unless ok.
  E.applyStatementReview = function (plan, review, decisions, today) {
    if (!review || !review.ok) return { ok: false, error: 'There is nothing to import.', missing: [], plan };
    decisions = decisions || {}; const conf = decisions.confirmed || {}, rowDec = decisions.rows || {};
    const missing = [];
    for (const req of review.required) {
      if (req.id === 'attention') {
        const allDecided = review.attention.every(a => rowDec[a.idx] && rowDec[a.idx].option);
        if (!conf.attention && !allDecided) missing.push('attention');
      } else if (!conf[req.id]) missing.push(req.id);
    }
    if (missing.length) return { ok: false, error: 'Please confirm: ' + missing.join(', ') + '.', missing, plan };
    const byIdx = {}; for (const a of review.attention) byIdx[a.idx] = a;
    const rows = []; let overrides = 0;
    for (const r of review.rows) {
      if (r.status !== 'ok') continue;
      const out = { date: r.date, desc: r.desc, amountCents: r.amountCents };
      const a = byIdx[r.idx], d = rowDec[r.idx];
      const optId = d && d.option ? d.option : (a && conf.attention ? a.suggested : null);
      if (a && optId) {
        const opt = (a.options || []).find(o => o.id === optId);
        if (opt && opt.flow) { out.overrideFlow = opt.flow; if (opt.category) out.overrideCategory = opt.category; if (d && E.CATEGORIES[d.category]) out.overrideCategory = d.category; overrides++; }
        else if (opt && !opt.flow && d && E.CATEGORIES[d.category]) out.overrideCategory = d.category;
        // 'asis' (no override): the automatic classification stands
      } else if (d && d.category && E.CATEGORIES[d.category]) out.overrideCategory = d.category;
      rows.push(out);
    }
    const res = E.importTransactions(plan, rows, { account: review.account, batch: 'import-' + (today != null ? D.fmt(today) : 'now'), today });
    return Object.assign(res, { ok: true, reviewed: { overrides, attentionRows: review.attention.length, confirmed: Object.keys(conf).filter(k => conf[k]) } });
  };
})(CCE);

;
/* ===== engine/10-onboarding.js ===== */
/* =========================================================================
   10 onboarding — from "I just opened it" to a first personalized plan with minimal effort
   -------------------------------------------------------------------------
   Product rules this module enforces (all pure functions: plan in, new plan out, nothing reads the clock):

   1. ONE mandatory input: today's checking balance. Everything else has a sensible default or is skippable.
      (School defaults to the University of Kentucky; semester dates default to typical dates and are labelled unconfirmed.)
   2. A bank CSV is the main way to personalize (E.reviewStatement / E.applyStatementReview, then E.detectedSetup).
      With no CSV, a short manual setup asks only for the things the plan cannot honestly work without.
   3. Only questions that block an honest number are "needed" (E.trust().missing). Everything else is optional and says what it improves.
   4. Budgets are PROPOSED (E.proposeBudgets) and become part of the plan only when the student approves them (E.approveBudgets).
      A proposal says where it came from (history, the student's answer, a generic starter split) and how much to trust it.
   5. Every screen can say how sure we are (E.confidenceSummary) and what would make the plan better.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const fail = (plan, error) => ({ ok: false, error, plan });
  const roundDown5 = c => Math.floor(c / 500) * 500;
  const roundTo5 = c => Math.round(c / 500) * 500;
  const isMoney = (c, max) => Number.isSafeInteger(c) && c > 0 && c <= (max || 1e8);

  E.SCHOOLS = {
    'University of Kentucky': {
      short: 'UK', city: 'Lexington, Kentucky',
      calendarNote: 'These are typical fall and spring dates, not your official calendar. Confirm them when you can.'
    }
  };
  E.ONBOARDING = {
    mandatory: [{ id: 'balance', label: 'Checking balance today' }],
    defaults: { school: E.DEMO_SCHOOL, cushionCents: 10000 },
    steps: {
      csv: ['welcome', 'basics', 'import', 'review', 'found', 'income', 'needs', 'optional', 'budgets', 'plan'],
      manual: ['welcome', 'basics', 'income', 'needs', 'optional', 'budgets', 'plan']
    }
  };

  /* ---------- 1. the mandatory step ---------- */
  // o: { today (day number), balanceCents, school?, name?, living?, cushionCents?, demo? }
  E.startPlan = function (o) {
    o = o || {};
    const bal = Math.round(Number(o.balanceCents));
    if (o.balanceCents === '' || o.balanceCents == null || !Number.isSafeInteger(bal) || Math.abs(bal) > 1e9) return { ok: false, error: 'Enter your checking balance as a number, for example 842.50.' };
    if (!Number.isSafeInteger(o.today)) return { ok: false, error: 'Today\'s date is missing.' };
    const cushion = o.cushionCents == null ? E.ONBOARDING.defaults.cushionCents : Math.round(Number(o.cushionCents));
    const plan = E.newPlan({
      meta: { name: o.name || '', school: o.school || E.ONBOARDING.defaults.school, living: o.living || 'Off campus', demo: o.demo || '' },
      periods: E.defaultPeriods(o.today),
      account: { balanceCents: bal, asOf: D.fmt(o.today), cushionCents: Number.isSafeInteger(cushion) && cushion >= 0 ? cushion : 10000 }
    });
    return { ok: true, plan };
  };
  // Where the student is in setup, in one object. Only the balance is mandatory.
  E.onboardingStatus = function (plan, T) {
    const hasBalance = D.parse(plan.account.asOf) !== null && Number.isSafeInteger(plan.account.balanceCents) && !!(plan.account.asOf);
    if (!hasBalance) return { hasBalance: false, mandatoryDone: false, blocking: ['balance'], complete: false, next: 'basics' };
    const t = E.trust(plan, T), blocking = t.missing.map(m => m.id);
    return { hasBalance: true, mandatoryDone: true, blocking, complete: blocking.length === 0, next: blocking.length ? 'needs' : 'plan', level: t.level };
  };

  /* ---------- 2. small, validated edits (each returns a NEW plan) ---------- */
  E.setMeta = function (plan, m) {
    const p = E.clone(plan); m = m || {};
    if (m.name !== undefined) p.meta.name = E.safeStr(m.name, 40);
    if (m.school !== undefined) p.meta.school = E.safeStr(m.school, 80) || E.ONBOARDING.defaults.school;
    if (m.living !== undefined) { if (E.LIVING.indexOf(m.living) < 0) return fail(plan, 'Choose where you live from the list.'); p.meta.living = m.living; }
    return { ok: true, plan: E.normalizePlan(p).plan };
  };
  const answered = (p, id) => { if (p.answered.indexOf(id) < 0) p.answered.push(id); };
  E.markAnswered = function (plan, id) { const p = E.clone(plan); answered(p, E.safeStr(id, 60)); return { ok: true, plan: p }; };

  E.setCushion = function (plan, cents) {
    const c = Math.round(Number(cents));
    if (!Number.isSafeInteger(c) || c < 0 || c > 500000) return fail(plan, 'Choose a cushion from $0 to $5,000.');
    const p = E.clone(plan); p.account.cushionCents = c; answered(p, 'cushion_set');
    return { ok: true, plan: E.normalizePlan(p).plan };
  };
  E.currentPeriod = function (plan, T) { const h = E.horizonInfo(plan, T); return plan.periods.find(p => p.name === h.period && p.kind === 'semester') || null; };
  // The student confirms (or corrects) the dates of the semester the forecast ends with. Marks them confirmed.
  E.confirmSemester = function (plan, T, o) {
    const per = E.currentPeriod(plan, T);
    if (!per) return fail(plan, 'There is no semester to confirm yet.');
    const s = D.parse(o && o.start), e = D.parse(o && o.end);
    if (s === null || e === null) return fail(plan, 'Enter both dates (year-month-day).');
    if (e < s) return fail(plan, 'The last day has to come after the first day.');
    if (e < T) return fail(plan, 'That last day has already passed.');
    if (e - s > 250) return fail(plan, 'A semester is shorter than that. Check the dates.');
    const p = E.clone(plan), q = p.periods.find(x => x.id === per.id); q.start = D.fmt(s); q.end = D.fmt(e); q.verified = true;
    return { ok: true, plan: E.normalizePlan(p).plan };
  };

  const INCOME_NAMES = { job: 'Paycheck', workstudy: 'Work-study paycheck', aid: 'Financial aid refund', scholarship: 'Scholarship', family: 'Family support', gig: 'Gig or side work', other: 'Other income' };
  E.INCOME_CHOICES = [
    { id: 'job', label: 'Paycheck', freq: 'biweekly' }, { id: 'workstudy', label: 'Work-study', freq: 'biweekly' }, { id: 'aid', label: 'Financial aid refund', freq: 'once' },
    { id: 'scholarship', label: 'Scholarship', freq: 'once' }, { id: 'family', label: 'Family support', freq: 'monthly' }, { id: 'gig', label: 'Gig or side work', freq: 'weekly' }
  ];
  // o: { type, name?, amountCents, freq: weekly|biweekly|semimonthly|monthly|once, nextDate (YYYY-MM-DD), employer?, irregular?, lowCents?, reliability? }
  // Family support and gig work start as 'uncertain' (not counted) until the student says they can count on it.
  E.addIncome = function (plan, o) {
    o = o || {};
    if (E.INCOME_TYPES.indexOf(o.type) < 0) return fail(plan, 'Choose what kind of money this is.');
    const amt = Math.round(Number(o.amountCents));
    if (!isMoney(amt)) return fail(plan, 'Enter an amount above $0.');
    if (['weekly', 'biweekly', 'semimonthly', 'monthly', 'once'].indexOf(o.freq) < 0) return fail(plan, 'Choose how often it arrives.');
    const next = D.parse(o.nextDate);
    if (next === null) return fail(plan, 'Enter the date it arrives next (year-month-day).');
    const sch = { freq: o.freq, anchor: D.fmt(next) };
    if (o.freq === 'monthly') sch.day = D.ymd(next).d;
    if (o.freq === 'semimonthly') { const dd = D.ymd(next).d; sch.days = dd <= 15 ? [dd, Math.min(28, dd + 15)] : [dd - 15, dd]; }
    const p = E.clone(plan), irregular = !!o.irregular || o.type === 'gig';
    let low = null;
    if (o.lowCents != null && o.lowCents !== '') { low = Math.round(Number(o.lowCents)); if (!Number.isSafeInteger(low) || low < 0 || low > amt) return fail(plan, 'The low amount cannot be above the usual amount.'); }
    const id = E.newId(p, 'in', new Set(p.incomes.map(x => x.id)));
    p.incomes.push({ id, name: E.safeStr(o.name, 60) || INCOME_NAMES[o.type], type: o.type, schedule: sch, amountCents: amt, lowCents: low, irregular, source: 'user', verified: true, reliability: ['certain', 'likely', 'uncertain'].indexOf(o.reliability) >= 0 ? o.reliability : (o.type === 'family' ? 'uncertain' : 'likely'), delayDays: 0, note: '', employer: E.safeStr(o.employer, 60), payerHints: [] });
    return { ok: true, plan: E.normalizePlan(p).plan, id };
  };
  const BILL_KIND = { 'Tuition & fees': 'tuition', 'Debt payment': 'debt', 'Subscriptions': 'subscription' };
  E.BILL_CATEGORIES = ['Phone', 'Utilities', 'Subscriptions', 'Insurance', 'Debt payment', 'Tuition & fees', 'Housing'];
  // Monthly bills retain the day-of-month default; other repeats require an anchor date.
  E.addBill = function (plan, o) {
    o = o || {};
    if (E.BILL_CATEGORIES.indexOf(o.category) < 0) return fail(plan, 'Choose a bill type from the list.');
    const amt = Math.round(Number(o.amountCents)), day = Math.round(Number(o.day));
    if (!isMoney(amt)) return fail(plan, 'Enter the bill amount above $0.');
    const freq = o.freq || 'monthly';
    if (['monthly', 'weekly', 'biweekly', 'yearly'].indexOf(freq) < 0) return fail(plan, 'Choose how often the bill repeats.');
    const next = D.parse(o.nextDate);
    if (freq === 'monthly' && !(day >= 1 && day <= 31)) return fail(plan, 'Enter the day of the month it is due (1 to 31).');
    if (freq !== 'monthly' && next === null) return fail(plan, 'Enter the next due date (year-month-day).');
    const schedule = freq === 'monthly' ? { freq, day } : { freq, anchor: D.fmt(next), start: D.fmt(next) };
    const p = E.clone(plan), id = E.newId(p, 'ob', new Set(p.obligations.map(x => x.id)));
    p.obligations.push({ id, name: E.safeStr(o.name, 60) || o.category, category: o.category, kind: BILL_KIND[o.category] || 'bill', schedule, amountCents: amt, highCents: null, essential: o.category !== 'Subscriptions', source: 'user', verified: true, reliability: 'certain', vendorKey: '', note: '' });
    return { ok: true, plan: E.normalizePlan(p).plan, id };
  };
  E.removeItem = function (plan, kind, id) {
    const p = E.clone(plan);
    if (kind === 'income') p.incomes = p.incomes.filter(x => x.id !== id); else if (kind === 'bill') p.obligations = p.obligations.filter(x => x.id !== id); else return fail(plan, 'Unknown item.');
    return { ok: true, plan: p };
  };

  /* ---------- 3. what a bank file revealed that needs a yes/no ---------- */
  // Repeating charges and paychecks found in the imported history. Nothing here changes the plan; the student confirms each one.
  E.detectedSetup = function (plan, T) {
    const bills = E.detectRecurring(plan, T).filter(r => r.flow === 'spend' && !r.ignored && !r.matched)
      .map(r => ({ key: r.key, name: r.name, category: r.category, amountCents: r.amountCents, cadence: r.cadence, count: r.count, confidence: r.confidence, reason: r.reason, nextDay: r.nextDay, preselected: r.confidence !== 'low' }));
    const incomes = E.detectIncome(plan, T).filter(r => !r.matched)
      .map(r => ({ key: r.key, name: r.name, cadence: r.cadence, typicalCents: r.typicalCents, lowCents: r.lowCents, highCents: r.highCents, irregular: r.irregular, count: r.count, nextDay: r.nextDay, preselected: true,
        reason: 'Seen ' + r.count + ' times, ' + (r.cadence === 'weekly' ? 'every week' : r.cadence === 'biweekly' ? 'every 2 weeks' : r.cadence === 'semimonthly' ? 'twice a month' : 'every month') + (r.irregular ? ', and the amount changes a lot' : '') }));
    return { bills, incomes };
  };
  // sel: { billKeys: [], rejectBillKeys: [], incomeKeys: [] }. Only what the student ticked is added.
  E.confirmDetected = function (plan, T, sel) {
    sel = sel || {};
    const det = E.detectRecurring(plan, T), dinc = E.detectIncome(plan, T), p = E.clone(plan); let addedBills = 0, addedIncomes = 0, ignoredBills = 0;
    const ids = new Set(p.obligations.map(x => x.id).concat(p.incomes.map(x => x.id)));
    for (const key of sel.billKeys || []) {
      const r = det.find(x => x.key === key && x.flow === 'spend'); if (!r) continue;
      p.obligations.push({ id: E.newId(p, 'ob', ids), name: r.name, category: r.category, kind: BILL_KIND[r.category] || 'bill', schedule: r.schedule, amountCents: r.amountCents, highCents: null, essential: r.category !== 'Subscriptions', source: 'detected', verified: true, reliability: 'certain', vendorKey: r.key, note: 'Found in your bank file and confirmed.' });
      ids.add(p.obligations[p.obligations.length - 1].id); addedBills++;
    }
    for (const key of sel.rejectBillKeys || []) { if (det.some(x => x.key === key) && p.ignored.indexOf('out|' + key) < 0) { p.ignored.push('out|' + key); ignoredBills++; } }
    for (const key of sel.incomeKeys || []) {
      const r = dinc.find(x => x.key === key); if (!r) continue;
      p.incomes.push({ id: E.newId(p, 'in', ids), name: r.name, type: 'job', schedule: r.schedule, amountCents: r.typicalCents, lowCents: r.irregular ? r.lowCents : null, irregular: r.irregular, source: 'detected', verified: true, reliability: 'likely', delayDays: 0, note: 'Found in your bank file and confirmed.', employer: '', payerHints: [r.key] });
      ids.add(p.incomes[p.incomes.length - 1].id); addedIncomes++;
    }
    return { ok: true, plan: E.normalizePlan(p).plan, addedBills, addedIncomes, ignoredBills };
  };

  /* ---------- 4. monthly category budgets: proposed, then approved by the student ---------- */
  E.BUDGET_CATEGORIES = ['Groceries', 'Transportation', 'Dining out', 'Entertainment', 'Shopping', 'Personal', 'Other'];
  // A generic starting split of the flexible money, used ONLY for categories with no history. It is labelled as generic everywhere it appears.
  E.STARTER_WEIGHTS = { 'Dining out': 30, 'Entertainment': 20, 'Shopping': 20, 'Personal': 15, 'Other': 15 };
  const STARTER_FRACTION_PCT = 90;       // never plan to spend the whole supported amount; keep a margin
  const BASIS_LABEL = { approved: 'You approved this', history: 'From your spending', thin: 'From very few purchases', starter: 'Generic starter split', answer: 'Your answer', none: 'No estimate' };
  const CONF_LABEL = { student: 'Your number', high: 'Strong evidence', medium: 'Fair evidence', low: 'Rough guess', none: 'No evidence' };
  E.BUDGET_BASIS_LABEL = BASIS_LABEL; E.BUDGET_CONFIDENCE_LABEL = CONF_LABEL;

  // What the plan can support for flexible spending in an average month, from the cautious scenario (never from the optimistic one).
  function supportedMonthly(cap, T) {
    if (!cap || !cap.ok) return 0;
    const days = Math.max(1, cap.endDay - T + 1);
    return Math.max(0, Math.round(cap.semester.allowanceCents * 30.4375 / days));
  }
  E.proposeBudgets = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    if (!snap || !snap.ok) return { ok: false, error: 'Enter your checking balance first.', rows: [] };
    const base = snap.base, rec = E.recommendBudgets(plan, T, base), trust = E.trust(plan, T, snap), cap = snap.cautious.capacity;
    const supported = trust.showAllowance ? supportedMonthly(cap, T) : 0, rows = [];
    for (const c of E.BUDGET_CATEGORIES) {
      const b = plan.budgets.find(x => x.category === c), r = rec.find(x => x.category === c), kind = E.catKind(c);
      const row = { category: c, kind, status: 'none', amountCents: null, proposedCents: null, basis: 'none', confidence: 'none', forwardOnly: false, evidence: r ? r.evidence : 'none', why: '', editable: true };
      if (b && b.approvedCents != null) {
        // an approved budget keeps the strength of the evidence it came from; approving a rough guess does not make it a measurement
        const src = b.source, ev = r ? r.evidence : 'none';
        Object.assign(row, { status: 'approved', amountCents: b.approvedCents, proposedCents: b.approvedCents,
          basis: src === 'thin' ? 'thin' : src === 'generic' ? 'starter' : src === 'accepted' ? 'history' : 'answer',
          confidence: src === 'thin' || src === 'generic' ? 'low' : src === 'accepted' ? (ev === 'strong' ? 'high' : 'medium') : 'student',
          forwardOnly: src === 'thin' && (ev === 'thin' || ev === 'none'),
          why: src === 'thin' ? 'You approved an estimate that rests on very few purchases. It stays labelled as rough until there is more history.' : src === 'generic' ? 'You approved a generic starter amount. It is a plan, not a measurement.' : src === 'accepted' ? 'You approved a suggestion based on your spending.' : 'You set this yourself.' });
      }
      else if (r && r.recommendedCents != null) { Object.assign(row, { status: 'proposed', proposedCents: r.recommendedCents, basis: 'history', confidence: r.evidence === 'strong' ? 'high' : 'medium', why: 'Based on what you actually spent: ' + r.evidenceWhy }); }
      else if (r && r.thinMonthlyCents != null) { Object.assign(row, { status: 'proposed', proposedCents: r.thinMonthlyCents, basis: 'thin', confidence: 'low', forwardOnly: true, why: r.evidenceWhy + ' Treated as a cautious estimate from today forward only.' }); }
      else if (c === 'Groceries') { Object.assign(row, { status: 'needs_answer', why: 'No grocery purchases or answer yet. Tell us a monthly amount so food is not left out.' }); }
      row.starter = row.status === 'none' && kind === 'flexible';
      rows.push(row);
    }
    // generic split for flexible categories that have no evidence, limited to what is left of the supported amount
    const flexUsed = E.sum(rows.filter(r => r.kind === 'flexible' && (r.status === 'approved' || r.status === 'proposed')), r => r.status === 'approved' ? r.amountCents : r.proposedCents);
    const pool = Math.max(0, Math.floor(supported * STARTER_FRACTION_PCT / 100) - flexUsed), need = rows.filter(r => r.starter);
    let starterTotal = 0, starterNote = '';
    if (!trust.showAllowance) starterNote = 'Generic starter amounts are held back until we have the answers your plan needs. A generic split of money we cannot see would be misleading.';
    else if (need.length && pool < 500 * need.length) starterNote = supported > 0 ? 'There is not enough room left in your plan to suggest generic amounts for the remaining categories.' : 'Your plan does not support any extra spending money right now, so no generic amounts are suggested.';
    else if (need.length) {
      const w = {}; for (const r of need) w[r.category] = E.STARTER_WEIGHTS[r.category] || 10;
      const alloc = E.allocate(pool, w);
      for (const r of need) { const v = roundDown5(alloc[r.category] || 0); if (v >= 500) { Object.assign(r, { status: 'proposed', proposedCents: v, basis: 'starter', confidence: 'low', why: 'A generic split of the flexible money your plan supports, not based on your spending. Adjust it to fit your life.' }); starterTotal += v; } }
    }
    for (const r of rows) delete r.starter;
    for (const r of rows) { r.basisLabel = BASIS_LABEL[r.basis]; r.confidenceLabel = CONF_LABEL[r.confidence]; }
    const plannedFlexible = E.sum(rows.filter(r => r.kind === 'flexible' && (r.status === 'approved' || r.status === 'proposed')), r => r.status === 'approved' ? r.amountCents : r.proposedCents);
    return {
      ok: true, level: trust.level, showAllowance: trust.showAllowance, rows, supportedMonthlyFlexibleCents: supported, plannedFlexibleCents: plannedFlexible, starterTotalCents: starterTotal,
      fits: plannedFlexible <= supported, starterNote,
      irregularNote: 'Rent, tuition, textbooks, travel and medical costs are not turned into a monthly habit. Add them as bills, or set your own budget when you know the amount.'
    };
  };
  // items: [{ category, cents, fromProposal, basis }]. fromProposal is true only when the amount was not edited; basis keeps a weak proposal labelled weak.
  // Only the student's confirm action calls this.
  E.approveBudgets = function (plan, items) {
    let p = E.clone(plan), n = 0; const errors = [];
    for (const it of items || []) {
      const cents = Math.round(Number(it && it.cents));
      const r = E.setBudget(p, it && it.category, cents);
      if (!r.ok) { errors.push((it && it.category) + ': enter an amount of $0 or more.'); continue; }
      p = r.plan; const b = p.budgets.find(x => x.category === it.category);
      if (b) b.source = it.fromProposal ? (it.basis === 'thin' ? 'thin' : it.basis === 'starter' ? 'generic' : 'accepted') : 'student';
      n++;
    }
    return { ok: errors.length === 0, plan: p, applied: n, errors };
  };
  E.clearBudgetApproval = function (plan, category) {
    const p = E.clone(plan), b = p.budgets.find(x => x.category === category);
    if (b) { b.approvedCents = null; b.source = 'starter'; }
    return { ok: true, plan: p };
  };

  /* ---------- 5. optional questions: each one says what it improves ---------- */
  E.optionalQuestions = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    const per = E.currentPeriod(plan, T), has = id => plan.answered.indexOf(id) >= 0;
    const so = snap && snap.ok ? E.safetyOutlook(plan, { today: T, scenario: 'cautious', base: snap.base, det: snap.det }) : null;
    const hasTransportBudget = snap && snap.ok ? E.effectiveBudgets(plan, T, snap.base).some(b => b.category === 'Transportation' && b.monthlyCents > 0) : false;
    const q = [
      { id: 'dates', title: 'Confirm your semester dates', improves: 'Makes the semester forecast end on the right day.', recommended: true, done: !!(per && per.verified), kind: 'dates' },
      { id: 'income', title: plan.incomes.length ? 'Any other money coming in?' : 'Is any regular money coming in?', improves: 'Paychecks, family support or work-study you list are counted. Money you do not list is never counted.', recommended: plan.incomes.length === 0 && !has('no_income'), done: plan.incomes.length > 0 || has('no_income'), kind: 'income' },
      { id: 'aid', title: 'Is a financial aid or scholarship refund coming?', improves: 'Adds a known deposit. It is counted two weeks late in the cautious view, so it never makes you overspend.', recommended: true, done: plan.incomes.some(i => i.type === 'aid' || i.type === 'scholarship') || has('no_aid'), kind: 'aid' },
      { id: 'bills', title: 'Any other regular bills?', improves: 'Phone, subscriptions, insurance. Bills you list are set aside before any spending money is shown.', recommended: true, done: plan.obligations.some(o => o.category !== 'Housing') || has('no_other_bills'), kind: 'bill' },
      { id: 'transport', title: 'Gas, parking or bus money?', improves: 'Adds a transportation estimate so getting around is not left out.', recommended: false, done: hasTransportBudget || has('no_transport'), kind: 'amount' },
      { id: 'reserve', title: 'Set money aside for between terms?', improves: 'Keeps cash for rent and food after the term ends, until your next refund.', recommended: !!(so && so.ok && so.recommend), done: plan.settings.reserveBridge || plan.settings.reserveFixedCents > 0 || has('reserve_declined'), kind: 'reserve' },
      { id: 'cushion', title: 'Your safety cushion', improves: 'The amount you never plan to spend. It starts at $100; change it if you want more or less breathing room.', recommended: false, done: has('cushion_set'), kind: 'cushion' },
      { id: 'name', title: 'What should we call you?', improves: 'Only makes the app friendlier. It changes no numbers.', recommended: false, done: !!plan.meta.name, kind: 'name' }
    ];
    // the reserve question only appears when there is something to set aside for, or the student already chose
    return q.filter(x => x.id !== 'reserve' || x.recommended || x.done);
  };
  // v depends on the question. Every answer returns a new plan and records that it was answered.
  E.answerOptional = function (plan, T, id, v) {
    v = v || {};
    if (id === 'dates') return E.confirmSemester(plan, T, v);
    if (id === 'income') return v.none ? E.markAnswered(plan, 'no_income') : E.addIncome(plan, v);
    if (id === 'aid') {
      if (v.none) return E.markAnswered(plan, 'no_aid');
      return E.addIncome(plan, { type: v.type === 'scholarship' ? 'scholarship' : 'aid', name: v.name, amountCents: v.amountCents, freq: 'once', nextDate: v.date });
    }
    if (id === 'bills') {
      if (v.none) return E.markAnswered(plan, 'no_other_bills');
      return E.addBill(plan, v);
    }
    if (id === 'transport') {
      if (v.none) return E.markAnswered(plan, 'no_transport');
      return E.approveBudgets(plan, [{ category: 'Transportation', cents: v.cents }]);
    }
    if (id === 'reserve') {
      if (v.decline) return E.markAnswered(plan, 'reserve_declined');
      if (v.accept) return E.acceptReserveRecommendation(plan, T, 'cautious');
      return fail(plan, 'Choose whether to set money aside.');
    }
    if (id === 'cushion') return E.setCushion(plan, v.cents);
    if (id === 'name') return E.setMeta(plan, { name: v.name });
    return fail(plan, 'Unknown question.');
  };

  /* ---------- 6. confidence, daily-pace foundation, and the whole first plan ---------- */
  E.confidenceSummary = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    const t = E.trust(plan, T, snap);
    if (!t.ok) return { level: 'blocked', badge: t.badge, summary: t.wording.summary, solid: [], estimated: [], improve: [{ id: 'balance', text: 'Enter your checking balance.' }], guaranteed: false };
    const solid = [], estimated = [], improve = [];
    solid.push('Your checking balance of ' + E.fmt(plan.account.balanceCents) + ' as of ' + D.label(D.parse(plan.account.asOf)) + ' (you entered it).');
    const vb = plan.obligations.filter(o => o.verified), vi = plan.incomes.filter(i => i.verified);
    if (vb.length) solid.push(vb.length + ' bill' + (vb.length === 1 ? '' : 's') + ' you confirmed: ' + vb.map(b => b.name).slice(0, 4).join(', ') + (vb.length > 4 ? ', and more' : '') + '.');
    if (vi.length) solid.push(vi.length + ' income source' + (vi.length === 1 ? '' : 's') + ' you confirmed: ' + vi.map(i => i.name).slice(0, 3).join(', ') + (vi.length > 3 ? ', and more' : '') + '.');
    const eff = E.effectiveBudgets(plan, T, snap.base);
    for (const b of eff) {
      if (b.basis === 'approved') solid.push(b.category + ' budget of ' + E.fmt(b.monthlyCents) + ' a month (your number).');
      else if (b.evidence === 'strong' || b.evidence === 'moderate') solid.push(b.category + ' estimate from ' + b.evidenceWhy.toLowerCase());
    }
    for (const l of t.labels) estimated.push(l.text);
    for (const q of t.questions) if (!q.blocking) estimated.push(q.name + ': a deposit on ' + q.txDate + ' might be this paycheck. It is counted once, as the deposit, until you confirm.');
    if (plan.settings.irregularLowFactorPct < 100 && plan.incomes.some(i => i.irregular && i.lowCents == null)) estimated.push('Irregular pay is counted at ' + plan.settings.irregularLowFactorPct + '% in the cautious view.');
    for (const m of t.missing) improve.push({ id: m.id, kind: 'needed', text: m.question });
    const txCount = E.activeTxs(plan).length;
    if (txCount < 15) improve.push({ id: 'csv', kind: 'csv', text: 'Import a bank CSV. Real purchases replace guesses, and the plan gets more accurate.' });
    for (const o of E.optionalQuestions(plan, T, snap).filter(x => !x.done && x.recommended)) improve.push({ id: o.id, kind: 'optional', text: o.title.replace(/[?.!]*$/, o.title.slice(-1) === '?' ? '?' : '.') + ' ' + o.improves });
    return { level: t.level, badge: t.badge, summary: t.summary, allowanceLabel: t.allowanceLabel, solid, estimated, improve, guaranteed: false };
  };
  // The foundation for daily recommendations: today's pace, the next days, and why. It never appears when the plan needs an answer first.
  E.dailyPreview = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    const t = E.trust(plan, T, snap);
    if (!t.ok || !t.showAllowance) return { shown: false, level: t.level, why: t.wording.summary, question: t.missing[0] || null };
    const cap = snap.cautious.capacity, next = [];
    for (let k = 0; k < 7 && k < cap.profile.daily.length; k++) next.push({ day: T + k, label: D.label(T + k), paceCents: cap.profile.daily[k] });
    return {
      shown: true, level: t.level, label: t.allowanceLabel, dailyCents: cap.todayLimit.allowanceCents, weekRemainingCents: cap.week.remainingCents, next,
      limitedBy: cap.pace.limitedBy && cap.pace.limitedBy.label ? cap.pace.limitedBy.label : '', short: !cap.safe,
      meaning: cap.pace.meaning, scenario: 'cautious'
    };
  };
  const FREQ_LABEL = { weekly: 'every week', biweekly: 'every 2 weeks', semimonthly: 'twice a month', monthly: 'every month', once: 'one time', yearly: 'every year' };
  E.firstPlan = function (plan, T) {
    const snap = E.snapshot(plan, T);
    if (!snap || !snap.ok) return { ok: false, error: 'Enter your checking balance first.' };
    const trust = E.trust(plan, T, snap), cap = snap.cautious.capacity, per = E.currentPeriod(plan, T), h = E.horizonInfo(plan, T), proposals = E.proposeBudgets(plan, T, snap);
    const safety = E.safetyOutlook(plan, { today: T, scenario: 'cautious', fc: snap.cautious.fc, base: snap.base, det: snap.det, reserve: cap.reserve });
    const health = typeof E.planHealth === 'function' ? E.planHealth(plan, T, snap) : { ok: true, okCushion: true };
    const roomSplit = typeof E.semesterRoomSplit === 'function' ? E.semesterRoomSplit(cap, safety) : null;
    if (roomSplit) {
      roomSplit.safeLabelOk = !!(health.ok && health.okCushion && roomSplit.afterTermProtected && cap.safe);
      roomSplit.safeToSpendCents = roomSplit.safeLabelOk ? roomSplit.unprotectedSpendCents : 0;
    }
    const dates = safety.dates || E.planDateContext(plan, T, safety);
    const conditionalPace = !!(trust.showAllowance && roomSplit && roomSplit.safeToSpendCents === 0);
    const paceReason = conditionalPace
      ? (health.ok && !health.okCushion ? 'Safe to spend is $0 because approved budgets already use the cushion.'
        : roomSplit.gapCents > 0 ? 'Safe to spend is $0 because after-term need is not fully earmarked.'
          : 'Safe to spend is $0 under the current plan.')
      : '';
    const nextBill = o => { const x = E.occurrences(o.schedule, T, T + 400)[0]; return x ? D.label(x.day) : ''; };
    const incomeRow = i => {
      const a = E.incomeArrivalDays(plan, i, T);
      if (!a) return { id: i.id, name: i.name, type: i.type, amountCents: i.amountCents, freq: FREQ_LABEL[i.schedule.freq] || '', next: '', nextScheduledDay: null, nextCautiousDay: null, nextNote: '', reliability: i.reliability, verified: i.verified };
      const next = a.differs ? D.label(a.scheduledDay) + ' (cautious ' + D.label(a.cautiousDay) + ')' : D.label(a.scheduledDay);
      const nextNote = a.differs ? 'Scheduled ' + D.label(a.scheduledDay) + '; counted ' + D.label(a.cautiousDay) + ' in the cautious view' : '';
      return { id: i.id, name: i.name, type: i.type, amountCents: i.amountCents, freq: FREQ_LABEL[i.schedule.freq] || '', next, nextScheduledDay: a.scheduledDay, nextCautiousDay: a.cautiousDay, nextNote, reliability: i.reliability, verified: i.verified };
    };
    return {
      ok: true, today: T, asOf: plan.account.asOf, trust, confidence: E.confidenceSummary(plan, T, snap), daily: E.dailyPreview(plan, T, snap), layers: E.transparency(plan, T, snap), safety,
      dates, roomSplit, planHealth: health, conditionalPace, paceReason,
      room: { shown: trust.showAllowance, label: conditionalPace ? 'Conditional daily pace' : trust.allowanceLabel, semesterCents: cap.semester.allowanceCents, dailyPaceCents: cap.todayLimit.allowanceCents, oneTimeCents: cap.immediate.cents, safe: cap.safe, level: trust.level, conditionalPace, paceReason,
        // the same plan if income and aid arrive as hoped; shown beside the cautious number, never instead of it
        expectedSemesterCents: snap.expected.capacity && snap.expected.capacity.ok ? snap.expected.capacity.semester.allowanceCents : null, expectedDailyCents: snap.expected.capacity && snap.expected.capacity.ok ? snap.expected.capacity.todayLimit.allowanceCents : null },
      semester: { name: per ? per.name : h.period, start: per ? per.start : '', end: D.fmt(h.endDay), endLabel: D.label(h.endDay), verified: per ? !!per.verified : false, daysLeft: h.days, basis: h.basis },
      budgets: proposals,
      income: plan.incomes.map(incomeRow),
      bills: plan.obligations.map(o => ({ id: o.id, name: o.name, category: o.category, amountCents: o.amountCents, freq: FREQ_LABEL[o.schedule.freq] || '', next: nextBill(o), verified: o.verified })),
      optional: E.optionalQuestions(plan, T, snap), needed: trust.missing
    };
  };

  /* ---------- 7. three realistic demo students (University of Kentucky) ---------- */
  // Each persona builds a bank CSV whose dates are relative to `today`, so the demo never goes stale.
  // The CSV goes through exactly the same review and confirmation as a real file.
  const pad2 = n => (n < 10 ? '0' : '') + n;
  const mdy = day => { const t = D.ymd(day); return pad2(t.m) + '/' + pad2(t.d) + '/' + t.y; };
  const q = s => (/[",\n]/.test(s) ? '"' + String(s).replace(/"/g, '""') + '"' : s);
  const cyc = (arr, i) => arr[i % arr.length];
  function firstsOfMonth(from, to) { const out = []; for (let idx = D.monthIndex(from); idx <= D.monthIndex(to); idx++) { const d = D.fromMonthIndex(idx, 1); if (d >= from && d <= to) out.push(d); } return out; }
  function nextDateOf(T, month, dom) { const y = D.ymd(T).y; for (const yy of [y, y + 1]) { const d = D.make(yy, month, dom); if (d > T) return D.fmt(d); } return D.fmt(D.make(y + 1, month, dom)); }
  function nextFirst(T) { const t = D.ymd(T); return D.fmt(D.make(t.m === 12 ? t.y + 1 : t.y, t.m === 12 ? 1 : t.m + 1, 1)); }

  function mayaRows(T) {
    const R = [];
    [38740, 36210, 40125, 38740, 37380].forEach((c, i) => R.push([-(3 + 14 * i), 'UNIV OF KENTUCKY PAYROLL 8841', c]));
    for (const d of firstsOfMonth(T - 75, T - 1)) R.push([d - T, 'CAMPUS PARK APARTMENTS RENT', -52500]);
    [6480, 5920, 7105].forEach((c, i) => R.push([-(9 + 30 * i), 'KENTUCKY UTILITIES PMT', -c]));
    [-17, -47].forEach(o => R.push([o, 'T-MOBILE AUTOPAY', -4500])); [-22, -52].forEach(o => R.push([o, 'SPOTIFY USA', -1199]));
    for (let k = 0; k < 14; k++) R.push([-(1 + 5 * k), k % 3 === 2 ? 'ALDI 71' : 'KROGER #512', -cyc([4818, 3560, 5230, 2975, 4410, 3890, 5120], k)]);
    for (let k = 0; k < 23; k++) R.push([-(2 + 3 * k), cyc(['CHIPOTLE 1843', 'STARBUCKS #1209', 'PAPA JOHNS PIZZA', 'CHICK-FIL-A #02214', 'SKYLINE CHILI'], k), -cyc([1185, 545, 1874, 968, 1240, 545, 1390], k)]);
    [-4, -16, -29, -41, -54, -66].forEach((o, i) => R.push([o, 'SHELL OIL 574', -cyc([3210, 2985, 3440, 3105, 3320, 3050], i)]));
    [[-11, 'AMAZON MKTPL', 2349], [-33, 'AMAZON MKTPL', 1899], [-50, 'TARGET 0824', 3299], [-26, 'AMC THEATRES LEXINGTON', 1650]].forEach(r => R.push([r[0], r[1], -r[2]]));
    R.push([-20, 'ZELLE FROM MOM', 5000], [-52, 'UK BURSAR REFUND', 164000]);
    return R;
  }
  function jordanRows(T) {
    const R = [];
    [14250, 21840, 9875, 23110, 17655].forEach((c, i) => R.push([-(2 + 7 * i), 'UK DINING SERVICES PAYROLL', c]));
    for (const d of firstsOfMonth(T - 35, T - 1)) R.push([d - T, 'ZELLE PAYMENT TO MIKE RODRIGUEZ', -38000]);
    for (let k = 0; k < 4; k++) R.push([-(2 + 9 * k), 'SPEEDWAY 4417', -cyc([3880, 4515, 4120, 3995], k)]);
    for (let k = 0; k < 4; k++) R.push([-(3 + 8 * k), 'WALMART SUPERCENTER', -cyc([6120, 4385, 7240, 5560], k)]);
    for (let k = 0; k < 9; k++) R.push([-(1 + 4 * k), cyc(['DOMINOS 7731', 'WAFFLE HOUSE 1189', 'TACO BELL 30912', 'DOORDASH*CHIPOTLE'], k), -cyc([1450, 1120, 960, 1875, 1590], k)]);
    R.push([-11, 'MOBILE DEP 3345', 12000], [-18, 'VENMO CASHOUT', 6500], [-22, 'TRANSFER TO SAVINGS', -5000], [-14, 'NETFLIX.COM', -1549], [-8, 'FOOT LOCKER 0291', -6899], [-27, 'GAMESTOP 4120', -2399]);
    return R;
  }
  function rileyRows() {
    return [[-11, 'ZELLE FROM MOM', 40000], [-10, 'UK BOOKSTORE', -18640], [-9, 'KROGER 512', -3870], [-8, 'SHELL OIL 574', -2800], [-6, 'CHIPOTLE 1843', -1185], [-5, 'STARBUCKS #1209', -545], [-4, 'PANDA EXPRESS', -960], [-3, 'KROGER 512', -5214], [-2, 'CHIPOTLE 1843', -1185], [-1, 'STARBUCKS #1209', -545]];
  }
  function toCsv(rows, T, balanceCents, style) {
    const sorted = rows.map((r, i) => ({ day: T + r[0], desc: r[1], cents: r[2], i })).sort((a, b) => b.day - a.day || a.i - b.i);
    const money = c => (c < 0 ? '-' : '') + (Math.abs(c) / 100).toFixed(2);
    if (style === 'running') {
      let run = balanceCents; const lines = ['Post Date,Description,Amount,Running Bal.'];
      for (const r of sorted) { lines.push([mdy(r.day), q(r.desc), money(r.cents), (run / 100).toFixed(2)].join(',')); run -= r.cents; }
      return lines.join('\n');
    }
    return ['Date,Description,Amount'].concat(sorted.map(r => [mdy(r.day), q(r.desc), money(r.cents)].join(','))).join('\n');
  }

  // Refunds and savings are highest early in a term, so a demo student's balance grows with the days left in the term.
  // The stated balance is for a term with 58 days left; the slope (cents per day) adjusts it for other dates.
  function daysLeftOf(T) { const per = E.defaultPeriods(T).find(p => p.kind === 'semester' && D.parse(p.end) >= T); return per ? Math.min(200, D.parse(per.end) - T) : 58; }
  const personaBalance = (p, T) => Math.max(p.floorCents, p.balanceCents + p.slope * (daysLeftOf(T) - 58));       // never below about a month of rent plus a cushion
  function termDue(T, daysBeforeEnd) {
    const pers = E.defaultPeriods(T);
    const sem = pers.find(p => p.kind === 'semester' && D.parse(p.end) >= T) || pers.find(p => p.kind === 'semester');
    const end = sem ? D.parse(sem.end) : T + 56;
    let due = end - (daysBeforeEnd || 0);
    if (due <= T) due = end;
    if (due <= T) due = T + 1;
    return D.fmt(due);
  }
  // Maya's one-click sample is a FIXED scenario for judges (build + view dates). Real student plans still use App.today().
  // Tests that pass an explicit day to runDemo without { fixed:true } keep date-relative behaviour for sweeps.
  E.DEMO_PERSONAS = [
    {
      id: 'maya', name: 'Maya', school: E.DEMO_SCHOOL, living: 'Off campus', balanceCents: 128460, slope: 1500, floorCents: 85000, style: 'plain', rows: mayaRows,
      // Fixed scenario: plan built as of 2026-11-12, Today evaluated on 2026-11-13 (audit reference).
      scenario: { buildDay: '2026-11-12', viewDay: '2026-11-13' },
      tagline: 'Sophomore. Campus job, off-campus apartment.', story: 'A $150 campus shift arrives Nov 21, before December rent. She approved a tight month and set winter costs aside, including $480 for spring materials while aid is late in the cautious forecast. The $100 cushion stays protected.',
      label: 'Maya\'s revised plan',
      about: 'Sophomore with a campus job and an off-campus apartment. This version adds a $150 shift on Nov 21, before December rent, a $480 bill for spring materials, and tighter spending budgets. She sets winter costs aside while aid is late in the cautious forecast, so her $100 cushion stays protected.',
      walkthrough: {
        extraIncome: { type: 'job', name: 'Extra campus shift', amountCents: 15000, freq: 'once', nextDate: '2026-11-21', reliability: 'certain' },
        plannedExpense: { name: 'Spring course materials', amountCents: 48000, date: '2027-01-14', category: 'School supplies', essential: true },
        purchase: { amountCents: 3500, desc: 'Used lab manual', category: 'School supplies' },
        secondPurchase: { amountCents: 5000, desc: 'Course packet', category: 'School supplies' },
        categoryHints: { 'used lab': 'School supplies', 'course packet': 'School supplies' },
        // History-based groceries and transportation, a small dining budget, and no generic starter extras.
        approvedBudgets: [
          { category: 'Groceries', cents: 22000 }, { category: 'Transportation', cents: 7500 }, { category: 'Dining out', cents: 2000 },
          { category: 'Entertainment', cents: 0 }, { category: 'Shopping', cents: 0 }, { category: 'Personal', cents: 0 }, { category: 'Other', cents: 0 }
        ],
        reserveBridge: true
      },
      setup: T => ({ housing: null, groceriesCents: null, incomes: [], optional: { aid: { name: 'Spring aid refund', amountCents: 180000, date: nextDateOf(T, 1, 11) }, bills: { none: true }, transport: { none: true } } }),
      hints: [{ match: /ZELLE FROM MOM/, option: 'income' }],
      goal: T => ({ name: 'Used laptop', type: 'purchase', targetCents: 12000, savedCents: 4000, dueDate: termDue(T, 0), priority: 1 })
    },
    {
      id: 'jordan', name: 'Jordan', school: E.DEMO_SCHOOL, living: 'Off campus', balanceCents: 91240, slope: 1500, floorCents: 65000, style: 'running', rows: jordanRows,
      tagline: 'Junior. Dining-hall hours that change every week.', story: 'Five weeks of history, weekly pay that swings from $99 to $231, rent paid to a roommate by Zelle, a few deposits the app cannot explain. Shows how an irregular income is handled cautiously.',
      about: 'Junior whose dining-hall pay swings from $99 to $231 a week. Jordan has five weeks of history, pays rent to a roommate by Zelle, and has a few deposits the app cannot explain. Shows how irregular income is handled cautiously.',
      setup: T => ({ housing: { amountCents: 38000, day: 1 }, groceriesCents: null, incomes: [], optional: { aid: { none: true }, bills: { none: true }, transport: { none: true } } }),
      hints: [{ match: /ZELLE PAYMENT TO MIKE/, option: 'rent' }, { match: /MOBILE DEP 3345/, option: 'income' }, { match: /VENMO CASHOUT/, option: 'income' }],
      goal: T => ({ name: 'Bus home for winter break', type: 'trip', targetCents: 12000, savedCents: 0, dueDate: termDue(T, 0), priority: 1 })
    }
  ];
  // No longer offered as a sample. Kept so plans and files made from it still open as that sample student.
  E.RETIRED_PERSONAS = [
    {
      id: 'riley', name: 'Riley', school: E.DEMO_SCHOOL, living: 'Off campus', balanceCents: 101230, slope: 1500, floorCents: 70000, style: 'plain', rows: rileyRows,
      tagline: 'First-year. New bank account, 11 days of history.', story: 'Only eleven days of transactions, no paycheck, and help from family. Shows what the app does with thin evidence: cautious, forward-only estimates and honest labels.',
      about: 'First-year with a new bank account: only 11 days of transactions, no paycheck, and help from family. Shows what the app does with thin evidence: cautious, forward-only estimates and honest labels.',
      setup: T => ({ housing: { amountCents: 45000, day: 1 }, groceriesCents: null, incomes: [{ type: 'family', name: 'Money from Mom', amountCents: 40000, freq: 'monthly', nextDate: nextFirst(T), reliability: 'likely' }], optional: { aid: { none: true }, bills: { none: true }, transport: { none: true } } }),
      hints: [{ match: /ZELLE FROM MOM/, option: 'income' }],
      goal: T => ({ name: 'Emergency fund', type: 'emergency', targetCents: 10000, savedCents: 0, dueDate: termDue(T, 7), priority: 1 })
    }
  ];
  const personaOf = id => E.DEMO_PERSONAS.find(p => p.id === id) || E.RETIRED_PERSONAS.find(p => p.id === id) || null;
  E.demoPersona = personaOf;
  // A sample's walk-through hints describe a plan that actually contains its extra income and planned bill. The welcome-screen
  // scenario (E.runDemo with walkthrough:false) and a plan the student has edited past them get none.
  E.demoWalkthrough = function (plan) {
    const m = /^stage2-([a-z0-9-]+)$/.exec(plan && plan.meta && plan.meta.demo || ''), p = m && personaOf(m[1]), w = p && p.walkthrough;
    if (!w || !plan.incomes || !plan.obligations) return null;
    const hasIncome = !w.extraIncome || plan.incomes.some(i => i.name === w.extraIncome.name);
    const hasBill = !w.plannedExpense || plan.obligations.some(o => o.name === w.plannedExpense.name);
    return hasIncome && hasBill ? w : null;
  };
  E.demoScenarioDays = function (id) {
    const p = personaOf(id); if (!p || !p.scenario) return null;
    const build = D.parse(p.scenario.buildDay), view = D.parse(p.scenario.viewDay);
    if (build === null || view === null) return null;
    return { buildDay: build, viewDay: view, buildLabel: p.scenario.buildDay, viewLabel: p.scenario.viewDay };
  };
  // Which day a saved file should reopen on. A fixed sample (Maya) stays on its scenario view day.
  // A hinted day is accepted only when it is that scenario's view day, so a file cannot freeze a real plan.
  // Files saved before sampleViewDay existed are recognized when the balance date is still the scenario build day.
  E.fixedSampleViewDay = function (plan, hintedDay) {
    if (!plan || !plan.meta) return null;
    const m = /^stage2-([a-z0-9-]+)$/.exec(plan.meta.demo || '');
    if (!m) return null;
    const sc = E.demoScenarioDays(m[1]);
    if (!sc) return null;
    if (hintedDay != null && hintedDay === sc.viewDay) return sc.viewDay;
    if (plan.account && plan.account.asOf === sc.buildLabel) return sc.viewDay;
    return null;
  };
  // Resolve which calendar day to build a demo on. opts.fixed (default true when a scenario exists and T is omitted) locks Maya for judges.
  E.demoBuildDay = function (id, T, opts) {
    opts = opts || {};
    const sc = E.demoScenarioDays(id);
    if (opts.fixed === true && sc) return sc.buildDay;
    if (opts.fixed === false) return T;
    if (sc && (T == null || opts.useScenario)) return sc.buildDay;
    return T;
  };
  E.demoStatement = function (id, T) { const p = personaOf(id); return p ? toCsv(p.rows(T), T, personaBalance(p, T), p.style) : ''; };
  E.demoBalance = function (id, T) { const p = personaOf(id); return p ? personaBalance(p, T) : null; };
  E.demoSetup = function (id, T) { const p = personaOf(id); return p ? p.setup(T) : null; };
  // The default choice for each flagged row in a demo: the persona's own answer if it has one, otherwise the app's suggestion.
  E.demoDecisions = function (id, review) {
    const p = personaOf(id), rows = {};
    for (const a of review.attention) {
      const hint = p ? p.hints.find(h => h.match.test(a.desc)) : null;
      const want = hint ? hint.option : a.suggested;
      rows[a.idx] = { option: (a.options || []).some(o => o.id === want) ? want : a.suggested };
    }
    return rows;
  };
  E.demoStart = function (id, T, opts) {
    const p = personaOf(id); if (!p) return { ok: false, error: 'Unknown sample student.' };
    const buildT = E.demoBuildDay(id, T, opts);
    return E.startPlan({ today: buildT, name: p.name, school: p.school, living: p.living, balanceCents: personaBalance(p, buildT), demo: 'stage2-' + p.id });
  };

  // Runs the complete onboarding for a persona with the same engine calls the screens use. For tests and for the "show me" report.
  // It confirms every review item and approves every proposed budget, exactly as a student who taps "looks right" at each step would.
  // opts.fixed:true forces a persona.scenario build day (Maya judge sample). Date-sweep tests pass T and omit fixed.
  E.runDemo = function (id, T, opts) {
    opts = opts || {};
    const p = personaOf(id); if (!p) return { ok: false, error: 'Unknown sample student.' };
    const buildT = E.demoBuildDay(id, T, opts);
    const sc = E.demoScenarioDays(id);
    const viewT = (opts.fixed === true && sc) ? sc.viewDay : (opts.useScenario && sc ? sc.viewDay : buildT);
    const log = [], note = s => log.push(s);
    let r = E.demoStart(id, buildT, { fixed: false }); if (!r.ok) return r; let plan = r.plan; note('Started with a balance of ' + E.fmt(plan.account.balanceCents) + '.');
    const csv = E.demoStatement(id, buildT), rv = E.reviewStatement(plan, csv, { today: buildT });
    if (!rv.ok) return { ok: false, error: rv.error, log };
    const conf = { mapping: true, direction: true, attention: true }; if (rv.dates.ambiguous) conf.dates = true;
    const ap = E.applyStatementReview(plan, rv, { confirmed: conf, rows: E.demoDecisions(id, rv) }, buildT);
    if (!ap.ok) return { ok: false, error: ap.error, log };
    plan = ap.plan; note('Imported ' + ap.added + ' transactions; ' + rv.attention.length + ' rows needed a decision.');
    const found = E.detectedSetup(plan, buildT), c = E.confirmDetected(plan, buildT, { billKeys: found.bills.map(b => b.key), incomeKeys: found.incomes.map(i => i.key) });
    plan = c.plan; note('Confirmed ' + c.addedBills + ' bills and ' + c.addedIncomes + ' paychecks found in the file.');
    const setup = p.setup(buildT);
    for (const inc of setup.incomes) { r = E.addIncome(plan, inc); if (!r.ok) return { ok: false, error: r.error, log }; plan = r.plan; note('Added income: ' + inc.name + '.'); }
    for (const m of E.trust(plan, buildT).missing) {
      if (m.id === 'housing') { r = E.answerQuestion(plan, 'housing', setup.housing || { none: true }); if (!r.ok) return { ok: false, error: r.error, log }; plan = r.plan; note('Answered the rent question.'); }
      else if (m.id === 'groceries') { r = E.answerQuestion(plan, 'groceries', setup.groceriesCents == null ? 25000 : setup.groceriesCents); plan = r.plan; note('Answered the groceries question.'); }
    }
    for (const o of E.optionalQuestions(plan, buildT).filter(x => !x.done)) {
      const v = setup.optional[o.id]; if (!v) continue;
      r = E.answerOptional(plan, buildT, o.id, v); if (r.ok) { plan = r.plan; note('Optional: ' + o.title); }
    }
    const pr = E.proposeBudgets(plan, buildT), items = pr.rows.filter(x => x.status === 'proposed').map(x => ({ category: x.category, cents: x.proposedCents, fromProposal: true, basis: x.basis }));
    r = E.approveBudgets(plan, items); plan = r.plan; note('Approved ' + r.applied + ' proposed budgets.');
    r = E.seedDemoGoal(plan, id, buildT);
    if (r.ok) { plan = r.plan; if (r.added) note('Sample goal: ' + plan.goals[0].name + ' (made-up, like the rest of this student). Nothing is set aside until the student accepts a savings plan.'); }
    // opts.walkthrough === false keeps the fixed dates but skips the sample's later edits: Maya as she first is (the welcome-screen scenario).
    if (opts.fixed === true && p.walkthrough && opts.walkthrough !== false) {
      if (p.walkthrough.extraIncome) {
        r = E.addIncome(plan, p.walkthrough.extraIncome); if (!r.ok) return { ok: false, error: r.error, log };
        plan = r.plan; note('Added one-time income: ' + p.walkthrough.extraIncome.name + '.');
      }
      if (p.walkthrough.plannedExpense) {
        r = E.addPlannedExpense(plan, p.walkthrough.plannedExpense); if (!r.ok) return { ok: false, error: r.error, log };
        plan = r.plan; note('Added planned expense: ' + p.walkthrough.plannedExpense.name + '.');
      }
      for (const b of p.walkthrough.approvedBudgets || []) {
        r = E.setBudget(plan, b.category, b.cents); if (!r.ok) return { ok: false, error: 'Could not set the ' + b.category + ' budget.', log };
        plan = r.plan;
      }
      if (p.walkthrough.approvedBudgets) note('Set the sample approved budgets.');
      if (p.walkthrough.reserveBridge) {
        r = E.setReserve(plan, { bridge: true }); if (!r.ok) return { ok: false, error: r.error, log };
        plan = r.plan; note('Earmarked the between-term reserve.');
      }
      if (p.walkthrough.categoryHints) {
        plan = E.clone(plan);
        plan.catRules = Object.assign({}, plan.catRules, p.walkthrough.categoryHints);
        note('Labeled the sample purchase names.');
      }
    }
    if (sc && buildT === sc.buildDay) {
      plan = E.clone(plan);
      plan.meta = Object.assign({}, plan.meta, { demoScenario: sc.buildLabel + '/' + sc.viewLabel });
    }
    return { ok: true, plan, log, csv, review: rv, found, buildDay: buildT, viewDay: viewT, scenario: sc };
  };
  // Same sample goal the UI plants at the end of a demo walk-through. No contribution is written.
  E.seedDemoGoal = function (plan, id, T) {
    const p = personaOf(id);
    if (!p || !p.goal || typeof E.addGoal !== 'function') return { ok: true, plan, added: false };
    if ((plan.goals || []).length) return { ok: true, plan, added: false };
    let r = E.addGoal(plan, p.goal(T), T);
    if (!r.ok) return r;
    plan = r.plan;
    if (plan.goals[0].savedCents > 0 && typeof E.setSavingsBalance === 'function') {
      const sav = E.setSavingsBalance(plan, plan.goals[0].savedCents, T);
      if (sav.ok) plan = sav.plan;
    }
    return { ok: true, plan, added: true };
  };
})(CCE);

;
/* ===== engine/11-purchase.js ===== */
/* =========================================================================
   11 purchase — "Can I afford this?", duplicate-safe logging, and bank-file match suggestions
   -------------------------------------------------------------------------
   STAGE 3 + STAGE D. Nothing here changes how the forecast or capacity are calculated. Every answer is
   produced by re-running the existing engine on a COPY of the plan that counts the purchase once as cash
   (or a proposed plan change written with E.writeGoalChoice). Preview freezes the plan's existing
   spending estimates (detect/baseline): a hypothetical purchase cannot create or inflate a recurring
   category estimate. Logging a purchase for real still updates estimates as usual. The student's
   approved plan is never edited from here.

   * E.purchaseCheck(plan, {today, amountCents, desc?, category?})   READ ONLY. Never records anything.
       verdict          Stage 3 commitments-only answer (fits_pace|fits_room|tight|not_now|needs_info)
       classification   Stage D full-plan answer (affordable|needs_changes|unaffordable|needs_info)
                        Affordable means the cautious planned forecast (discretionary + existing goal
                        contributions + cushion + end-of-term reserve) still holds, and an approved
                        discretionary budget is not exceeded. A day below the cushion is never affordable
                        or recommended, even if the student would accept the risk.
   * E.logPurchase(plan, o, today)                                   records a purchase (the only way a purchase is recorded
                                                                     from the Today screen), after a duplicate check.
   * E.possibleDuplicates / E.manualMatchSuggestions / E.decideDuplicate
                                                                     keep a purchase the student typed from being counted a
                                                                     second time when the same charge is in a bank file.

   Vocabulary the screen must keep apart (they are different questions):
     today's pace       what is left of the SUSTAINABLE daily amount today        (E.capacity().todayLimit)
     approved budget    the student's own monthly category numbers                (E.budgetStatus)
     room (bills only)  what bills, essentials, cushion and reserve leave          (E.capacity().immediate)
     one purchase       the most a single payment can be right now, once the      (E.purchaseLimit)
                        approved budgets still to be spent are kept too. Never above the room line.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const dayOf = t => D.parse(t.date);

  /* ---------- pace for the days AFTER today ---------- */
  // The sustainable daily pace if you started again tomorrow from the balance you have RIGHT NOW (after everything already recorded today).
  // Same lower-convex-hull rule as E.capacity, so it answers "if I overspend today, what happens to tomorrow?" in the same units.
  E.paceFromTomorrow = function (cap) {
    if (!cap || !cap.ok) return { cents: 0, startsOn: null };
    const fc = cap.fc, N = fc.N, C = fc.cushionCents, R = cap.reserve.totalCents;
    if (N < 1) return { cents: 0, startsOn: null };
    const Ucur = fc.days.map(d => d.bal - C); Ucur[N] -= R;
    let kLast = 0;
    for (let k = 1; k <= N; k++) if (Ucur[k] < 0) kLast = k;
    if (kLast > 0) return { cents: 0, startsOn: fc.today + kLast + 1 <= fc.endDay ? fc.today + kLast + 1 : null };
    const pts = [[0, 0]];
    for (let k = 1; k <= N; k++) pts.push([k, Ucur[k]]);
    const hull = E.lowerHull(pts);
    if (hull.length < 2) return { cents: 0, startsOn: null };
    const a = hull[0], b = hull[1];
    return { cents: Math.max(0, Math.floor((b[1] - a[1]) / (b[0] - a[0]))), startsOn: fc.today + 1 };
  };

  /* ---------- how one forecast treats a cushion ---------- */
  // The weeks right after the term: with only bills and essentials (no other spending at all), can every listed bill still be paid until the
  // next aid refund or AFTER_TERM_DAYS, whichever comes first? Pure arithmetic on the same cautious forecast, extended past the term.
  E.AFTER_TERM_DAYS = 30;
  function afterTermStats(plan, T, snap) {
    const fc = snap.cautious.fc, H = fc.endDay;
    const long = E.forecast(plan, { today: T, scenario: 'cautious', flex: 'none', det: snap.det, base: snap.base, endDay: H + E.AFTER_TERM_DAYS });
    if (!long || !long.ok) return null;
    let aid = null;
    for (const e of long.events) if (e.type === 'income' && e.amountCents > 0 && e.day > H && (e.itype === 'aid' || e.itype === 'scholarship') && (aid === null || e.day < aid.day)) aid = e;
    const end = aid ? Math.min(H + E.AFTER_TERM_DAYS, aid.day - 1) : H + E.AFTER_TERM_DAYS;
    let minCents = Infinity, minDay = null, firstShortDay = null;
    for (const d of long.days) {
      if (d.day <= H || d.day > end) continue;
      if (d.bal < minCents) { minCents = d.bal; minDay = d.day; }
      if (firstShortDay === null && d.bal < 0) firstShortDay = d.day;
    }
    if (minDay === null) return null;
    // the first listed bill that falls due once the money has run out (essentials can run out first, between bills)
    const balOn = {}; for (const d of long.days) balOn[d.day] = d.bal;
    let cause = null;
    if (firstShortDay !== null) for (const e of long.events) if ((e.type === 'bill' || e.type === 'detected' || e.type === 'savings') && e.amountCents < 0 && e.day >= firstShortDay && e.day <= end && balOn[e.day] < 0 && (!cause || e.day < cause.day)) cause = { name: e.name, day: e.day, amountCents: -e.amountCents };
    return { startDay: H + 1, endDay: end, endedBy: aid ? 'aid' : 'limit', aidName: aid ? aid.name : '', ok: minCents >= 0, minCents, minDay, firstShortDay, shortByCents: Math.max(0, -minCents), cause };
  }

  function roomStats(fc, C, R) {
    const N = fc.N; let minAdj = Infinity, minRaw = Infinity, minRawDay = fc.today, minAdjDay = fc.today, firstBelow = null, firstNeg = null, minBal = Infinity, minBalDay = fc.today;
    fc.days.forEach((d, k) => {
      const raw = d.bal - C, adj = raw - (k === N ? R : 0);
      if (adj < minAdj) { minAdj = adj; minAdjDay = d.day; }
      if (raw < minRaw) { minRaw = raw; minRawDay = d.day; }
      if (d.bal < minBal) { minBal = d.bal; minBalDay = d.day; }
      if (firstBelow === null && raw < 0) firstBelow = d.day;
      if (firstNeg === null && d.bal < 0) firstNeg = d.day;
    });
    return {
      minCents: minBal, minDay: minBalDay, okCushion: minRaw >= 0, okWithReserve: minAdj >= 0, negative: firstNeg !== null,
      firstBelowCushionDay: firstBelow, firstNegativeDay: firstNeg, shortByCents: Math.max(0, -minRaw), reserveShortByCents: Math.max(0, -minAdj), endCents: fc.days[N].bal
    };
  }
  // The outflow most likely responsible for a low point: the latest required payment on or before that day.
  function causeOf(fc, day) {
    let best = null;
    for (const e of fc.events) {
      if (e.amountCents >= 0 || e.type === 'purchase' || e.day > day || e.day < fc.today) continue;
      if (!best || e.day > best.day || (e.day === best.day && e.amountCents < best.amountCents)) best = e;
    }
    return best ? { name: best.name, day: best.day, amountCents: -best.amountCents, type: best.type } : null;
  }
  // The first day a one-time purchase of X fits, if nothing else flexible is spent before it. Uses the commitments-only timeline.
  function earliestFit(fc, X, C, R) {
    const N = fc.N, adj = fc.days.map((d, k) => d.bal - C - (k === N ? R : 0)), suffix = new Array(adj.length);
    let m = Infinity;
    for (let k = N; k >= 0; k--) { m = Math.min(m, adj[k]); suffix[k] = m; }
    for (let k = 0; k <= N; k++) if (suffix[k] - X >= 0) return fc.days[k].day;
    return null;
  }

  /* ---------- Stage D: full-plan classification (planned discretionary + goals + cushion + reserve) ---------- */
  const DOLLAR = 100;
  function compactGoals(st) {
    return ((st && st.goals) || []).map(g => ({
      id: g.goalId, name: g.name, contributionCents: g.currentContributionCents || 0,
      completionDay: g.completionDay == null ? null : g.completionDay, onTrack: !!g.onTrack,
      dueDate: g.dueDate || '', needCents: g.needCents == null ? null : g.needCents,
      remainingCents: g.remainingCents == null ? null : g.remainingCents
    }));
  }
  function validationOf(pr) {
    return {
      safe: pr.safe, okCushion: pr.okCushion, budgetOk: pr.budgetOk, restores: pr.restores,
      minCents: pr.cautious.minCents, minDay: pr.cautious.minDay, endCents: pr.cautious.endCents,
      scenarios: {
        cautious: { safe: pr.cautious.okWithReserve, okCushion: pr.cautious.okCushion, minCents: pr.cautious.minCents, minDay: pr.cautious.minDay, endCents: pr.cautious.endCents },
        expected: { safe: pr.expected.okWithReserve, okCushion: pr.expected.okCushion, minCents: pr.expected.minCents, minDay: pr.expected.minDay, endCents: pr.expected.endCents }
      }
    };
  }
  function goalDelta(before, after) {
    const b = {}, rows = [];
    for (const g of before) b[g.id] = g;
    for (const g of after) {
      const p = b[g.id] || { contributionCents: 0, completionDay: null, onTrack: false, dueDate: '' };
      rows.push({
        id: g.id, name: g.name,
        contributionCents: { before: p.contributionCents, after: g.contributionCents },
        completionDay: { before: p.completionDay, after: g.completionDay },
        onTrack: { before: !!p.onTrack, after: !!g.onTrack },
        dueDate: { before: p.dueDate || '', after: g.dueDate || '' },
        changed: p.contributionCents !== g.contributionCents || p.completionDay !== g.completionDay || p.dueDate !== g.dueDate
      });
    }
    return rows;
  }
  // Re-run the full daily planned forecast with the purchase (today via a logged copy, later via extraEvents)
  // and any proposed goal/discretionary/budget change. Never writes the student's plan. Spending estimates
  // stay those of the pre-purchase plan so a hypothetical buy cannot invent thin recurring spend.
  function probePurchase(plan, T, spec, ctx) {
    const amount = ctx.amount, category = ctx.category, desc = ctx.desc, kind = ctx.kind, C = ctx.C, RC = ctx.RC, RE = ctx.RE;
    let p = plan;
    if (spec.budgets) {
      p = E.clone(p);
      for (const b of spec.budgets) {
        let row = p.budgets.find(x => x.category === b.category);
        if (!row) { row = { category: b.category, approvedCents: null, recommendedCents: null, source: 'student' }; p.budgets.push(row); }
        row.approvedCents = b.approvedCents; row.source = 'student';
      }
      p = E.normalizePlan(p).plan;
    }
    if (spec.choice) p = E.writeGoalChoice(p, spec.choice, T);
    const day = spec.day == null ? T : spec.day;
    // Freeze detect/baseline before the hypothetical purchase lands on the copy.
    const det = E.detectRecurring(p, T), base = E.baseline(p, T, det);
    let extra = [];
    if (day <= T) {
      const r = E.addManualTx(p, { amountCents: amount, category, desc, date: D.fmt(T) }, T);
      if (!r.ok) return null;
      p = r.plan;
    } else extra = [{ day, amountCents: -amount, label: desc || 'This purchase', category }];
    const cau = E.forecast(p, { today: T, scenario: 'cautious', flex: 'budget', det, base, extraEvents: extra });
    if (!cau.ok) return null;
    const exp = spec.expected === false ? cau : E.forecast(p, { today: T, scenario: 'expected', flex: 'budget', det, base, extraEvents: extra });
    const stC = roomStats(cau, C, RC), stE = exp && exp.ok ? roomStats(exp, C, RE) : stC;
    const gs = typeof E.goalStatus === 'function' ? E.goalStatus(p, T, { fc: cau }) : { goals: [] };
    const bud = E.budgetStatus(p, T, base).find(r => r.category === category) || null;
    let remainingAfter = null, overBy = 0, budgetOk = true;
    if (kind === 'flexible' && bud && bud.basis === 'approved') {
      if (D.monthKey(day) === D.monthKey(T)) remainingAfter = day <= T ? bud.remainingCents : bud.remainingCents - amount;
      else remainingAfter = bud.plannedCents - amount;
      overBy = Math.max(0, -remainingAfter);
      budgetOk = remainingAfter >= 0;
    }
    return {
      plan: p, day, extra, cautious: stC, expected: stE, goals: gs, budget: bud,
      remainingAfterCents: remainingAfter, overByCents: overBy, budgetOk,
      safe: stC.okWithReserve, okCushion: stC.okCushion,
      restores: !!(stC.okWithReserve && stC.okCushion && budgetOk)
    };
  }
  function packAlt(kind, pr, extra) {
    extra = extra || {};
    const restores = extra.restores != null ? extra.restores : !!(pr && pr.restores);
    return Object.assign({
      kind, available: true, requiresExplicitChoice: extra.requiresExplicitChoice === true, restores, recommended: false,
      text: extra.text || '', day: extra.day == null ? null : extra.day, weeklyCents: extra.weeklyCents == null ? null : extra.weeklyCents,
      choice: extra.choice || null, budgets: extra.budgets || null, goals: extra.goals || (pr ? compactGoals(pr.goals) : []),
      validation: pr ? validationOf(pr) : { safe: false, okCushion: false, budgetOk: false, restores: false, minCents: 0, minDay: null, endCents: 0, scenarios: { cautious: { safe: false, okCushion: false, minCents: 0, minDay: null, endCents: 0 }, expected: { safe: false, okCushion: false, minCents: 0, minDay: null, endCents: 0 } } }
    }, extra.more || {});
  }
  function unavailable(kind, text, extra) {
    extra = extra || {};
    return Object.assign({
      kind, available: false, requiresExplicitChoice: extra.requiresExplicitChoice === true, restores: false, recommended: false,
      text, day: null, weeklyCents: extra.weeklyCents == null ? null : extra.weeklyCents, choice: null, budgets: null, goals: [],
      validation: { safe: false, okCushion: false, budgetOk: false, restores: false, minCents: 0, minDay: null, endCents: 0, scenarios: { cautious: { safe: false, okCushion: false, minCents: 0, minDay: null, endCents: 0 }, expected: { safe: false, okCushion: false, minCents: 0, minDay: null, endCents: 0 } } }
    }, extra.more || {});
  }
  function sameChoice(a, b) {
    return JSON.stringify(a || null) === JSON.stringify(b || null);
  }
  function findPurchaseAlternatives(plan, T, ctx, H, gsBefore) {
    const alts = [], fmt = E.fmt, label = D.label, amount = ctx.amount, category = ctx.category, kind = ctx.kind;
    const disc = typeof E.discretionaryPlan === 'function' ? E.discretionaryPlan(plan, T) : { plannedWeeklyCents: 0, effectiveFloorWeeklyCents: 0 };
    const contrib = plan.goals.filter(g => g.contribution && g.status === 'active');
    const beforeRows = compactGoals(gsBefore);

    // 1. Delay until the earliest day the current plan can absorb it (planned spending + current goals + budget month).
    const nextMonth = D.monthStart(D.addMonths(T, 1));
    const last = probePurchase(plan, T, { day: H, expected: false }, ctx);
    let delay = null;
    if (last && last.safe) {
      const start = (kind === 'flexible' && ctx.budgetApproved && ctx.remainingBeforeCents < amount) ? Math.max(T + 1, nextMonth) : T + 1;
      for (let day = start; day <= H; day++) {
        const pr = probePurchase(plan, T, { day, expected: false }, ctx);
        if (pr && pr.restores) { delay = probePurchase(plan, T, { day }, ctx); break; }
      }
    }
    if (delay && delay.day > T) alts.push(packAlt('delay', delay, {
      day: delay.day, text: 'Wait until ' + label(delay.day) + ' (' + (delay.day - T) + ' day' + (delay.day - T === 1 ? '' : 's') + ' from now). Your approved plan stays as it is.',
      goals: goalDelta(beforeRows, compactGoals(delay.goals))
    }));
    else alts.push(unavailable('delay', last && last.safe
      ? 'No later date before ' + label(H) + ' keeps this purchase inside your approved discretionary budget and at or above your cushion.'
      : 'It does not fit before the end of the term on ' + label(H) + ' even if you wait, unless something else changes.'));

    // 2. Reduce discretionary spending toward the weekly minimum (never automatically).
    if (disc.plannedWeeklyCents > disc.effectiveFloorWeeklyCents) {
      const floorPr = probePurchase(plan, T, { choice: { discretionary: { weeklyCents: disc.effectiveFloorWeeklyCents } }, day: T }, ctx);
      if (floorPr && floorPr.restores) {
        let lo = Math.ceil(disc.effectiveFloorWeeklyCents / DOLLAR), hi = Math.floor((disc.plannedWeeklyCents - 1) / DOLLAR), best = { w: disc.effectiveFloorWeeklyCents, pr: floorPr };
        while (lo <= hi) {
          const mid = (lo + hi) >> 1, w = mid * DOLLAR, pr = probePurchase(plan, T, { choice: { discretionary: { weeklyCents: w } }, day: T, expected: false }, ctx);
          if (pr && pr.restores) { best = { w, pr }; lo = mid + 1; } else hi = mid - 1;
        }
        const full = best.w === disc.effectiveFloorWeeklyCents ? floorPr : probePurchase(plan, T, { choice: { discretionary: { weeklyCents: best.w } }, day: T }, ctx);
        alts.push(packAlt('reduce_discretionary', full, {
          requiresExplicitChoice: true, weeklyCents: best.w, choice: { discretionary: { weeklyCents: best.w } },
          text: 'Lower discretionary spending to ' + fmt(best.w) + ' a week (from ' + fmt(disc.plannedWeeklyCents) + '). Change this on Budgets — nothing updates unless you choose it.',
          more: { cutWeeklyCents: disc.plannedWeeklyCents - best.w, floorWeeklyCents: disc.effectiveFloorWeeklyCents },
          goals: goalDelta(beforeRows, compactGoals(full.goals))
        }));
      } else alts.push(unavailable('reduce_discretionary', 'Even at your weekly minimum of ' + fmt(disc.effectiveFloorWeeklyCents) + ' for discretionary spending, this purchase would not stay at or above your cushion.', { requiresExplicitChoice: true, weeklyCents: disc.effectiveFloorWeeklyCents, more: { floorWeeklyCents: disc.effectiveFloorWeeklyCents } }));
    } else alts.push(unavailable('reduce_discretionary', 'Your discretionary spending is already at your weekly minimum.', { requiresExplicitChoice: true, weeklyCents: disc.effectiveFloorWeeklyCents, more: { floorWeeklyCents: disc.effectiveFloorWeeklyCents } }));

    // 3. Adjust savings contributions (pause lowest-priority first, then the allocation the leftover cash can support).
    if (contrib.length && typeof E.writeGoalChoice === 'function') {
      const ordered = typeof E.goalOrder === 'function' ? E.goalOrder(plan).filter(g => g.contribution && g.status === 'active') : contrib.slice();
      let pauseHit = null, paused = [];
      for (let i = ordered.length - 1; i >= 0; i--) {
        paused.push(ordered[i].id);
        const choice = { goals: paused.map(id => ({ id, amountCents: 0 })) };
        const pr = probePurchase(plan, T, { choice, day: T }, ctx);
        if (pr && pr.restores) { pauseHit = { pr, choice, names: paused.map(id => (plan.goals.find(g => g.id === id) || {}).name).filter(Boolean) }; break; }
      }
      if (pauseHit) alts.push(packAlt('pause_goals', pauseHit.pr, {
        requiresExplicitChoice: true, choice: pauseHit.choice,
        text: 'Pause saving for ' + pauseHit.names.map(n => '"' + n + '"').join(' and ') + ' so this stays at or above your cushion. Change this on Goals.',
        goals: goalDelta(beforeRows, compactGoals(pauseHit.pr.goals))
      }));
      else alts.push(unavailable('pause_goals', contrib.length ? 'Even with every savings contribution paused, this purchase would not stay at or above your cushion.' : 'There are no savings contributions to pause.', { requiresExplicitChoice: true }));

      if (typeof E.goalAllocation === 'function') {
        const sim = E.addManualTx(plan, { amountCents: amount, category, desc: ctx.desc, date: D.fmt(T) }, T);
        if (sim.ok) {
          const alloc = E.goalAllocation(sim.plan, T);
          if (alloc.ok && alloc.choice) {
            const pr = probePurchase(plan, T, { choice: alloc.choice, day: T }, ctx);
            const changed = (alloc.changes || []).some(c => c.fromCents !== c.toCents);
            if (pr && pr.restores && changed && !sameChoice(alloc.choice, pauseHit && pauseHit.choice)) {
              alts.push(packAlt('adjust_savings', pr, {
                requiresExplicitChoice: true, choice: alloc.choice,
                text: 'Lower goal transfers to what leftover cash can support after this purchase (deadlines may slip). Change this on Goals.',
                goals: goalDelta(beforeRows, compactGoals(pr.goals))
              }));
            } else if (!(pr && pr.restores && changed)) alts.push(unavailable('adjust_savings', changed ? 'Lowering your goal transfers to what is left still would not keep this purchase at or above your cushion.' : 'Your current savings contributions are already the amounts this purchase can support, or there is nothing to lower.', { requiresExplicitChoice: true }));
          }
        }
      }
    }

    // 4. Extend a goal deadline (and the lower per-transfer amount that longer window allows).
    if (contrib.length && typeof E.goalAllocation === 'function') {
      const sim = E.addManualTx(plan, { amountCents: amount, category, desc: ctx.desc, date: D.fmt(T) }, T);
      let found = null;
      if (sim.ok) {
        for (const g of contrib) {
          const due = D.parse(g.dueDate); if (due === null || due >= H) continue;
          const alloc = E.goalAllocation(sim.plan, T, { overrides: [{ id: g.id, dueDate: D.fmt(H) }], expected: false, classify: false });
          if (!alloc.ok || !alloc.choice) continue;
          const pr = probePurchase(plan, T, { choice: alloc.choice, day: T }, ctx);
          if (pr && pr.restores) { found = { pr, choice: alloc.choice, g, due: H }; break; }
        }
      }
      if (found) alts.push(packAlt('later_deadline', found.pr, {
        requiresExplicitChoice: true, choice: found.choice, more: { dueDate: D.fmt(found.due), goalId: found.g.id },
        text: 'Move the deadline for "' + found.g.name + '" to ' + label(found.due) + ' so transfers are smaller. Change this on Goals.',
        goals: goalDelta(beforeRows, compactGoals(found.pr.goals))
      }));
      else alts.push(unavailable('later_deadline', 'No later deadline before the end of the term would make this purchase stay at or above your cushion.', { requiresExplicitChoice: true }));
    }

    // 5. Change goal priorities where that actually frees enough cash.
    if (contrib.length >= 2 && typeof E.goalAllocation === 'function') {
      const order = (typeof E.goalOrder === 'function' ? E.goalOrder(plan) : contrib).map(g => g.id).filter((id, i, a) => a.indexOf(id) === i);
      const reversed = order.slice().reverse();
      const sim = E.addManualTx(plan, { amountCents: amount, category, desc: ctx.desc, date: D.fmt(T) }, T);
      let pr = null, choice = null;
      if (sim.ok) {
        const alloc = E.goalAllocation(sim.plan, T, { order: reversed, expected: false, classify: false });
        if (alloc.ok && alloc.choice) { choice = alloc.choice; pr = probePurchase(plan, T, { choice, day: T }, ctx); }
      }
      if (pr && pr.restores && !alts.some(a => a.available && a.choice && sameChoice(a.choice, choice))) alts.push(packAlt('priority', pr, {
        requiresExplicitChoice: true, choice, more: { order: reversed },
        text: 'Fund "' + ((plan.goals.find(g => g.id === reversed[0]) || {}).name || 'the lower-priority goal') + '" first so leftover cash covers this purchase. Change this on Goals.',
        goals: goalDelta(beforeRows, compactGoals(pr.goals))
      }));
      else alts.push(unavailable('priority', 'Changing which goal is funded first would not make this purchase stay at or above your cushion.', { requiresExplicitChoice: true }));
    }

    return alts;
  }

  /* ---------- the most ONE purchase can be today, under the whole plan ---------- */
  // Same tests the classification applies: the cautious planned path (approved budgets and goal transfers still to be spent) keeps the cushion and
  // the after-term reserve on every day, and bills after the term stay covered. A payment today lowers every later balance by its amount, so the limit
  // is the smallest margin on that path. It is for a purchase outside a monthly category budget; a category with its own budget also needs room in it.
  // todayView's "safe to spend" (commitments room) is larger by plannedSpendingCents: the approved-budget spending still planned through the term end.
  E.purchaseLimit = function (plan, T, opts) {
    opts = opts || {};
    const snap = opts.snap || E.snapshot(plan, T);
    if (!snap || !snap.ok) return { ok: false, maxCents: 0 };
    const capC = snap.cautious.capacity, pl = snap.cautious.planned, fc = snap.cautious.fc;
    if (!capC || !capC.ok || !pl || !pl.ok) return { ok: false, maxCents: 0 };
    const C = plan.account.cushionCents, R = capC.reserve.totalCents, N = pl.N;
    let marginCents = Infinity, lowDay = pl.today, atEnd = false;
    pl.days.forEach((d, k) => { const adj = d.bal - C - (k === N ? R : 0); if (adj < marginCents) { marginCents = adj; lowDay = d.day; atEnd = k === N; } });
    const at = afterTermStats(plan, T, snap);
    let maxCents = Math.max(0, marginCents), limitedBy = atEnd && R > 0 ? 'reserve' : 'cushion';
    if (at && at.minCents < maxCents) { maxCents = Math.max(0, at.minCents); limitedBy = 'after_term'; }
    const plannedSpendingCents = Math.max(0, fc.days[fc.N].bal - pl.days[N].bal);
    return { ok: true, maxCents, limitedBy, lowDay, marginCents, commitmentsRoomCents: capC.immediate.cents, plannedSpendingCents, cushionCents: C, reserveCents: R, endDay: pl.endDay };
  };

  /* ---------- "Can I afford this?" ---------- */
  // opts: { today, amountCents, desc?, category?, snap? }  ->  a plain object the screen draws. Records nothing, changes nothing.
  E.purchaseCheck = function (plan, opts) {
    opts = opts || {};
    const T = opts.today, amount = Math.round(Number(opts.amountCents));
    if (!Number.isSafeInteger(amount) || amount <= 0) return { ok: false, error: 'Enter an amount above $0.' };
    if (amount > 1e8) return { ok: false, error: 'That amount is too large to check.' };
    const desc = E.safeStr(opts.desc, 120), picked = E.CATEGORIES[opts.category] ? opts.category : '';
    const category = picked || (desc ? E.categoryOf(desc, plan.catRules) : 'Other'), kind = E.catKind(category);
    const snap = opts.snap || E.snapshot(plan, T);
    if (!snap || !snap.ok) return { ok: false, error: 'Enter your checking balance first.' };
    const trust = E.trust(plan, T, snap), fmt = E.fmt, label = D.label;
    const out = {
      ok: true, amountCents: amount, desc, category, categoryKind: kind, categoryPicked: !!picked, today: T, trust: { level: trust.level, badge: trust.badge },
      provisional: trust.level === 'provisional', verdict: 'needs_info', classification: 'needs_info', recommended: false, tone: 'grey', headline: '', summary: '', lines: [], advice: [], recorded: false,
      alternatives: [], planUnchanged: true, goals: { before: [], after: [], stillFit: false, affected: false }, question: null, heavy: false, alreadyBelowCushion: false, classificationExpected: 'needs_info'
    };
    if (!trust.showAllowance) {
      const q = trust.missing[0];
      out.headline = 'I cannot give you a reliable answer yet';
      out.summary = 'Campus Compass is missing something it needs to answer honestly' + (q ? ': ' + q.question : '.') + ' Until then any yes would quietly leave something out.';
      out.question = q ? { id: q.id, question: q.question, why: q.why } : null;
      return out;
    }
    const sim = E.addManualTx(plan, { amountCents: amount, category, desc, date: D.fmt(T) }, T);
    if (!sim.ok) return { ok: false, error: sim.error };
    // Count the purchase once as cash; keep the live plan's spending estimates (no thin inflate from the preview).
    const snap2 = E.snapshot(sim.plan, T, { det: snap.det, base: snap.base });
    const capC = snap.cautious.capacity, capE = snap.expected.capacity, capC2 = snap2.cautious.capacity, capE2 = snap2.expected.capacity;
    const C = plan.account.cushionCents, RC = capC.reserve.totalCents, RE = capE.reserve.totalCents;
    // The most one purchase can be under the WHOLE plan. The commitments-only room (capC.immediate) leaves out the approved-budget spending still planned.
    const limit = E.purchaseLimit(plan, T, { snap }), lim = limit.ok ? limit.maxCents : 0;
    out.limit = limit.ok ? { cents: lim, commitmentsRoomCents: limit.commitmentsRoomCents, plannedSpendingCents: limit.plannedSpendingCents, limitedBy: limit.limitedBy, lowDay: limit.lowDay, endDay: limit.endDay } : null;
    const before = { cautious: roomStats(snap.cautious.fc, C, RC), expected: roomStats(snap.expected.fc, C, RE) };
    const after = { cautious: roomStats(snap2.cautious.fc, C, RC), expected: roomStats(snap2.expected.fc, C, RE) };
    const cau = after.cautious, exp = after.expected;
    const remToday = capC.todayLimit.remainingCents, paceToday = capC.todayLimit.allowanceCents;
    const fitsPace = kind !== 'essential' && amount <= remToday && capC.safe;

    /* the verdict (headline case = cautious; expected is reported beside it) */
    let reason = '';
    if (!capC.safe) { out.verdict = 'not_now'; reason = 'shortfall'; }
    else if (cau.okWithReserve && exp.okWithReserve) { out.verdict = fitsPace ? 'fits_pace' : 'fits_room'; }
    else if (cau.okCushion && !cau.okWithReserve && exp.okCushion) { out.verdict = 'tight'; reason = 'reserve'; }
    else if (!cau.okCushion && exp.okCushion) { out.verdict = 'tight'; reason = 'cautious'; }
    else { out.verdict = 'not_now'; reason = cau.negative ? 'bills' : 'cushion'; }
    out.reason = reason;
    out.tone = { fits_pace: 'good', fits_room: 'good', tight: 'amber', not_now: 'bad' }[out.verdict];
    out.fitsTodayPace = fitsPace;

    /* the numbers behind it */
    const budBefore = E.budgetStatus(plan, T, snap.base).find(r => r.category === category) || null, budAfter = E.budgetStatus(sim.plan, T, snap.base).find(r => r.category === category) || null;
    out.budget = budBefore ? { category, approved: budBefore.basis === 'approved', basis: budBefore.basis, plannedCents: budBefore.plannedCents, remainingBeforeCents: budBefore.remainingCents, remainingAfterCents: budAfter ? budAfter.remainingCents : budBefore.remainingCents - amount, overByCents: Math.max(0, -(budAfter ? budAfter.remainingCents : budBefore.remainingCents - amount)) } : null;
    const tmB = E.paceFromTomorrow(capC), tmA = E.paceFromTomorrow(capC2);
    out.effect = {
      todayRemainingBeforeCents: remToday, todayRemainingAfterCents: capC2.todayLimit.remainingCents, todayPaceCents: paceToday,
      weekRemainingBeforeCents: capC.week.remainingCents, weekRemainingAfterCents: capC2.week.remainingCents,
      monthRemainingBeforeCents: capC.month.remainingCents, monthRemainingAfterCents: capC2.month.remainingCents,
      semesterRoomBeforeCents: capC.semester.remainingCents, semesterRoomAfterCents: capC2.semester.remainingCents, semesterEndDay: capC.endDay,
      tomorrowPaceBeforeCents: tmB.cents, tomorrowPaceAfterCents: tmA.cents,
      lowestBefore: { cautiousCents: before.cautious.minCents, expectedCents: before.expected.minCents },
      lowestAfter: { cautiousCents: cau.minCents, cautiousDay: cau.minDay, expectedCents: exp.minCents, expectedDay: exp.minDay },
      endBalanceBeforeCents: before.cautious.endCents, endBalanceAfterCents: cau.endCents, oneTimeMaxCents: capC.immediate.cents, oneTimeMaxExpectedCents: capE.immediate.cents
    };
    out.scenarios = { cautious: { fits: cau.okWithReserve, minCents: cau.minCents, minDay: cau.minDay, short: cau.shortByCents }, expected: { fits: exp.okWithReserve, minCents: exp.minCents, minDay: exp.minDay, short: exp.shortByCents }, differ: cau.okWithReserve !== exp.okWithReserve };
    const wC = earliestFit(snap.cautious.fc, amount, C, RC), wE = earliestFit(snap.expected.fc, amount, C, RE);
    out.earliest = { cautiousDay: wC, expectedDay: wE, cautiousWaitDays: wC === null ? null : wC - T, expectedWaitDays: wE === null ? null : wE - T };
    const causeC = cau.firstNegativeDay !== null ? causeOf(snap2.cautious.fc, cau.firstNegativeDay) : cau.firstBelowCushionDay !== null ? causeOf(snap2.cautious.fc, cau.firstBelowCushionDay) : null;
    out.cause = causeC;
    out.goalImpact = plan.goals.filter(g => g.contribution).map(g => { const mo = E.monthlyEquivalent(g.contribution.schedule, g.contribution.amountCents); return { id: g.id, name: g.name, monthsOfContributions: mo > 0 ? Math.round(amount / mo * 10) / 10 : null }; });

    /* the explanation, one plain sentence per question the student asked */
    const L = out.lines, e = out.effect;
    // 1. bills
    if (cau.negative) L.push({ id: 'bills', tone: 'bad', title: 'Upcoming bills', text: 'In the cautious view you would be about ' + fmt(-cau.minCents) + ' short around ' + label(cau.firstNegativeDay) + (causeC ? ', when ' + causeC.name + ' (' + fmt(causeC.amountCents) + ') is due' : '') + '.' });
    else L.push({ id: 'bills', tone: 'good', title: 'Upcoming bills', text: 'Every bill and paycheck-dependent payment stays covered. Your lowest balance afterwards is ' + fmt(cau.minCents) + ' on ' + label(cau.minDay) + '.' });
    // 2. cushion
    if (cau.okCushion) L.push({ id: 'cushion', tone: cau.okWithReserve ? 'good' : 'amber', title: 'Your cushion', text: cau.okWithReserve ? 'Your ' + fmt(C) + ' cushion stays untouched.' : 'Your ' + fmt(C) + ' cushion stays, but it eats ' + fmt(cau.reserveShortByCents) + ' of the ' + fmt(RC) + ' you are keeping for after the term.' });
    else L.push({ id: 'cushion', tone: 'bad', title: 'Your cushion', text: 'Your balance would sink to ' + fmt(cau.minCents) + ' on ' + label(cau.minDay) + ', which is ' + fmt(cau.shortByCents) + ' below your ' + fmt(C) + ' cushion.' + (!before.cautious.okCushion ? ' (It is already below the cushion before this purchase.)' : '') });
    // 3. today's pace
    if (kind === 'essential') L.push({ id: 'pace', tone: 'blue', title: 'Today\'s pace', text: category + ' is an everyday essential. Money for it is already set aside each day, so this mostly uses what is reserved instead of your spending pace.' });
    else if (amount <= remToday) L.push({ id: 'pace', tone: 'good', title: 'Today\'s pace', text: 'It is within what is left of today\'s pace (' + fmt(remToday) + '). After it you have ' + fmt(e.todayRemainingAfterCents) + ' left today.' });
    else if (remToday > 0) L.push({ id: 'pace', tone: 'amber', title: 'Today\'s pace', text: 'It is ' + fmt(amount - remToday) + ' more than what is left of today\'s pace (' + fmt(remToday) + '). That is fine as a one-off only because your balance can absorb it. The extra comes out of the days ahead.' });
    else L.push({ id: 'pace', tone: 'amber', title: 'Today\'s pace', text: 'You have already used today\'s pace' + (remToday < 0 ? ' (' + fmt(-remToday) + ' over)' : '') + ', so all of this comes out of the days ahead.' });
    // 4. monthly budget
    if (out.budget && out.budget.approved) {
      const b = out.budget;
      L.push({ id: 'budget', tone: b.overByCents > 0 ? 'amber' : 'good', title: 'Your ' + category + ' budget', text: b.overByCents > 0 ? 'You approved ' + fmt(b.plannedCents) + ' a month for ' + category + '. This puts you ' + fmt(b.overByCents) + ' over it. Your budget is not changed.' : 'You approved ' + fmt(b.plannedCents) + ' a month for ' + category + '. After this you have ' + fmt(b.remainingAfterCents) + ' left in it (from ' + fmt(b.remainingBeforeCents) + ').' });
    } else if (kind !== 'essential') L.push({ id: 'budget', tone: 'blue', title: 'Your monthly budget', text: 'You have not approved a monthly budget for ' + category + (picked ? '' : ' (guessed from what you typed)') + ', so nothing is compared. Your plan\'s room for this month goes from ' + fmt(e.monthRemainingBeforeCents) + ' to ' + fmt(e.monthRemainingAfterCents) + '.' });
    else if (out.budget) L.push({ id: 'budget', tone: 'blue', title: 'Your ' + category + ' budget', text: out.budget.approved ? '' : 'You have not approved a ' + category + ' budget. The amount your plan sets aside for it is ' + fmt(out.budget.plannedCents) + ' a month.' });
    // 5. semester outlook
    L.push({ id: 'semester', tone: e.semesterRoomAfterCents < 0 ? 'bad' : 'blue', title: 'The rest of the semester', text: 'Room for all flexible spending through ' + label(e.semesterEndDay) + ' (before your approved budgets draw from it) goes from ' + fmt(e.semesterRoomBeforeCents) + ' to ' + fmt(Math.max(0, e.semesterRoomAfterCents)) + '. Your daily pace from tomorrow goes from ' + fmt(e.tomorrowPaceBeforeCents) + ' to ' + fmt(e.tomorrowPaceAfterCents) + '.' });
    if (limit.ok) L.push({ id: 'limit', tone: 'blue', title: 'The most one purchase can be today', text: fmt(lim) + ' under your full plan (cushion, bills, approved budgets and the money kept for after the term).' + (limit.plannedSpendingCents > 0 ? ' It is lower than the ' + fmt(e.semesterRoomBeforeCents) + ' room above because your approved budgets still plan to spend about ' + fmt(limit.plannedSpendingCents) + ' of it by ' + label(e.semesterEndDay) + '.' : '') });
    // 6. cautious vs expected
    if (out.scenarios.differ) L.push({ id: 'scenarios', tone: 'amber', title: 'Cautious versus expected', text: exp.okWithReserve ? 'If your income and aid arrive on time (expected), it fits. In the cautious view (irregular pay at its lowest, aid ' + plan.settings.cautiousLateDays + ' days late) it does not.' : 'It fits in the cautious view but not in the expected one.' });
    else L.push({ id: 'scenarios', tone: 'grey', title: 'Cautious versus expected', text: 'The answer is the same whether your income and aid arrive as hoped or not.' });
    if (out.provisional) L.push({ id: 'provisional', tone: 'amber', title: 'How sure is this?', text: 'Provisional. Your plan rests on limited information, so treat this as a careful estimate, not a measurement.' });
    if (out.goalImpact.length) for (const g of out.goalImpact) if (g.monthsOfContributions) L.push({ id: 'goal-' + g.id, tone: 'blue', title: 'Your goal: ' + g.name, text: 'It equals about ' + g.monthsOfContributions + ' month' + (g.monthsOfContributions === 1 ? '' : 's') + ' of what you save toward it.' });

    /* the one-line answer, and what would make a "no" into a "yes" */
    const imm = capC.immediate.cents, adv = out.advice;
    switch (out.verdict) {
      case 'fits_pace': out.headline = 'Yes, that fits'; out.summary = 'It is within today\'s pace, your bills stay covered and your cushion is untouched.'; break;
      case 'fits_room': {
        // "heavy": it fits the bills and the cushion, but it takes most of the room left for the rest of the term
        const roomB = e.semesterRoomBeforeCents, roomA = Math.max(0, e.semesterRoomAfterCents);
        out.heavy = kind !== 'essential' && roomB > 0 && (roomA < roomB * 0.5 || e.monthRemainingAfterCents < 0);
        out.headline = kind === 'essential' ? 'Yes, that fits' : out.heavy ? 'Yes, but it uses most of your room' : 'Yes, but it is more than today\'s pace';
        out.summary = kind === 'essential' ? 'Your bills stay covered and your cushion is untouched.' : 'Your bills stay covered and your cushion is untouched, but it uses ' + fmt(Math.max(0, amount - Math.max(0, remToday))) + ' of room you would otherwise spread over the next days' + (out.heavy ? ', leaving ' + fmt(roomA) + ' of room (about ' + fmt(e.tomorrowPaceAfterCents) + ' a day) through ' + label(e.semesterEndDay) : '') + '.';
        if (out.heavy) out.tone = 'amber';
        break;
      }
      case 'tight':
        out.headline = reason === 'reserve' ? 'Possible, but it uses money you set aside' : 'Only if your income and aid arrive on time';
        out.summary = reason === 'reserve' ? 'It keeps your cushion, but it would take about ' + fmt(cau.reserveShortByCents) + ' from the money you are keeping for after the term.' : 'In the expected case it fits. In the cautious case it would put you ' + fmt(cau.shortByCents) + ' below your cushion' + (cau.negative ? ' and short on a bill' : '') + '.'; break;
      default:
        out.headline = 'Not right now';
        out.summary = reason === 'shortfall' ? 'Your listed bills and essentials already use up your cushion' + (capC.shortfall.firstDay ? ' by ' + label(capC.shortfall.firstDay) : '') + ', so there is no room for an extra purchase.' : reason === 'bills' ? 'It would leave you ' + fmt(-cau.minCents) + ' short on ' + label(cau.firstNegativeDay) + (causeC ? ' when ' + causeC.name + ' is due' : '') + '.' : 'It would take you ' + fmt(cau.shortByCents) + ' below your ' + fmt(C) + ' cushion on ' + label(cau.minDay) + '.';
    }
    if (out.verdict === 'tight' || out.verdict === 'not_now') {
      // Offer only an amount the full plan would itself call affordable. Bills and essentials alone (imm) can allow more than the approved budgets leave.
      if (lim > 0 && amount > lim) adv.push({ kind: 'smaller', amountCents: lim, text: 'An amount up to ' + fmt(lim) + ' fits today under your full plan (cushion, bills, approved budgets and the money kept for after the term).' });
      else if (lim <= 0 && imm > 0 && amount > imm) adv.push({ kind: 'smaller', amountCents: imm, text: 'On bills and essentials alone, an amount up to ' + fmt(imm) + ' fits today in the cautious view, but your approved budgets leave nothing extra, so nothing is affordable under your full plan until that changes.' });
      else if (imm <= 0 && out.verdict === 'not_now') adv.push({ kind: 'none_today', text: 'Nothing extra fits today' + (capC.immediate.limitedBy && capC.immediate.limitedBy.label ? ' because of ' + capC.immediate.limitedBy.label : '') + '.' });
      if (wC !== null && wC > T) adv.push({ kind: 'wait', day: wC, text: 'In the cautious view it fits from ' + label(wC) + ' (' + (wC - T) + ' day' + (wC - T === 1 ? '' : 's') + ' from now), as long as you hold off on other flexible spending until then.' });
      else if (wC === null && wE !== null && wE > T) adv.push({ kind: 'wait_expected', day: wE, text: 'If your income and aid arrive as hoped it fits from ' + label(wE) + '. In the cautious view it does not fit before ' + label(snap.cautious.fc.endDay) + '.' });
      else if (wC === null && wE === null) adv.push({ kind: 'not_this_term', text: 'It does not fit before the end of the term on ' + label(snap.cautious.fc.endDay) + ' in either view, unless something else changes (more income, a lower bill).' });
      if (wC !== null && wE !== null && wE < wC) adv.push({ kind: 'expected_earlier', day: wE, text: 'If everything arrives on time it would fit as early as ' + label(wE) + '.' });
    }
    if (out.verdict === 'fits_room' && kind !== 'essential' && e.tomorrowPaceAfterCents < e.tomorrowPaceBeforeCents) adv.push({ kind: 'cost', text: 'The cost is a lower daily pace afterwards. Buying it later, or a cheaper version, keeps more of your pace.' });
    out.imm = { cents: imm, expectedCents: capE.immediate.cents };

    /* Stage D: classify against the full planned forecast. Never writes the plan. Never calls a below-cushion path affordable. */
    const plannedBeforeC = roomStats(snap.cautious.planned, C, RC), plannedAfterC = roomStats(snap2.cautious.planned, C, RC);
    const plannedBeforeE = roomStats(snap.expected.planned, C, RE), plannedAfterE = roomStats(snap2.expected.planned, C, RE);
    const budgetOk = !(out.budget && out.budget.approved && kind === 'flexible' && out.budget.overByCents > 0);
    const alreadyBelow = !plannedBeforeC.okCushion;
    const todayFitC = plannedAfterC.okWithReserve && plannedAfterC.okCushion && budgetOk;
    const todayFitE = plannedAfterE.okWithReserve && plannedAfterE.okCushion && budgetOk;
    const gsBefore = typeof E.goalStatus === 'function' ? E.goalStatus(plan, T, { fc: snap.cautious.fc }) : { goals: [] };
    const gsAfter = typeof E.goalStatus === 'function' ? E.goalStatus(sim.plan, T, { fc: snap2.cautious.fc }) : { goals: [] };
    const beforeRows = compactGoals(gsBefore), afterRows = compactGoals(gsAfter);
    out.effect.plannedLowestBefore = { cautiousCents: plannedBeforeC.minCents, cautiousDay: plannedBeforeC.minDay, expectedCents: plannedBeforeE.minCents, expectedDay: plannedBeforeE.minDay };
    out.effect.plannedLowestAfter = { cautiousCents: plannedAfterC.minCents, cautiousDay: plannedAfterC.minDay, expectedCents: plannedAfterE.minCents, expectedDay: plannedAfterE.minDay };
    out.effect.cushionCents = C; out.effect.cushionShortAfterCents = plannedAfterC.shortByCents;
    out.effect.reserveCents = RC; out.effect.reserveShortAfterCents = plannedAfterC.reserveShortByCents;
    out.scenarios.cautious.plannedFits = todayFitC; out.scenarios.cautious.plannedMinCents = plannedAfterC.minCents; out.scenarios.cautious.plannedMinDay = plannedAfterC.minDay; out.scenarios.cautious.okCushion = plannedAfterC.okCushion;
    out.scenarios.expected.plannedFits = todayFitE; out.scenarios.expected.plannedMinCents = plannedAfterE.minCents; out.scenarios.expected.plannedMinDay = plannedAfterE.minDay; out.scenarios.expected.okCushion = plannedAfterE.okCushion;
    out.goals = { before: beforeRows, after: afterRows, stillFit: todayFitC, affected: !todayFitC || beforeRows.some((g, i) => afterRows[i] && (afterRows[i].contributionCents !== g.contributionCents || afterRows[i].completionDay !== g.completionDay)), deltas: goalDelta(beforeRows, afterRows) };
    const atBefore = afterTermStats(plan, T, snap), atAfter = afterTermStats(sim.plan, T, snap2);
    const afterTermOk = !atAfter || atAfter.ok;
    out.afterTerm = atAfter ? { ok: atAfter.ok, okBefore: !atBefore || atBefore.ok, startDay: atAfter.startDay, endDay: atAfter.endDay, endedBy: atAfter.endedBy, aidName: atAfter.aidName, minCents: atAfter.minCents, minDay: atAfter.minDay, firstShortDay: atAfter.firstShortDay, shortByCents: atAfter.shortByCents, cause: atAfter.cause } : null;
    let classification = 'unaffordable', alts = [];
    if (todayFitC && afterTermOk) classification = 'affordable';
    else if (todayFitC) classification = 'unaffordable';
    else {
      const ctx = { amount, category, desc, kind, C, RC, RE, budgetApproved: !!(out.budget && out.budget.approved), remainingBeforeCents: out.budget ? out.budget.remainingBeforeCents : 0 };
      alts = findPurchaseAlternatives(plan, T, ctx, snap.cautious.fc.endDay, gsBefore);
      classification = alts.some(a => a.available && a.restores && a.validation && a.validation.okCushion) ? 'needs_changes' : 'unaffordable';
    }
    for (const a of alts) {
      if (!a.validation || !a.validation.okCushion) { a.restores = false; if (a.validation) a.validation.restores = false; }
      a.recommended = false;
    }
    out.classification = classification;
    out.recommended = classification === 'affordable';
    if (alreadyBelow || !plannedAfterC.okCushion) out.recommended = false;
    let classificationE = 'unaffordable';
    if (!plannedBeforeE.okCushion) classificationE = 'unaffordable';
    else if (todayFitE) classificationE = 'affordable';
    else classificationE = alts.some(a => a.available && a.validation && a.validation.scenarios.expected.okCushion && a.validation.scenarios.expected.safe) ? 'needs_changes' : 'unaffordable';
    out.classificationExpected = classificationE;
    out.alternatives = alts;
    out.alreadyBelowCushion = alreadyBelow;
    // The headline must never say "yes" when the full plan says no: bills alone may absorb it while planned budgets and savings do not.
    out.headlineFollowsPlan = false;
    const at = out.afterTerm, afterTermOnly = todayFitC && !afterTermOk;
    out.reasonAfterTerm = afterTermOnly;
    if (afterTermOnly) {
      out.headlineFollowsPlan = true;
      const runOut = at.cause && at.cause.day === at.firstShortDay ? 'you could not pay ' + at.cause.name + ' (' + fmt(at.cause.amountCents) + ') on ' + label(at.cause.day)
        : 'your money would run out around ' + label(at.firstShortDay) + (at.cause ? ', before ' + at.cause.name + ' (' + fmt(at.cause.amountCents) + ') is due on ' + label(at.cause.day) : '');
      const until = at.endedBy === 'aid' ? 'before ' + at.aidName + ' arrives' : 'in the ' + E.AFTER_TERM_DAYS + ' days after the term';
      out.headline = 'Not if you want to pay your bills after the term';
      out.summary = (at.okBefore
        ? 'It fits this term, but after the term ends ' + runOut + '. Without this purchase your bills and food stay covered ' + until + '.'
        : 'It fits this term, but after the term ends you are already short ' + until + ': ' + runOut + '. This purchase makes the gap about ' + fmt(at.shortByCents) + '.')
        + ' Setting money aside for between terms on My plan protects those bills.';
      out.tone = 'bad';
      const bl = L.find(l => l.id === 'bills');
      if (bl && bl.tone === 'good') { bl.tone = 'amber'; bl.text = 'Every bill due by ' + label(snap.cautious.fc.endDay) + ' stays covered. Your lowest balance this term is ' + fmt(cau.minCents) + ' on ' + label(cau.minDay) + '.'; }
      L.splice(bl ? L.indexOf(bl) + 1 : 0, 0, { id: 'after_term', tone: 'bad', title: 'After the term', text: 'Counting only bills and essentials (no other spending at all), your balance would reach ' + fmt(at.minCents) + ' on ' + label(at.minDay) + ', ' + until + '. ' + (at.okBefore ? 'Without this purchase it stays at $0.00 or above.' : 'It is already below $0.00 without this purchase.') });
    } else if (classification !== 'affordable' && /^fits_/.test(out.verdict)) {
      out.headlineFollowsPlan = true;
      const why = alreadyBelow
        ? 'The spending already planned in your budgets takes your balance to ' + fmt(plannedBeforeC.minCents) + ' on ' + label(plannedBeforeC.minDay) + ', below your ' + fmt(C) + ' cushion, even before this purchase.'
        : !budgetOk
          ? 'It would put you ' + fmt(out.budget.overByCents) + ' over the ' + fmt(out.budget.plannedCents) + ' a month you approved for ' + category + '.'
          : !plannedAfterC.okCushion
            ? 'Together with the spending already planned in your budgets' + (beforeRows.length ? ' and your savings contributions' : '') + ', your balance would sink to ' + fmt(plannedAfterC.minCents) + ' on ' + label(plannedAfterC.minDay) + ', below your ' + fmt(C) + ' cushion.' + (lim > 0 ? ' The most that fits today without a change is ' + fmt(lim) + '.' : '')
            : 'Together with your planned spending it would take ' + fmt(plannedAfterC.reserveShortByCents) + ' of the ' + fmt(RC) + ' you are keeping for after the term.' + (lim > 0 ? ' The most that fits today without a change is ' + fmt(lim) + '.' : ' Your approved budgets leave nothing extra today.');
      out.headline = classification === 'needs_changes' ? 'Only with a change to your plan' : 'Not with your current plan';
      out.summary = 'Your bills alone could absorb it. ' + why + (classification === 'needs_changes' ? ' One of the changes below makes room.' : ' Fix that first, or wait.');
      out.tone = classification === 'needs_changes' ? 'amber' : 'bad';
      const cl = L.find(l => l.id === 'cushion');
      if (cl && !plannedAfterC.okCushion) { cl.tone = 'amber'; cl.text = 'Counting only your bills, your ' + fmt(C) + ' cushion stays. Counting your planned spending too, the lowest point is ' + fmt(plannedAfterC.minCents) + ' on ' + label(plannedAfterC.minDay) + '.'; }
    }
    const classTone = classification === 'affordable' ? 'good' : classification === 'needs_changes' ? 'amber' : 'bad';
    const classText = classification === 'affordable'
      ? 'Against your full plan (planned spending, savings contributions, cushion and the money kept for after the term) this purchase fits in the cautious view. Nothing in your approved plan is changed.'
      : classification === 'needs_changes'
        ? 'It can fit only if you choose a change listed below. Nothing in your plan changes unless you accept one.'
        : todayFitC && !afterTermOk
          ? 'It fits your plan for this term, but not the weeks right after it: listed bills there would go unpaid. A purchase is only called affordable when those bills stay covered too.'
          : alreadyBelow
          ? 'Your plan is already below your ' + fmt(C) + ' cushion, so this purchase is not affordable and is not recommended. Fix the shortfall first.'
          : 'Even with less discretionary spending, paused savings contributions, a later deadline, or waiting until the end of the term, this purchase would threaten essentials or your protected cushion.';
    L.push({ id: 'classification', tone: classTone, title: 'Your full plan', text: classText });
    if (beforeRows.length) L.push({ id: 'goals-plan', tone: todayFitC ? 'blue' : 'amber', title: 'Your savings goals', text: todayFitC
      ? 'Existing savings contributions stay on the same schedule. Goal savings stay separate from discretionary spending and from your cushion.'
      : 'Keeping your current savings contributions with this purchase would not leave every day at or above your cushion. Goal savings are not discretionary money and are never taken from the cushion.' });
    // Alternatives cards already list restoring options — do not duplicate them under "What would help".
    if (!(alts.length && classification === 'needs_changes')) {
      for (const a of alts) if (a.available && a.restores) adv.push({ kind: a.kind, day: a.day, weeklyCents: a.weeklyCents, text: a.text, requiresExplicitChoice: a.requiresExplicitChoice });
    }
    return out;
  };

  /* ---------- logging a purchase without counting it twice ---------- */
  // Rows already in the ledger that the new purchase could be the same as: same amount, close in date, and either an identical entry the student
  // typed or a bank-file row. A true repeat purchase (two $5.45 coffees) is allowed, but only after the student says so.
  E.possibleDuplicates = function (plan, o, today) {
    const amt = Math.abs(Math.round(Number(o && o.amountCents)));
    if (!Number.isSafeInteger(amt) || amt <= 0) return [];
    const day = o.date ? D.parse(o.date) : today; if (day === null || day === undefined) return [];
    const matchedTargets = new Set(plan.transactions.filter(t => t.matchedTo).map(t => t.matchedTo));
    return E.activeTxs(plan).filter(t => t.flow === 'spend' && t.amountCents === -amt && Math.abs(dayOf(t) - day) <= 3 && !(t.source !== 'manual' && matchedTargets.has(t.id)))
      .map(t => ({ id: t.id, date: t.date, desc: t.desc, category: t.category, amountCents: t.amountCents, source: t.source, sameDay: dayOf(t) === day }));
  };
  // o: { amountCents, category?, desc?, date?, force? }. Without force, a possible duplicate comes back as { ok:false, needsConfirm:true, duplicates:[...] }.
  E.logPurchase = function (plan, o, today) {
    o = o || {};
    const base = E.addManualTx(plan, { amountCents: o.amountCents, category: o.category, desc: o.desc, date: o.date }, today);
    if (!base.ok) return base;           // invalid amount / date: the engine's own message
    const dups = E.possibleDuplicates(plan, { amountCents: o.amountCents, date: o.date || D.fmt(today) }, today);
    if (dups.length && !o.force) return { ok: false, needsConfirm: true, duplicates: dups, error: '', plan };
    return base;
  };
  // Only entries the student typed can be edited in every field. A row from a bank file keeps its amount and date (they came from the bank); its category can be corrected.
  E.editPurchase = function (plan, id, patch, today) {
    const t = plan.transactions.find(x => x.id === id);
    if (!t) return { ok: false, error: 'That purchase no longer exists.', plan };
    const p = {};
    if (patch.category !== undefined) p.category = patch.category;
    if (t.source === 'manual') {
      if (patch.amountCents !== undefined) { const a = Math.abs(Math.round(Number(patch.amountCents))); if (!Number.isSafeInteger(a) || a <= 0) return { ok: false, error: 'Enter an amount above $0.', plan }; p.amountCents = t.amountCents < 0 ? -a : a; }
      if (patch.date !== undefined) { const d = D.parse(patch.date); if (d === null) return { ok: false, error: 'That date is not valid.', plan }; if (typeof today === 'number' && d > today) return { ok: false, error: 'Purchases can only be logged for today or earlier.', plan }; p.date = patch.date; }
      if (patch.desc !== undefined) p.desc = patch.desc;
    }
    return E.editTx(plan, id, p);
  };
  // Manual purchases only (bank rows are not deleted from here).
  E.removePurchase = function (plan, id) {
    const t = plan.transactions.find(x => x.id === id);
    if (!t) return { ok: false, error: 'That purchase no longer exists.', plan };
    if (t.source !== 'manual') return { ok: false, error: 'That row came from your bank file. Delete it from your import instead.', plan };
    return E.deleteTx(plan, id);
  };

  /* ---------- a typed purchase that may also be in the bank file ---------- */
  // Unlinked pairs the import could not be sure about (or that were logged after the file was imported). Nothing is counted twice while they are open:
  // the engine counts the typed purchase and the bank row, so the student is asked.
  E.manualMatchSuggestions = function (plan) {
    const dismissed = new Set(plan.dismissed || []), taken = new Set(plan.transactions.filter(t => t.matchedTo).map(t => t.matchedTo));
    const manual = plan.transactions.filter(t => t.source === 'manual' && !t.matchedTo && t.flow === 'spend' && t.account === 'checking');
    const bank = plan.transactions.filter(t => t.source !== 'manual' && !t.matchedTo && t.flow === 'spend' && t.account === 'checking' && !taken.has(t.id));
    const out = [], used = new Set();
    for (const m of manual) {
      let best = null;
      for (const b of bank) {
        if (used.has(b.id) || b.amountCents !== m.amountCents || dismissed.has('dupe:' + m.id + ':' + b.id)) continue;
        const gap = Math.abs(dayOf(m) - dayOf(b)); if (gap > 5) continue;
        if (!best || gap < best.gap) best = { b, gap };
      }
      if (best) { used.add(best.b.id); out.push({ manualId: m.id, importId: best.b.id, gapDays: best.gap, manual: { date: m.date, desc: m.desc, category: m.category, amountCents: m.amountCents }, bank: { date: best.b.date, desc: best.b.desc, category: best.b.category, amountCents: best.b.amountCents } }); }
    }
    return out;
  };
  // same:true links them (the typed purchase is hidden so only the bank row counts); same:false remembers "these are different" and stops asking.
  E.decideDuplicate = function (plan, manualId, importId, same) {
    if (same) {
      if (!plan.transactions.some(t => t.id === manualId) || !plan.transactions.some(t => t.id === importId)) return { ok: false, error: 'One of those rows no longer exists.', plan };
      const p = E.linkManual(plan, manualId, importId), b = p.transactions.find(t => t.id === importId), m = p.transactions.find(t => t.id === manualId);
      if (b && m && m.locked && m.category && !b.locked) { b.category = m.category; b.locked = true; }      // the student's own category choice survives
      return { ok: true, plan: p };
    }
    return E.dismissKey(plan, 'dupe:' + manualId + ':' + importId);
  };

  /* ---------- tiny, bounded "don't ask again" memory ---------- */
  // Keys are short strings. The list never grows past 80 entries (the oldest are dropped), because the plan normaliser keeps only the first 100.
  E.dismissKey = function (plan, key) {
    const p = E.clone(plan), k = E.safeStr(key, 60);
    if (!k) return { ok: false, plan };
    p.dismissed = (p.dismissed || []).filter(x => x !== k).concat([k]).slice(-80);
    return { ok: true, plan: p };
  };
})(CCE);

;
/* ===== engine/12-today.js ===== */
/* =========================================================================
   12 today — everything the Today screen shows, from ONE snapshot of the existing model
   -------------------------------------------------------------------------
   STAGE 3. This module only READS the plan. It calls the same forecast / capacity / trust functions every other
   screen uses, so Today, the first-plan summary and the purchase checker can never disagree.

   What the screen shows, and the one idea each number carries (these must never be presented as interchangeable):
     pace         sustainable money per day, spread to the end of the term      "how much per day can I keep spending?"
     budget       the student's OWN approved monthly category numbers           "what did I tell myself I'd spend?"
     one purchase the most one payment can be right now                          (see E.purchaseCheck)
     reserved     held back on purpose (bills, essentials, cushion, optional reserve)
     estimated    assumptions that real data will later replace (never written to the ledger)
   Nested windows: today <= week <= month <= semester, always, because each is a sum of the same daily pace over a longer window.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D, fmt = E.fmt, label = D.label;
  const dayOf = t => D.parse(t.date);
  E.CHECKIN_NUDGE_DAYS = 7;           // a gentle weekly prompt. The app already calls a balance "not recently verified" after settings.staleDays.
  const plural = (n, w) => n + ' ' + w + (n === 1 ? '' : 's');

  /* ---------- balance check-ins ---------- */
  E.checkInStatus = function (plan, T) {
    const asOf = D.parse(plan.account.asOf), stale = asOf === null ? 0 : Math.max(0, T - asOf), last = (plan.checkIns || [])[(plan.checkIns || []).length - 1] || null;
    const level = stale >= plan.settings.staleDays ? 'overdue' : stale >= E.CHECKIN_NUDGE_DAYS ? 'due' : 'fresh';
    return {
      asOf: plan.account.asOf, asOfDay: asOf, staleDays: stale, level, due: level !== 'fresh', balanceCents: plan.account.balanceCents,
      last: last ? { date: last.date, actualCents: last.actualCents, projectedCents: last.projectedCents, diffCents: last.actualCents - last.projectedCents } : null,
      neverCheckedIn: !last
    };
  };
  // What has been recorded, assumed and estimated since the balance the student last verified. Every line says which kind of number it is.
  E.sinceLastCheckIn = function (plan, T, fc) {
    const A0 = D.parse(plan.account.asOf); if (A0 === null) return { ok: false, lines: [] };
    fc = fc || E.forecast(plan, { today: T, scenario: 'expected', flex: 'none' });
    const seq = plan.account.seq, rec = E.cashTxs(plan).filter(t => { const d = dayOf(t); return d <= T && (d > A0 || (d === A0 && t.source === 'manual' && t.seq > seq)); });
    const spend = rec.filter(t => t.flow === 'spend' || t.flow === 'card_payment'), inc = rec.filter(t => t.amountCents > 0 && (t.flow === 'income' || t.flow === 'aid'));
    const spendCents = E.sum(spend, t => -t.amountCents), incCents = E.sum(inc, t => t.amountCents), comp = fc && fc.ok ? fc.open.components : null;
    const lines = [];
    if (spend.length) lines.push({ kind: 'recorded', label: 'Spending you logged or imported (' + plural(spend.length, 'purchase') + ')', cents: -spendCents });
    if (inc.length) lines.push({ kind: 'recorded', label: 'Money that arrived (' + plural(inc.length, 'deposit') + ')', cents: incCents });
    if (comp) {
      if (comp.assumedBillsCents) lines.push({ kind: 'assumed', label: 'Bills we assume were paid', cents: -comp.assumedBillsCents });
      if (comp.assumedIncomeCents) lines.push({ kind: 'assumed', label: 'Paychecks or aid we assume arrived', cents: comp.assumedIncomeCents });
      if (comp.assumedSavingsCents) lines.push({ kind: 'assumed', label: 'Savings transfers we assume were made', cents: -comp.assumedSavingsCents });
      if (comp.unloggedSpendingCents) lines.push({ kind: 'estimated', label: 'Everyday spending we estimate you did not log', cents: -comp.unloggedSpendingCents });
    }
    return { ok: true, sinceDay: A0, days: Math.max(0, T - A0), lines, recordedSpendCents: spendCents, recordedIncomeCents: incCents, count: rec.length, modelledBalanceCents: fc && fc.ok ? fc.open.cents : null };
  };

  /* ---------- recent purchases (for logging, correcting, deleting) ---------- */
  E.recentSpending = function (plan, T, n) {
    const rows = E.activeTxs(plan).filter(t => (t.flow === 'spend' || t.flow === 'refund') && dayOf(t) <= T)
      .sort((a, b) => dayOf(b) - dayOf(a) || b.seq - a.seq).slice(0, n || 8);
    return rows.map(t => ({ id: t.id, date: t.date, desc: t.desc, category: t.category, amountCents: Math.abs(t.amountCents), flow: t.flow, source: t.source, account: t.account, manual: t.source === 'manual', daysAgo: T - dayOf(t) }));
  };

  /* ---------- what is coming up ---------- */
  const NATURE = {
    confirmed: { label: 'Confirmed', note: 'You verified the amount and date.' },
    scheduled: { label: 'Scheduled', note: 'Set for a known date, but not guaranteed until it arrives.' },
    expected: { label: 'Expected', note: 'Based on a pattern or a rough number, not verified.' },
    uncertain: { label: 'Uncertain', note: 'You were not sure about this, so it is not counted.' }
  };
  E.NATURE = NATURE;
  E.natureOf = natureOf;
  function natureOf(o, item) {
    if (o.type === 'detected') return 'expected';
    if (!item) return 'expected';
    if (item.reliability === 'uncertain') return 'uncertain';
    if (o.type === 'savings') return 'confirmed';
    if (o.type === 'bill') return item.verified && item.source !== 'estimated' ? 'confirmed' : 'expected';
    if (item.irregular || item.lowCents != null || !item.verified || item.source === 'estimated') return 'expected';
    return 'scheduled';
  }
  const STATE_TEXT = {
    received: 'Received', paid: 'Paid', assumed_received: 'We assume this arrived. Did it?', assumed_paid: 'We assume this was paid. Did it go out?', unconfirmed: 'Dated on the day of your last balance check. Has it happened?',
    overdue: 'You said it is not paid yet', awaiting: 'Still waiting for it', due_today: 'Due today', match_unconfirmed: 'A deposit may be this', unconfirmed_deposit: 'Not counted until you confirm it arrived', scheduled: 'Coming up', not_counted: 'Not counted'
  };
  // days: how far ahead to look (default 14). Rows still needing an answer are always included, however old.
  E.upcomingEvents = function (plan, T, snap, opts) {
    opts = opts || {}; const days = opts.days || 14, fcE = snap.expected.fc, fcC = snap.cautious.fc, cap = snap.cautious.capacity, lim = cap.pace.limitedBy;
    const cmap = {}; for (const o of fcC.occurrences) cmap[o.type + '|' + o.id + '|' + o.nominal] = o;
    const mq = {}; for (const q of fcC.matchQuestions || []) mq[q.incomeId + '|' + q.nominal] = q;
    const rows = [], seen = new Set();
    const build = o => {
      const item = o.type === 'income' ? plan.incomes.find(x => x.id === o.id) : o.type === 'bill' ? plan.obligations.find(x => x.id === o.id) : o.type === 'savings' ? plan.goals.find(x => x.id === o.id) : null;
      const cm = cmap[o.type + '|' + o.id + '|' + o.nominal], income = o.type === 'income', sign = income ? 1 : -1;
      const needsAnswer = ['assumed_received', 'assumed_paid', 'unconfirmed', 'overdue', 'awaiting'].indexOf(o.status) >= 0 || (o.status === 'unconfirmed_deposit');
      const nature = o.status === 'received' || o.status === 'paid' ? 'confirmed' : natureOf(o, item);
      const cautiousAmt = cm ? cm.amountCents : o.amountCents, cautiousDay = cm ? cm.day : o.day;
      let note = '';
      if (income && cautiousAmt !== o.amountCents) note = 'Counted at ' + fmt(cautiousAmt) + ' in the cautious view.';
      if (income && cautiousDay > o.day && !note) note = 'Counted ' + plural(cautiousDay - o.day, 'day') + ' late in the cautious view.';
      else if (income && cautiousDay > o.day) note += ' Arrives ' + plural(cautiousDay - o.day, 'day') + ' late in that view.';
      if (cm && cm.status === 'unconfirmed_deposit') note = 'The cautious view does not count it until you confirm it arrived.';
      const q = mq[o.id + '|' + o.nominal];
      return {
        key: o.type + '|' + o.id + '|' + D.fmt(o.nominal), type: o.type, kind: o.kind, id: o.id, name: o.name, nominal: o.nominal, day: o.day, dayLabel: label(o.day), daysAway: o.day - T,
        amountCents: sign * o.amountCents, cautiousAmountCents: sign * cautiousAmt, cautiousDay, status: o.status, state: STATE_TEXT[o.status] || '', nature, natureLabel: NATURE[nature].label, natureNote: NATURE[nature].note, note,
        done: o.status === 'received' || o.status === 'paid', needsAnswer, canResolve: !!item && o.type !== 'detected', resolveKind: o.type === 'detected' ? null : o.type, detectedKey: o.type === 'detected' && String(o.id).indexOf('det:') === 0 ? String(o.id).slice(4) : '',
        matchQuestion: q ? { txId: q.txId, txDesc: q.txDesc, txCents: q.txCents } : null, limiting: !!(lim && lim.kind === 'bill' && lim.label === o.name && lim.day === o.day), irregular: !!(item && item.irregular), source: item ? item.source : 'detected'
      };
    };
    for (const o of fcE.occurrences) {
      const open = (o.group === 'assumed' || o.group === 'unpaid') && o.nominal <= T, windowed = o.nominal >= T - 3 && o.nominal <= T + days;
      if (!open && !windowed) continue;
      if (o.group === 'paid' && o.nominal < T - 3) continue;
      const r = build(o); seen.add(r.key); rows.push(r);
    }
    // the bill that limits today's pace is always shown, even if it is further than two weeks away
    if (lim && lim.kind === 'bill' && lim.day - T > days && lim.day - T <= 60) {
      const o = fcE.occurrences.find(x => x.name === lim.label && x.day === lim.day && x.kind !== 'income');
      if (o) { const r = build(o); if (!seen.has(r.key)) { r.pinned = true; rows.push(r); } }
    }
    for (const u of fcC.uncounted) {
      if (u.day < T || u.day > T + days || u.reason === 'unconfirmed_deposit') continue;
      const income = u.type === 'income';
      rows.push({ key: 'uncounted|' + u.id + '|' + D.fmt(u.day), type: u.type, kind: income ? 'income' : 'bill', id: u.id, name: u.name, nominal: u.day, day: u.day, dayLabel: label(u.day), daysAway: u.day - T, amountCents: (income ? 1 : -1) * u.amountCents, cautiousAmountCents: 0, status: 'not_counted', state: STATE_TEXT.not_counted,
        nature: 'uncertain', natureLabel: NATURE.uncertain.label, natureNote: NATURE.uncertain.note, note: income ? 'Left out of both views until you say you can count on it.' : 'Found in your transactions with low confidence; left out of the expected view.', done: false, needsAnswer: false, canResolve: false, resolveKind: null, detectedKey: '', matchQuestion: null, limiting: false, irregular: false, source: 'detected' });
    }
    rows.sort((a, b) => a.day - b.day || (a.amountCents < b.amountCents ? 1 : -1) || (a.name < b.name ? -1 : 1));
    const future = rows.filter(r => !r.done && r.daysAway >= 0 && r.status !== 'not_counted');
    const nextIncome = future.find(r => r.amountCents > 0 && r.nature !== 'uncertain') || null, nextBill = future.find(r => r.amountCents < 0) || null;
    const pinnedOutside = rows.some(r => (r.pinned || r.limiting) && r.daysAway > days);
    const subtitle = pinnedOutside
      ? 'The next ' + days + ' days, plus bills that limit your daily pace (even if they fall later).'
      : 'The next ' + days + ' days';
    return {
      rows, days, subtitle, pinnedOutside, nextIncome, nextBill, needAnswer: rows.filter(r => r.needsAnswer).length,
      billsInWindowCents: E.sum(future.filter(r => r.amountCents < 0 && r.daysAway <= days), r => -r.amountCents), incomeInWindowCents: E.sum(future.filter(r => r.amountCents > 0 && r.daysAway <= days && r.nature !== 'uncertain'), r => r.cautiousAmountCents)
    };
  };

  /* ---------- approved-budget cash flow vs cushion (same planned forecast the purchase checker uses) ---------- */
  // shortfallCents = max(0, cushion − minimum projected balance) on the cautious flex:'budget' timeline.
  E.planHealth = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    if (!snap || !snap.ok || !snap.cautious.planned || !snap.cautious.planned.ok) return { ok: false, error: 'no_plan' };
    const C = plan.account.cushionCents, days = snap.cautious.planned.days;
    let minCents = Infinity, minDay = null;
    for (const d of days) if (d.bal < minCents) { minCents = d.bal; minDay = d.day; }
    const shortfallCents = Math.max(0, C - minCents), okCushion = shortfallCents === 0;
    const paceCents = snap.cautious.capacity && snap.cautious.capacity.ok ? snap.cautious.capacity.todayLimit.allowanceCents : 0;
    return {
      ok: true, cushionCents: C, minCents, minDay, shortfallCents, okCushion,
      summary: okCushion
        ? 'Spending your approved budgets in full still keeps every day at or above your ' + fmt(C) + ' cushion (lowest ' + fmt(minCents) + ' on ' + label(minDay) + ').'
        : 'If you spend every approved budget in full, your lowest balance is ' + fmt(minCents) + ' on ' + label(minDay) + ', which is ' + fmt(shortfallCents) + ' below your ' + fmt(C) + ' cushion. The daily pace (' + fmt(paceCents) + ') is still cushion-safe only if you spend at that pace—not if you spend the full approved budgets.'
    };
  };

  /* ---------- semester room with after-term need called out (reserve stays opt-in) ---------- */
  // Capacity already subtracts any earmarked winter reserve from remainingCents. Gross = remaining + applied (before that earmark).
  E.semesterRoomSplit = function (cap, so) {
    const remainingAfterReserveCents = cap.semester.remainingCents;
    const needCents = so && so.ok ? so.needsBetweenTermsCents : 0;
    const appliedCents = so && so.ok ? so.appliedReserveCents : 0, gapCents = so && so.ok ? so.gapCents : 0;
    const grossCents = remainingAfterReserveCents + appliedCents;
    const afterTermProtected = gapCents === 0;
    // Residual after funding the still-uncovered after-term gap from remaining room (never below $0). Not "safe" unless safeLabelOk.
    const unprotectedSpendCents = Math.max(0, remainingAfterReserveCents - gapCents);
    return {
      grossCents, remainingAfterReserveCents, needCents, appliedCents, gapCents, afterTermProtected, unprotectedSpendCents,
      // Filled by todayView / semesterView once planHealth is known: 0 unless cushion-OK and after-term protected.
      safeToSpendCents: 0, safeLabelOk: false
    };
  };

  /* ---------- is the semester plan on track? ---------- */
  E.semesterStatus = function (plan, T, snap, so, health) {
    const cap = snap.cautious.capacity, capE = snap.expected.capacity, fc = cap.fc, end = label(cap.endDay), C = plan.account.cushionCents, m = fc.metrics;
    health = health || E.planHealth(plan, T, snap);
    const split = E.semesterRoomSplit(cap, so);
    const facts = []; let status = 'on_track', headline = 'On track for ' + end, detail = '';
    const room = split.remainingAfterReserveCents, roomE = capE && capE.ok ? capE.semester.remainingCents : null;
    const gap = split.gapCents, applied = split.appliedCents, R = cap.reserve.totalCents;
    if (!cap.safe) {
      status = 'off_track'; headline = 'Off track: bills and essentials use up your cushion';
      detail = 'Even before any spending money, your balance drops ' + fmt(cap.shortfall.maxCents) + ' below your ' + fmt(C) + ' cushion' + (cap.shortfall.firstDay ? ' around ' + label(cap.shortfall.firstDay) : '') + '. Check whether income is missing from your plan, or whether a bill is entered wrongly.';
    } else if (health.ok && !health.okCushion) {
      status = 'watch'; headline = 'Watch: approved budgets spend past your cushion';
      detail = health.summary + (gap > 0 ? ' After the term you still need about ' + fmt(gap) + ' that is not earmarked yet.' : applied > 0 ? ' A winter reserve is earmarked in your plan, but that does not fix the budget shortfall.' : '');
    } else if (cap.month.remainingCents < 0) {
      status = 'watch'; headline = 'Watch this month: you are past the room your plan supports';
      detail = 'You have recorded ' + fmt(-cap.month.remainingCents) + ' more flexible spending this month than the plan supports. Your cushion is safe, but the days ahead have less room.';
    } else if (gap > 0) {
      status = 'watch'; headline = 'On track this term, but after-term bills are not fully earmarked';
      detail = 'Your bills stay covered through ' + end + ' if you spend about your daily pace, but about ' + fmt(gap) + ' of bills and essentials after the term is not protected yet. That money is not safe to treat as disposable.';
    } else if (roomE !== null && roomE > 0 && room < roomE * 0.5 && roomE - room >= 5000) {
      status = 'watch'; headline = 'On track, but it depends on income arriving';
      detail = 'If your pay and aid arrive as hoped you have ' + fmt(roomE) + ' of room. In the cautious view you have ' + fmt(room) + '. Plan with the cautious number.';
    } else detail = 'Your bills stay covered and your ' + fmt(C) + ' cushion stays intact through ' + end + ' in the cautious view, if you spend about your daily pace' + (health.ok && health.okCushion ? ', and your approved budgets also stay at or above the cushion' : '') + '.';
    facts.push({ id: 'room', label: 'Gross room through ' + end + ' (before winter reserve)', value: fmt(split.grossCents), note: 'Commitments view (bills and essentials held back)' + (roomE !== null && roomE !== room ? '. If everything arrives as hoped: ' + fmt(roomE + applied) : '') });
    if (applied > 0) facts.push({ id: 'earmarked', label: 'Winter reserve earmarked in your plan', value: fmt(applied), note: 'Earmarked here only — not moved to another account, and not guaranteed to remain unused if you overspend' });
    if (applied > 0) facts.push({ id: 'remaining', label: 'Remaining room after the reserve', value: fmt(room), note: 'What is left on the commitments timeline after the earmark' });
    if (gap > 0 || (so && so.ok && so.needsBetweenTermsCents > 0)) {
      facts.push({ id: 'after', label: 'Unfunded winter / after-term need', value: fmt(gap > 0 ? gap : 0), note: gap > 0 ? (fmt(split.needCents) + ' needed; ' + fmt(gap) + ' still uncovered — not safe disposable cash') : 'Covered by the amount earmarked in your plan' });
      facts.push({ id: 'protected', label: 'Room after protecting after-term need', value: fmt(split.unprotectedSpendCents), note: gap > 0 ? 'Math residual after covering the unfunded gap from remaining room — not labeled safe while budgets or the gap fail' : 'After-term need is already covered' });
    }
    const safeOk = !!(health.ok && health.okCushion && split.afterTermProtected && cap.safe);
    facts.push({ id: 'safe', label: 'Safe to spend under the current plan', value: fmt(safeOk ? split.unprotectedSpendCents : 0), note: safeOk ? 'Approved-budget cash flow and after-term needs are both protected' : (health.ok && !health.okCushion ? 'Not safe: approved budgets already use the cushion' : gap > 0 ? 'Not safe: after-term need is not fully earmarked' : 'Not safe under the current plan') });
    // Commitments-only balances (flex:'none') — not the same as spending at the daily pace or full budgets.
    facts.push({ id: 'low', label: 'Lowest balance (commitments only)', value: fmt(m.minCents), note: 'Bills and essentials held back; no discretionary spending. On ' + label(m.minDay) });
    facts.push({ id: 'end', label: 'Balance on ' + end + ' (commitments only)', value: fmt(m.endCents), note: 'Before discretionary spending' });
    facts.push({ id: 'pace_end', label: 'End balance if you spend at recommended daily pace', value: fmt(C + R), note: 'Following the pace uses flexible room by term end while keeping every day at or above your cushion' + (R ? ' (cushion plus earmarked after-term reserve)' : ' (your cushion)') + '.' });
    if (health.ok && !health.okCushion) facts.push({ id: 'budgets', label: 'Lowest if you spend every approved budget', value: fmt(health.minCents), note: fmt(health.shortfallCents) + ' below your cushion on ' + label(health.minDay) });
    else if (health.ok && health.okCushion) facts.push({ id: 'budgets', label: 'Lowest if you spend every approved budget', value: fmt(health.minCents), note: 'Stays at or above your cushion on ' + label(health.minDay) });
    const dates = so && so.ok ? (so.dates || E.planDateContext(plan, T, so)) : E.planDateContext(plan, T, so);
    const afterTerm = so && so.ok ? { needCents: so.needsBetweenTermsCents, appliedCents: so.appliedReserveCents, gapCents: so.gapCents, recommend: so.recommend, summary: so.summary, endedBy: so.bridge ? so.bridge.endedBy : '', untilDay: so.bridge ? so.bridge.endDay : null, aidName: so.bridge ? so.bridge.aidName : '', aidDay: so.bridge ? so.bridge.aidDay : null, aidScheduledDay: dates.aidScheduledDay, bridgeStartDay: dates.bridgeStartDay, bridgeEndDay: dates.bridgeEndDay, bridgeRangeLabel: dates.bridgeRangeLabel, aidLabel: dates.aidLabel } : null;
    return { status, headline, detail, facts, endDay: cap.endDay, endLabel: end, daysLeft: cap.endDay - T, provisional: fc.horizon.provisional, periodName: fc.horizon.period, afterTerm, planHealth: health, roomSplit: split, dates };
  };

  /* ---------- why the daily pace changes later in the term ---------- */
  // The pace you see today is the FIRST step of a staircase. Later steps appear when money arrives and nothing else is due before the term ends. They are not extra cash.
  E.paceOutlook = function (plan, T, snap, so) {
    const cap = snap.cautious.capacity, fc = cap.fc, segs = cap.pace.segments || [], now = cap.todayLimit.allowanceCents;
    const steps = [];
    for (let i = 1; i < segs.length; i++) {
      const prev = segs[i - 1], seg = segs[i], from = prev.throughDay + 1, rate = Math.floor(seg.ratePerDayCents);
      let cause = null;
      for (const e of fc.events) if (e.type === 'income' && e.amountCents > 0 && e.day > prev.throughDay && e.day <= seg.throughDay && (!cause || e.amountCents > cause.amountCents)) cause = e;
      const last = seg.throughDay >= cap.endDay;
      const dependsOn = cause ? { kind: 'income', name: cause.name, day: cause.day, amountCents: cause.amountCents, itype: cause.itype || '', certain: !!(cause.verified && cause.reliability === 'certain') } : { kind: last ? 'end' : 'none', name: '', day: last ? cap.endDay : from, amountCents: 0, itype: '', certain: true };
      steps.push({ fromDay: from, throughDay: seg.throughDay, rateCents: rate, isLast: last, dependsOn, caution: !!(cause && !dependsOn.certain) });
    }
    const big = steps.find(s => s.rateCents >= Math.max(now * 1.5, now + 500)) || null;
    const need = so && so.ok ? so.needsBetweenTermsCents : 0, applied = so && so.ok ? so.appliedReserveCents : 0;
    let ifSetAside = null, ifPartial = null;
    if (so && so.ok && so.recommend && !so.reserveEnabled) {
      const r = E.setReserve(plan, { bridge: true });
      if (r.ok) { const c2 = capOf(r.plan, T); if (c2) ifSetAside = { paceCents: c2.todayLimit.allowanceCents, roomCents: c2.semester.allowanceCents, reserveCents: c2.reserve.totalCents }; }
      // if setting ALL of it aside would nearly or completely use up the pace, offer a realistic first step instead (half of today's term room, in whole $5 steps)
      if (ifSetAside && (ifSetAside.paceCents < now * 0.5)) {
        const part = Math.floor(cap.semester.allowanceCents * 0.5 / 500) * 500;
        if (part >= 500 && part < need) {
          const r2 = E.setReserve(plan, { fixedCents: part }), c3 = r2.ok ? capOf(r2.plan, T) : null;
          if (c3) ifPartial = { fixedCents: part, paceCents: c3.todayLimit.allowanceCents, roomCents: c3.semester.allowanceCents };
        }
      }
    }
    let explanation = '';
    if (big) {
      explanation = 'Your pace is ' + fmt(now) + ' a day now. It steps up to about ' + fmt(big.rateCents) + ' a day from ' + label(big.fromDay) + (big.dependsOn.kind === 'income' ? ', after ' + big.dependsOn.name + ' (' + fmt(big.dependsOn.amountCents) + ') arrives on ' + label(big.dependsOn.day) : ', because nothing else is due before the term ends') + '. That higher rate is the same semester room, spread over fewer days after the tight stretch—not extra cash you can spend ahead of time.';
      if (big.isLast && need > 0) explanation += ' That later room exists mostly because the term ends before the next round of rent and bills' + (so.bridge && so.bridge.aidDay ? ' (and before your next refund on ' + label(so.bridge.aidDay) + ')' : '') + '. You will still need about ' + fmt(need) + ' after the term, so it is not free cash.';
      else if (big.caution) explanation += ' It depends on that money actually arriving, so do not spend ahead of it.';
    }
    if (ifPartial && now > 0) {
      explanation += (explanation ? ' ' : '') + 'Setting aside only ' + fmt(ifPartial.fixedCents) + ' for after the term may change today\'s pace only a little (to about ' + fmt(ifPartial.paceCents) + '), because today\'s pace is often limited by a near-term bill, while a partial reserve mainly uses room that appears later.';
    }
    return { nowCents: now, first: segs.length ? { throughDay: segs[0].throughDay, rateCents: Math.floor(segs[0].ratePerDayCents) } : null, steps, big, needAfterTermCents: need, appliedReserveCents: applied, gapCents: so && so.ok ? so.gapCents : 0, ifSetAside, ifPartial, explanation, recommendReserve: !!(so && so.ok && so.recommend && !so.reserveEnabled) };
  };

  /* ---------- "what would help?" (hypothetical; nothing is applied) ---------- */
  function capOf(plan, T) {
    const det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det), c = E.capacity(plan, { today: T, scenario: 'cautious', det, base });
    return c.ok ? c : null;
  }
  E.improvementIdeas = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    const cap = snap.cautious.capacity, base0 = cap.todayLimit.allowanceCents, room0 = cap.semester.allowanceCents, ideas = [];
    const push = (id, title, detail, p2, extra) => { const c = capOf(p2, T); if (!c) return; const gain = c.todayLimit.allowanceCents - base0; if (gain >= 10) ideas.push(Object.assign({ id, title, detail, paceBeforeCents: base0, paceAfterCents: c.todayLimit.allowanceCents, gainCents: gain, roomGainCents: c.semester.allowanceCents - room0 }, extra || {})); };
    // 1. steadier pay: the cautious view counts irregular pay at its lowest recent amount. What if it held at the usual amount?
    for (const inc of plan.incomes) {
      if (!inc.schedule || inc.reliability === 'uncertain' || inc.amountCents <= 0) continue;
      const lowC = E.cautiousIncomeCents(plan, inc);
      if (lowC >= inc.amountCents) continue;
      const p2 = E.clone(plan), i2 = p2.incomes.find(x => x.id === inc.id); i2.irregular = false; i2.lowCents = null; if (i2.source === 'estimated') { i2.source = 'user'; i2.verified = true; }
      push('steady-' + inc.id, 'If ' + inc.name + ' held at its usual amount', 'The cautious view counts ' + fmt(lowC) + ' per payment (' + E.cautiousReason(plan, inc) + '). Your usual is ' + fmt(inc.amountCents) + '. Steadier or guaranteed hours is the biggest lever you have.', E.normalizePlan(p2).plan, { kind: 'income' });
    }
    // 2. the pricier subscription
    const subs = plan.obligations.filter(o => o.category === 'Subscriptions' && o.schedule && o.amountCents > 0).sort((a, b) => b.amountCents - a.amountCents);
    if (subs.length) {
      const o = subs[0], a = E.applyChange(plan, { type: 'cancelObligation', id: o.id, today: T });
      push('cancel-' + o.id, 'Cancel ' + o.name, 'It costs ' + fmt(o.amountCents) + ' ' + (o.schedule.freq === 'monthly' ? 'a month' : 'each time') + '.', a.plan, { kind: 'bill' });
    }
    // 3. a little less on the biggest essential estimate
    const ess = E.effectiveBudgets(plan, T, snap.base).filter(b => b.kind === 'essential' && b.monthlyCents >= 4000).sort((a, b) => b.monthlyCents - a.monthlyCents);
    if (ess.length) {
      const c = ess[0], a = E.applyChange(plan, { type: 'cutBudget', category: c.category, weeklyCents: -1000, today: T });
      push('trim-' + c.category, 'Spend $10 a week less on ' + c.category.toLowerCase(), 'Your plan sets aside ' + fmt(c.monthlyCents) + ' a month for it. Essentials are reserved before any spending money is shown, so a smaller estimate frees room.', a.plan, { kind: 'budget' });
    }
    return ideas.sort((a, b) => b.gainCents - a.gainCents).slice(0, 3);
  };

  // Why do the cautious and expected numbers differ, and what practical changes would close the gap? Only computed when they do differ.
  E.scenarioExplain = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    const c = snap.cautious.capacity, x = snap.expected.capacity;
    const out = { differs: false, cautiousPaceCents: c.todayLimit.allowanceCents, expectedPaceCents: x && x.ok ? x.todayLimit.allowanceCents : c.todayLimit.allowanceCents, cautiousRoomCents: c.semester.allowanceCents, expectedRoomCents: x && x.ok ? x.semester.allowanceCents : c.semester.allowanceCents, drivers: [], ideas: [] };
    out.differs = Math.abs(out.expectedPaceCents - out.cautiousPaceCents) >= 25 || Math.abs(out.expectedRoomCents - out.cautiousRoomCents) >= 500;
    if (!out.differs) return out;
    const tr = E.incomeTreatment(plan, T);
    if (tr.ok) for (const r of tr.rows) {
      if (!r.cautious.counted) continue;
      const parts = [];
      if (r.cautious.amountCents < r.expected.amountCents) parts.push('counts ' + fmt(r.cautious.amountCents) + ' per payment instead of the usual ' + fmt(r.expected.amountCents) + ' (' + r.cautious.reason + ')');
      if (r.cautious.delayDays > r.expected.delayDays) parts.push('assumes it arrives ' + plural(r.cautious.delayDays - r.expected.delayDays, 'day') + ' late');
      if (parts.length) out.drivers.push({ id: r.id, name: r.name, text: 'The cautious view ' + parts.join(' and ') + '.' + (r.impact && r.impact.paceCents > 0 ? ' This income is worth about ' + fmt(r.impact.paceCents) + ' a day of your pace.' : '') });
    }
    out.ideas = E.improvementIdeas(plan, T, snap);
    return out;
  };

  /* ---------- the ONE recommendation ---------- */
  const recKey = (id, T) => 'rec:' + id + ':' + D.fmt(T);
  E.isRecDismissed = (plan, id, T) => (plan.dismissed || []).indexOf(recKey(id, T)) >= 0;
  E.dismissRecommendation = function (plan, id, T) {
    const r = E.dismissKey(plan, recKey(id, T));
    if (!r.ok) return r;
    // keep today's keys and yesterday's only
    const keep = new Set([D.fmt(T), D.fmt(T - 1)]); r.plan.dismissed = r.plan.dismissed.filter(k => k.indexOf('rec:') !== 0 || keep.has(k.slice(k.lastIndexOf(':') + 1)));
    return r;
  };
  // Candidates are ranked by how much they matter to THIS student's money today. Each carries the evidence it is built on and the explicit actions the
  // student may take. None of them is ever applied without a tap.
  E.todayRecommendations = function (plan, T, snap, ctx) {
    ctx = ctx || {};
    const cap = snap.cautious.capacity, fcC = snap.cautious.fc, base = snap.base, trust = ctx.trust || E.trust(plan, T, snap), up = ctx.upcoming, so = ctx.so, outlook = ctx.outlook, cands = [];
    const health = ctx.health || E.planHealth(plan, T, snap), roomSplit = ctx.roomSplit || E.semesterRoomSplit(cap, so);
    const add = r => cands.push(r);
    // 0. an answer is blocking the daily number
    if (!trust.showAllowance && trust.missing.length) {
      const q = trust.missing[0];
      add({ id: 'needs_answer', priority: 99, tone: 'amber', title: 'One answer unlocks your daily amount', body: q.question + ' ' + q.why, evidence: ['No daily amount is shown until this is answered, because it would quietly leave something out.'], actions: [{ id: 'answer', label: 'Answer this', kind: 'primary', op: { type: 'goto', screen: 'needs' } }], dismissible: false });
    }
    // 0b. approved budgets already break the cushion — never present unrestricted positive spend advice beside this
    if (health.ok && !health.okCushion && !cap.shortfall.exists) {
      const gap = roomSplit && roomSplit.gapCents > 0 ? roomSplit.gapCents : 0;
      const actions = [{ id: 'budgets', label: 'Review budgets', kind: 'primary', op: { type: 'goto', screen: 'budgets' } }, { id: 'check', label: 'Can I afford this?', kind: 'ghost', op: { type: 'goto', screen: 'today' } }];
      // Keep after-term reserve reachable (and honestly explained) when this card outranks the reserve recommendation.
      let winterNote = '';
      if (so && so.ok && so.recommend && !so.reserveEnabled) {
        const part = outlook && outlook.ifPartial, full = outlook && outlook.ifSetAside, now = cap.todayLimit.allowanceCents;
        const unrealistic = !!(full && full.paceCents < now * 0.5);
        const brk = plan.periods.find(p => p.kind !== 'semester' && D.parse(p.start) >= cap.endDay && D.parse(p.start) - cap.endDay <= 3);
        const where = brk ? brk.name.toLowerCase() : 'the weeks after the term';
        if (unrealistic && part) {
          actions.unshift({ id: 'reserve_part', label: 'Set aside ' + fmt(part.fixedCents) + ' to start', kind: 'primary', op: { type: 'reserveFixed', fixedCents: part.fixedCents, needCents: so.needsBetweenTermsCents } });
          winterNote = ' ' + where.charAt(0).toUpperCase() + where.slice(1) + ' will cost about ' + fmt(so.needsBetweenTermsCents) + ', more than this term leaves room for. Setting all of it aside now would take your daily pace from ' + fmt(now) + ' to ' + fmt(full.paceCents) + ', so it is not realistic from this term\'s room alone.';
        } else {
          actions.unshift({ id: 'reserve', label: 'Set aside ' + fmt(so.needsBetweenTermsCents), kind: 'primary', op: { type: 'reserve' } });
        }
      }
      add({
        id: 'budgets_break_cushion', priority: 86, tone: 'amber',
        title: 'Approved budgets reach ' + fmt(health.minCents) + ' on ' + label(health.minDay),
        body: health.summary + (gap > 0 ? ' After the term, about ' + fmt(gap) + ' is still not set aside.' : '') + winterNote + ' Campus Compass will not change budgets or turn on a reserve unless you choose to. Until then, treat the daily pace as the sustainable path, and use "Can I afford this?" before a purchase.',
        evidence: ['Lowest under approved budgets: ' + fmt(health.minCents) + ' on ' + label(health.minDay), 'Shortfall below cushion: ' + fmt(health.shortfallCents), 'Daily pace (if followed): ' + fmt(cap.todayLimit.allowanceCents)].concat(gap > 0 ? ['After-term need not set aside: ' + fmt(gap)] : []),
        actions, dismissible: true
      });
    }
    // 1. bills already exceed money
    if (cap.shortfall.exists) {
      const lim = cap.pace.limitedBy;
      add({ id: 'shortfall', priority: 100, tone: 'bad', title: 'Your bills are bigger than your money on ' + label(cap.shortfall.firstDay), body: 'Before any spending money, your balance would fall about ' + fmt(cap.shortfall.maxCents) + ' below your cushion' + (lim && lim.label ? ', mostly because of ' + lim.label : '') + '. That is why today\'s pace is $0.00.',
        evidence: ['Balance today: ' + fmt(plan.account.balanceCents), 'Cushion you keep: ' + fmt(plan.account.cushionCents), 'First day short: ' + label(cap.shortfall.firstDay)], actions: [{ id: 'income', label: 'Check my income', kind: 'primary', op: { type: 'goto', screen: 'optional', open: 'income' } }, { id: 'bills', label: 'Check my bills', kind: 'ghost', op: { type: 'goto', screen: 'optional', open: 'bills' } }], dismissible: false });
    }
    // 2. a paycheck or aid payment that should have arrived has no matching deposit
    const missing = fcC.occurrences.filter(o => o.kind === 'income' && o.nominal <= T && ['unconfirmed_deposit', 'awaiting', 'assumed_received'].indexOf(o.status) >= 0).sort((a, b) => b.nominal - a.nominal);
    if (missing.length) {
      const o = missing[0], inc = plan.incomes.find(x => x.id === o.id);
      add({ id: 'paycheck_unconfirmed', priority: 95, tone: 'amber', title: 'Did your ' + label(o.nominal) + ' ' + o.name + ' arrive?', body: 'We expected about ' + fmt(inc ? inc.amountCents : o.amountCents) + ' on ' + label(o.nominal) + ' but have no matching deposit' + (o.status === 'unconfirmed_deposit' ? ', so the cautious view is not counting it' : o.status === 'awaiting' ? ', and you told us it had not arrived yet' : '') + '.',
        evidence: ['Scheduled ' + label(o.nominal) + ', not matched to a deposit in your transactions', 'Counted in the expected view only while it is unconfirmed'], actions: [{ id: 'arrived', label: 'Yes, it arrived', kind: 'primary', op: { type: 'resolve', kind: 'income', id: o.id, nominal: D.fmt(o.nominal), status: 'paid', amountCents: inc ? inc.amountCents : o.amountCents } }, { id: 'notyet', label: 'Not yet', kind: 'ghost', op: { type: 'resolve', kind: 'income', id: o.id, nominal: D.fmt(o.nominal), status: 'unpaid' } }], dismissible: true });
    }
    // 3. a deposit that might be a scheduled paycheck
    if ((fcC.matchQuestions || []).length) {
      const q = fcC.matchQuestions[0];
      add({ id: 'deposit_match', priority: 90, tone: 'blue', title: 'Is this deposit your ' + q.name + '?', body: 'A ' + fmt(q.txCents) + ' deposit on ' + label(D.parse(q.txDate)) + ' ("' + q.txDesc + '") might be the ' + fmt(q.expectedCents) + ' paycheck we expected. Until you say, it is counted once, as the deposit.', evidence: ['Same neighbourhood of dates and amounts, but the description does not settle it'],
        actions: [{ id: 'same', label: 'Yes, same paycheck', kind: 'primary', op: { type: 'match', incomeId: q.incomeId, nominal: D.fmt(q.nominal), txId: q.txId, decision: 'same' } }, { id: 'diff', label: 'No, different money', kind: 'ghost', op: { type: 'match', incomeId: q.incomeId, nominal: D.fmt(q.nominal), txId: q.txId, decision: 'different' } }], dismissible: true });
    }
    // 4. a large bill lands before the next paycheck
    if (up && !cap.shortfall.exists) {
      const bill = up.rows.find(r => r.amountCents <= -10000 && r.daysAway >= 0 && r.daysAway <= 10 && r.status !== 'not_counted' && !r.done);
      if (bill) {
        const nextIn = up.rows.find(r => r.amountCents > 0 && r.day > T && r.nature !== 'uncertain' && !r.done && r.status !== 'not_counted');
        const before = !nextIn || nextIn.cautiousDay > bill.day;
        if (before) {
          const k = Math.min(fcC.N, Math.max(0, bill.day - T)), balAfter = fcC.days[k].bal;
          add({ id: 'bill_before_income', priority: 85, tone: 'amber', title: bill.name + ' (' + fmt(-bill.amountCents) + ') is due ' + (bill.daysAway === 0 ? 'today' : bill.daysAway === 1 ? 'tomorrow' : label(bill.day)) + (nextIn ? ', ' + plural(Math.max(1, nextIn.cautiousDay - bill.day), 'day') + ' before your next money in' : ', with no money in sight before it'),
            body: 'Your projected balance on ' + label(bill.day) + ' is about ' + fmt(balAfter) + ' (cautious view, after everyday essentials). That is why your daily pace is held to ' + fmt(cap.todayLimit.allowanceCents) + ' until it is paid.' + (nextIn ? ' Next money in: ' + nextIn.name + ' on ' + label(nextIn.cautiousDay) + '.' : ''),
            evidence: ['Balance today: ' + fmt(plan.account.balanceCents), bill.name + ': ' + fmt(-bill.amountCents) + ' on ' + label(bill.day), nextIn ? 'Next money in: ' + nextIn.name + ', ' + label(nextIn.cautiousDay) + ' (' + fmt(nextIn.cautiousAmountCents) + ' in the cautious view)' : 'No income scheduled before it'], actions: [], dismissible: true });
        }
      }
    }
    // 5. this week's discretionary spending is unusually high
    {
      let top = null; const from = T - 6;
      for (const c of Object.keys(base.categories)) {
        const h = base.categories[c]; if (h.kind !== 'flexible' || h.usualCount < 3) continue;
        const rows = E.activeTxs(plan).filter(t => t.category === c && t.flow === 'spend' && dayOf(t) >= from && dayOf(t) <= T && !E.obligationLike(plan, t));
        const spent = E.sum(rows, t => -t.amountCents), usual = h.weeklyCents;
        if (rows.length >= 2 && spent >= 4000 && spent >= Math.max(usual * 2, usual + 3000) && (!top || spent - usual > top.spent - top.usual)) top = { c, spent, usual, n: rows.length };
      }
      if (top) add({ id: 'unusual_' + top.c.replace(/\W/g, ''), priority: 80, tone: 'amber', title: top.c + ' is running high this week', body: 'You have recorded ' + fmt(top.spent) + ' on ' + top.c.toLowerCase() + ' in the last 7 days (' + plural(top.n, 'purchase') + '). Your usual is about ' + fmt(top.usual) + ' a week.', evidence: [fmt(top.spent) + ' in the last 7 days', 'Usual: ' + fmt(top.usual) + ' a week, from your own history'], actions: [], dismissible: true });
    }
    // 6. money to keep for the weeks after the term
    if (so && so.ok && so.recommend && !so.reserveEnabled) {
      const left = cap.endDay - T, brk = plan.periods.find(p => p.kind !== 'semester' && D.parse(p.start) >= cap.endDay && D.parse(p.start) - cap.endDay <= 3), where = brk ? brk.name.toLowerCase() : 'the weeks after the term';
      const items = so.bridge && so.bridge.items ? so.bridge.items.slice().sort((a, b) => b.amountCents - a.amountCents).slice(0, 3) : [];
      const ev = items.map(i => i.name + ': ' + fmt(i.amountCents) + ' on ' + label(i.day));
      ev.push('Next refund: ' + (so.bridge && so.bridge.endedBy === 'aid' ? so.bridge.aidName + ', ' + label(so.bridge.aidDay) : 'none scheduled'));
      const until = so.bridge && so.bridge.endedBy === 'aid' ? 'your next refund (' + label(so.bridge.aidDay) + ')' : 'the ' + (so.bridge ? so.bridge.days : 0) + '-day limit (no refund is scheduled)';
      const full = outlook && outlook.ifSetAside, part = outlook && outlook.ifPartial, now = cap.todayLimit.allowanceCents;
      const unrealistic = !!(full && full.paceCents < now * 0.5);
      const actions = [];
      if (unrealistic) {
        if (part) actions.push({ id: 'reserve_part', label: 'Set aside ' + fmt(part.fixedCents) + ' to start', kind: 'primary', op: { type: 'reserveFixed', fixedCents: part.fixedCents, needCents: so.needsBetweenTermsCents } });
      } else actions.push({ id: 'reserve', label: 'Set aside ' + fmt(so.needsBetweenTermsCents), kind: 'primary', op: { type: 'reserve' } });
      add({ id: 'reserve', priority: left <= 21 ? 92 : 70, tone: unrealistic ? 'amber' : 'blue', title: unrealistic ? where.charAt(0).toUpperCase() + where.slice(1) + ' will cost about ' + fmt(so.needsBetweenTermsCents) + ', more than this term leaves room for' : 'Set money aside for ' + where,
        body: 'After ' + label(cap.endDay) + ' you still need about ' + fmt(so.needsBetweenTermsCents) + ' of bills and essentials until ' + until + '. ' + (unrealistic ? 'Setting all of it aside now would take your daily pace from ' + fmt(now) + ' to ' + fmt(full.paceCents) + ', so it is not realistic from this term\'s room alone.' + (part ? ' Starting with ' + fmt(part.fixedCents) + ' would change your pace to ' + fmt(part.paceCents) + '. That covers only part of it: about ' + fmt(Math.max(0, so.needsBetweenTermsCents - part.fixedCents)) + ' would still be uncovered, so it may not fully cover your between-term expenses.' : '') + ' Extra income, a lower bill or help from family are the other ways to close the gap.' : full ? 'Setting it aside now would change your daily pace from ' + fmt(now) + ' to ' + fmt(full.paceCents) + '.' : 'It is not set aside right now.'),
        evidence: ev, actions, dismissible: true });
    }
    // 7. thin evidence
    if (trust.showAllowance && (base.status === 'provisional' || base.status === 'limited') && base.coverageDays > 0) {
      add({ id: 'thin_history', priority: trust.level === 'provisional' ? 75 : 60, tone: 'blue', title: 'Only ' + plural(base.coverageDays, 'day') + ' of history so far', body: 'Your daily pace rests on very little evidence, so it is labelled provisional and counted from today forward only. A month or two of real transactions would replace the guesses.', evidence: [plural(base.txCount, 'purchase') + ' over ' + plural(base.coverageDays, 'day'), 'Estimates for ' + (trust.estimates.filter(e => e.evidence === 'thin').map(e => e.category).join(', ') || 'your categories') + ' are rough'], actions: [{ id: 'import', label: 'Add more bank history', kind: 'primary', op: { type: 'goto', screen: 'import' } }], dismissible: true });
    }
    // 8. subscriptions worth a look
    {
      const subs = plan.obligations.filter(o => o.category === 'Subscriptions' && o.schedule && o.amountCents > 0).concat(snap.det.filter(r => !r.ignored && !r.matched && r.category === 'Subscriptions' && r.flow === 'spend').map(r => ({ name: r.name, amountCents: r.amountCents, schedule: r.schedule, detected: true, id: 'det:' + r.key })));
      const monthly = E.sum(subs, s => E.monthlyEquivalent(s.schedule, s.amountCents));
      if (subs.length >= 2 && monthly >= 2000) {
        const big = subs.slice().sort((a, b) => b.amountCents - a.amountCents)[0];
        add({ id: 'subscriptions', priority: 50, tone: 'blue', title: 'Your subscriptions add up to ' + fmt(monthly) + ' a month', body: subs.map(s => s.name + ' ' + fmt(s.amountCents)).join(', ') + '. If you dropped ' + big.name + ' (' + fmt(big.amountCents) + ') it would add about ' + fmt(big.amountCents * Math.max(1, Math.floor((cap.endDay - T) / 30))) + ' of room by the end of the term.', evidence: subs.map(s => s.name + (s.detected ? ' (found in your transactions)' : '') + ': ' + fmt(s.amountCents)), actions: [], dismissible: true });
      }
    }
    // 9. a savings goal that needs attention (E.goalStatus: confirmed progress and real transfer dates, never a calendar-month guess)
    {
      const st = ctx.goals || E.goalStatus(plan, T, { fc: snap.cautious && snap.cautious.fc });
      for (const r of st.goals) {
        if (r.goalStatus !== 'active' || r.reached || !(r.needCents > 0) || r.dueDay === null || r.dueDay <= T || r.onTrack) continue;
        const perMonth = r.required ? r.required.monthlyCents : Math.round(r.needCents / Math.max(1, (r.dueDay - T) / 30.4375));
        const conflict = st.conflicts.find(c => c.laterId === r.goalId);
        add({ id: 'goal_' + r.goalId, priority: r.urgent ? 55 : 40, tone: r.urgent ? 'amber' : 'blue', title: r.name + ' needs ' + fmt(perMonth) + ' a month',
          body: 'To reach ' + fmt(r.targetCents) + ' by ' + label(r.dueDay) + ' you would need ' + (r.required ? fmt(r.required.perContributionCents) + ' per transfer (' + fmt(perMonth) + ' a month)' : 'about ' + fmt(perMonth) + ' a month') + (r.currentContributionCents ? ', and your plan sets aside ' + fmt(r.currentContributionCents) + ' per transfer' : ', and nothing is set aside yet') + '.' + (conflict ? ' ' + conflict.text : ''),
          evidence: ['Saved so far: ' + fmt(r.confirmedCents), 'Still needed: ' + fmt(r.needCents)].concat(r.urgent ? ['Due in ' + r.daysLeft + ' day' + (r.daysLeft === 1 ? '' : 's')] : []),
          actions: [{ id: 'goals', label: 'Open goals', kind: 'primary', op: { type: 'goto', screen: 'goals' } }], dismissible: true });
      }
    }
    // 10. nothing is wrong: say so, specifically
    {
      const w = cap.week, m = cap.month;
      add({ id: 'on_pace', priority: 10, tone: 'good', title: w.spentCents <= w.allowanceCents ? 'You are on pace' : 'You are a little over this week', body: w.spentCents <= w.allowanceCents ? 'You have recorded ' + fmt(w.spentCents) + ' of this week\'s ' + fmt(w.allowanceCents) + ' and ' + fmt(m.spentCents) + ' of this month\'s ' + fmt(m.allowanceCents) + '. Nothing needs fixing. You never have to log everything: a quick balance check-in keeps the picture honest.' : 'You have recorded ' + fmt(w.spentCents) + ' against this week\'s ' + fmt(w.allowanceCents) + '. A lighter few days brings you back.', evidence: [], actions: [], dismissible: false });
    }
    const live = cands.filter(r => !r.dismissible || !E.isRecDismissed(plan, r.id, T)).sort((a, b) => b.priority - a.priority);
    return { top: live[0] || null, others: Math.max(0, live.length - 1), all: live };
  };

  /* ---------- the whole Today screen, in one call ---------- */
  E.todayView = function (plan, T) {
    const snap = E.snapshot(plan, T);
    if (!snap || !snap.ok) return { ok: false, error: 'no_balance', today: T };
    const trust = E.trust(plan, T, snap), cap = snap.cautious.capacity, capE = snap.expected.capacity, fc = cap.fc, C = plan.account.cushionCents;
    const so = E.safetyOutlook(plan, { today: T, scenario: 'cautious', fc, base: snap.base, det: snap.det, reserve: cap.reserve });
    const health = E.planHealth(plan, T, snap);
    const roomSplit = E.semesterRoomSplit(cap, so);
    roomSplit.safeLabelOk = !!(health.ok && health.okCushion && roomSplit.afterTermProtected && cap.safe);
    roomSplit.safeToSpendCents = roomSplit.safeLabelOk ? roomSplit.unprotectedSpendCents : 0;
    const tm = E.paceFromTomorrow(cap), shown = trust.showAllowance;
    const expOk = capE && capE.ok;
    const budgetsBreak = !!(health.ok && !health.okCushion);
    const dates = so.dates || E.planDateContext(plan, T, so);
    const conditionalPace = !!(shown && roomSplit.safeToSpendCents === 0);
    const paceReason = conditionalPace
      ? (budgetsBreak ? 'Safe to spend is $0.00 because approved budgets already use the cushion.'
        : roomSplit.gapCents > 0 ? 'Safe to spend is $0.00 because after-term need is not fully earmarked.'
          : 'Safe to spend is $0.00 under the current plan.')
      : '';
    // Commitments pace/one-time stay as calculated; they are never marketed as "safe under approved budgets" when budgets break the cushion.
    const pace = {
      shown, level: trust.level, badge: trust.badge, label: conditionalPace ? 'Conditional daily pace' : trust.allowanceLabel, summary: trust.summary, labels: trust.labels,
      allowanceCents: cap.todayLimit.allowanceCents, spentTodayCents: cap.todayLimit.spentCents, remainingTodayCents: cap.todayLimit.remainingCents, over: cap.todayLimit.remainingCents < 0,
      expectedAllowanceCents: expOk ? capE.todayLimit.allowanceCents : null, expectedRemainingTodayCents: expOk ? capE.todayLimit.remainingCents : null, differs: expOk && Math.abs(capE.todayLimit.allowanceCents - cap.todayLimit.allowanceCents) >= 25,
      tomorrowCents: tm.cents, oneTimeCents: cap.immediate.cents, oneTimeExpectedCents: expOk ? capE.immediate.cents : null, oneTimeLimitedBy: cap.immediate.limitedBy, safe: cap.safe, shortfall: cap.shortfall, limitedBy: cap.pace.limitedBy, meaning: cap.pace.meaning, cushionCents: C, endDay: cap.endDay,
      question: trust.missing[0] || null, missingCount: trust.missing.length, hidden: shown ? '' : trust.wording.summary,
      budgetsBreakCushion: budgetsBreak, recommendSpend: !!(shown && cap.safe && !budgetsBreak && roomSplit.afterTermProtected),
      conditionalPace, paceReason,
      paceCondition: conditionalPace
        ? 'Conditional daily pace: cushion-safe on the bills-and-essentials timeline if you follow it, but not labeled safe to spend under the current plan.'
        : 'Daily pace holds bills, essentials and your cushion if you spend about this much each day—not if you spend every approved budget dollar.',
      oneTimeCondition: budgetsBreak
        ? 'This one-time amount is cushion-safe only on the bills-and-essentials timeline. Under your current approved budgets the plan already goes below the cushion, so it is not recommended as affordable.'
        : (cap.immediate.cents > Math.max(0, cap.month.remainingCents)
          ? 'A one-time purchase up to this amount can exceed this month\'s pace room—it borrows from later days in the term. It is not a daily amount.'
          : 'A single payment up to this amount still leaves the commitments forecast at or above your cushion through the term end.'),
      glossary: [
        { id: 'pace', title: conditionalPace ? 'Conditional daily pace' : 'Daily pace', text: conditionalPace ? 'Follow-this-pace amount on the commitments timeline. It is conditional because safe-to-spend under the current plan is $0.' : 'Sustainable flexible spending per day if you follow the pace (bills, essentials and cushion held back).' },
        { id: 'month', title: 'Spendable this month', text: 'The smaller of approved budget remaining and pace room left in this calendar month.' },
        { id: 'one', title: 'One-time capacity', text: 'Largest single payment that keeps the commitments forecast at or above your cushion—not permission to spend full budgets.' },
        { id: 'sem', title: 'Semester room', text: 'Gross flexible room is before any winter reserve earmark. Remaining room is after that earmark. A positive residual is not “safe to spend” unless approved budgets and after-term needs both clear.' }
      ]
    };
    const rowsFlex = snap.budgetStatus.filter(r => r.kind === 'flexible'), approved = rowsFlex.filter(r => r.basis === 'approved');
    const plannedC = E.sum(approved, r => r.plannedCents), spentC = E.sum(approved, r => r.spentCents), budRem = plannedC - spentC, planRem = cap.month.remainingCents;
    const budget = {
      hasApproved: approved.length > 0, plannedCents: plannedC, spentCents: spentC, remainingCents: budRem, planRemainingCents: planRem,
      spendableCents: Math.max(0, approved.length ? Math.min(budRem, planRem) : planRem), limitedBy: !approved.length ? 'plan' : budRem <= planRem ? 'budget' : 'plan',
      categories: approved.map(r => ({ category: r.category, plannedCents: r.plannedCents, spentCents: r.spentCents, remainingCents: r.remainingCents, status: r.status })),
      unbudgetedSpentCents: E.sum(rowsFlex.filter(r => r.basis !== 'approved'), r => r.spentCents),
      note: 'Your monthly budgets are your own targets, not cash. What you can actually spend is the smaller of your budget and the room your bills and income leave.' + (budgetsBreak ? ' Right now those targets spend past your cushion if used in full—change them only when you choose to.' : ''),
      sustainableUnderBudgets: !budgetsBreak
    };
    const sum = (k, n) => { let s = 0; for (let i = 0; i <= Math.min(n, fc.N); i++) s += fc.days[i][k]; return s; };
    const comp = fc.open.components;
    const reserved = { cushionCents: C, billsToTermEndCents: sum('obl', fc.N), essentialsToTermEndCents: sum('ess', fc.N), savingsToTermEndCents: sum('sav', fc.N), endOfTermReserveCents: cap.reserve.totalCents, billsNext14Cents: sum('obl', 13), essentialsNext14Cents: sum('ess', 13) };
    const estimated = { unloggedSpendingCents: comp.unloggedSpendingCents, unloggedBy: comp.unloggedBy, assumedBillsCents: comp.assumedBillsCents, assumedIncomeCents: comp.assumedIncomeCents, sinceDay: D.parse(plan.account.asOf), thinCategories: trust.estimates.filter(e => e.evidence === 'thin').map(e => e.category) };
    estimated.any = estimated.unloggedSpendingCents > 0 || estimated.assumedBillsCents > 0 || estimated.thinCategories.length > 0;
    const progress = {
      today: { allowanceCents: cap.todayLimit.allowanceCents, spentCents: cap.todayLimit.spentCents, remainingCents: cap.todayLimit.remainingCents },
      week: { startDay: cap.week.startDay, endDay: cap.week.endDay, allowanceCents: cap.week.allowanceCents, spentCents: cap.week.spentCents, remainingCents: cap.week.remainingCents },
      month: { startDay: cap.month.startDay, endDay: cap.month.endDay, allowanceCents: cap.month.allowanceCents, spentCents: cap.month.spentCents, remainingCents: cap.month.remainingCents },
      semester: { endDay: cap.endDay, allowanceCents: cap.semester.allowanceCents, remainingCents: cap.semester.remainingCents, split: roomSplit },
      budget, reserved, estimated, planHealth: health, roomSplit
    };
    const upcoming = E.upcomingEvents(plan, T, snap), status = E.semesterStatus(plan, T, snap, so, health), outlook = E.paceOutlook(plan, T, snap, so);
    const goals = E.goalStatus(plan, T, { fc: snap.cautious.fc });
    const rec = E.todayRecommendations(plan, T, snap, { trust, upcoming, so, outlook, goals, health, roomSplit });
    const checkIn = E.checkInStatus(plan, T);
    checkIn.since = E.sinceLastCheckIn(plan, T, snap.expected.fc);
    const irregular = plan.incomes.some(i => i.irregular && i.reliability !== 'uncertain');
    const thinData = shown && (trust.level === 'provisional' || snap.base.status === 'provisional' || snap.base.status === 'limited');
    const mode = !shown ? 'needs_answer' : irregular || pace.differs ? 'variable' : thinData ? 'thin' : 'steady';
    return {
      ok: true, today: T, name: plan.meta.name, mode, thinData, trust: { level: trust.level, badge: trust.badge, showAllowance: shown, labels: trust.labels, reasons: trust.reasons, questions: trust.questions, missing: trust.missing },
      pace, progress, upcoming, status, outlook, goals, planHealth: health, roomSplit, dates,
      // The most one purchase can be today under the whole plan (same test as Can I afford this?). roomSplit.safeToSpendCents is the room before approved budgets draw from it.
      purchaseLimit: shown ? E.purchaseLimit(plan, T, { snap }) : { ok: false, maxCents: 0 },
      scenario: pace.differs && shown ? E.scenarioExplain(plan, T, snap) : { differs: false, drivers: [], ideas: [] }, recommendation: rec, checkIn, recent: E.recentSpending(plan, T, 8), duplicates: E.manualMatchSuggestions(plan),
      semesterEndDay: cap.endDay, snapshotNote: 'All numbers come from the same forecast the plan summary and the purchase checker use. Semester numbers use ' + dates.semesterRangeLabel + (dates.bridgeRangeLabel ? '; the after-term safety outlook uses ' + dates.bridgeRangeLabel + (dates.aidLabel ? ' (' + dates.aidLabel + ')' : '') : '') + '.'
    };
  };

  /* ---------- Finley's one next action (rule-based; every sentence comes from engine outputs already on the screens) ---------- */
  E.finleyAdvice = function (plan, T, opts) {
    opts = opts || {};
    const screen = opts.screen || 'today';
    const fmt = E.fmt, label = D.label;
    const out = (text, action) => ({ text, action: action || null });
    if (!plan || !plan.account || !plan.account.asOf) {
      return out('Set your checking balance first so I can work from a real number.', { label: 'Enter it', screen: 'basics' });
    }
    const tv = opts.tv || null;
    const standing = opts.standing || null;
    const breakdown = opts.breakdown || null;
    const status = opts.status || (tv && tv.goals) || null;
    const alloc = opts.alloc || null;

    if (tv && !tv.pace.shown && tv.pace.question) {
      return out('Answer this first: ' + tv.pace.question.question + ' A daily number would leave something out until you do.', { label: 'Answer this', screen: 'needs' });
    }
    if (tv && tv.checkIn && tv.checkIn.due) {
      return out('A quick balance check-in keeps the picture honest. You do not have to log every purchase.', { label: 'Check in', screen: 'today', focus: 'ci-h' });
    }
    if (tv && tv.recommendation && tv.recommendation.top && tv.recommendation.top.priority >= 90) {
      const r = tv.recommendation.top;
      const first = r.body ? r.body.split('. ')[0] + '.' : 'That is the one thing to handle next.';
      return out(r.title + '. ' + first, { label: 'See this on Today', screen: 'today' });
    }
    if (tv && tv.upcoming && tv.upcoming.rows) {
      const due = tv.upcoming.rows.find(e => e.canResolve && !e.done && (e.needsAnswer || e.daysAway <= 0));
      if (due) {
        const arrived = due.amountCents > 0;
        return out((arrived ? 'Did ' : 'Was ') + due.name + (arrived ? ' arrive' : ' paid') + '? Mark it if it happened so the forecast stays honest.', { label: 'Open Today', screen: 'today', focus: 'up-h' });
      }
    }
    if (tv && tv.pace && tv.pace.shown && tv.pace.safe === false) {
      return out('Your listed bills and essentials already use up your cushion in the cautious view. Look at the semester picture before spending.', { label: 'Open Semester', screen: 'semester' });
    }

    const goals = status && status.goals ? status.goals.filter(g => g.goalStatus === 'active') : [];
    if (screen === 'goals' && alloc && alloc.ok) {
      if (alloc.recommended && alloc.changesNeeded) {
        return out('I have a savings split that stays at or above your cushion. You decide whether to use it.', { label: 'Review the split', screen: 'goals', focus: 'alloc-h' });
      }
      if (alloc.summary.unreachable.length) {
        const g = alloc.goals.find(x => x.status === 'unreachable');
        return out((g ? '"' + g.name + '"' : 'A goal') + ' cannot be funded on time with this plan. Compare the alternatives. Nothing changes until you pick one.', { label: 'See alternatives', screen: 'goals', focus: 'gl-h' });
      }
      if (alloc.summary.needsChanges.length) {
        const g = alloc.goals.find(x => x.status === 'needs_changes');
        return out((g ? '"' + g.name + '"' : 'A goal') + ' needs a change to fit. Open the alternatives. I will not pick one for you.', { label: 'See alternatives', screen: 'goals', focus: 'gl-h' });
      }
      if (!alloc.safe) return out('Your forecast already dips below your cushion, so I will not call a savings plan feasible until that is fixed.', { label: 'Open Today', screen: 'today' });
    }
    const behind = goals.find(g => !g.onTrack && g.needCents > 0);
    if (behind) {
      const due = behind.dueDay != null ? ' by ' + label(behind.dueDay) : '';
      if (screen === 'goals') {
        return out('"' + behind.name + '" still needs ' + fmt(behind.needCents) + due + '. I only count savings you have confirmed.', alloc && alloc.ok ? { label: 'Review the split', screen: 'goals', focus: 'alloc-h' } : null);
      }
      return out('"' + behind.name + '" still needs ' + fmt(behind.needCents) + due + '. Open Goals when you want to decide.', { label: 'Open goals', screen: 'goals' });
    }

    if (screen === 'semester' && standing && standing.status === 'needs_info') {
      return out('A missing answer is holding the semester picture back. Handle that first.', { label: 'Open Today', screen: 'today' });
    }
    if (screen === 'semester' && standing && standing.status !== 'on_track') {
      return out(standing.headline + ' Look at one change below. Nothing is applied until you choose it.', { label: 'See ideas', screen: 'semester', focus: 'rc-h' });
    }
    if (screen === 'semester' && breakdown && breakdown.history && breakdown.history.incompleteWeeks) {
      return out('Some earlier weeks have incomplete history. I show what is on record and I do not invent past balances.', { label: 'See the weeks', screen: 'semester', focus: 'bd-h' });
    }

    if (tv && tv.thinData) {
      return out('These numbers rest on very little history, so they are careful starting points. A bank file would replace the guesses.', { label: 'Add bank history', screen: 'import' });
    }

    if (goals.length && goals.every(g => g.onTrack || g.reached)) {
      return out('"' + goals[0].name + '" is on track. I only count savings you have confirmed, never a transfer that was only scheduled.', screen === 'goals' ? null : { label: 'Open goals', screen: 'goals' });
    }

    if (screen === 'semester') return out('This is the term picture. Check a week when you want the detail.', { label: 'See cash flow', screen: 'semester', focus: 'bd-h' });
    if (screen === 'goals') return out('You are in charge of these goals. Pause, edit or complete them whenever you want.', null);
    return out('Check a purchase before you make it. I will not change your plan unless you say so.', { label: 'Can I afford this?', screen: 'today', focus: 'chk-h' });
  };
})(CCE);

;
/* ===== engine/13-semester.js ===== */
/* =========================================================================
   13 semester — the Semester planning view (Stage 4)
   -------------------------------------------------------------------------
   Everything here is built from the SAME calls that power the Today screen: E.snapshot (forecast + capacity), E.trust,
   E.safetyOutlook and E.paceOutlook. This file adds presentation-level questions on top of them (is the semester on track?
   where are the pressure points? what does a stress test do? which adjustment would fix a shortfall, verified by re-running the
   forecast?) and never re-implements the forecast itself.
   Rules that hold for every function below:
     * pure: the engine never reads the clock (`T` is passed in) and a plan passed in is never modified (clones only);
     * stress tests and recommendations are HYPOTHETICAL. A recommendation changes the student's plan only through
       E.applyRecommendation, which the UI calls only when the student presses the button that says so;
     * money is integer cents and dates are integer day numbers.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D, fmt = E.fmt, label = D.label;
  const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const monthLabel = key => MONTHS[parseInt(key.slice(5), 10) - 1] + ' ' + key.slice(0, 4);
  const plural = (n, w) => n + ' ' + w + (n === 1 ? '' : 's');
  const DAYS_PER_MONTH = 30.4375;
  const fail = (plan, error) => ({ ok: false, error, plan });
  const mk = m => ({ endCents: m.endCents, minCents: m.minCents, minDay: m.minDay, firstBelowCushionDay: m.firstBelowCushionDay, firstNegativeDay: m.firstNegativeDay, shortfallCents: m.shortfallCents, belowZeroCents: m.belowZeroCents });

  /* ---------- calendar: which period are we planning, and where does the student stand in it? ---------- */
  E.termContext = function (plan, T) {
    const per = plan.periods.slice().sort((a, b) => D.parse(a.start) - D.parse(b.start));
    const hz = E.horizonInfo(plan, T);
    const inside = per.find(p => D.parse(p.start) <= T && T <= D.parse(p.end)) || null;
    const selected = per.find(p => p.name === hz.period && p.kind === 'semester') || null;
    let phase = 'no_calendar';
    if (per.length) phase = inside ? (inside.kind === 'semester' ? 'in_term' : 'on_break') : T < D.parse(per[0].start) ? 'before_terms' : T > D.parse(per[per.length - 1].end) ? 'after_terms' : 'between_terms';
    const options = per.filter(p => p.kind === 'semester' && D.parse(p.end) >= T).map(p => ({ id: p.id, name: p.name, start: p.start, end: p.end, verified: !!p.verified, selected: !!selected && selected.id === p.id, label: 'Through the end of ' + p.name }));
    const H = hz.endDay;
    const nextBreak = per.find(p => p.kind !== 'semester' && D.parse(p.start) > H - 1 && D.parse(p.start) - H <= 3) || null;
    const nextSemester = per.find(p => p.kind === 'semester' && D.parse(p.start) > H) || null;
    let note = '';
    if (phase === 'on_break') note = 'You are between terms (' + inside.name + '). The forecast below runs to the end of ' + (hz.period || 'the next term') + '.';
    else if (phase === 'before_terms') note = 'Your first term has not started yet. The forecast runs to the end of ' + (hz.period || 'the next term') + '.';
    else if (phase === 'after_terms' || phase === 'no_calendar') note = 'No semester dates cover this period, so the forecast uses a default length of ' + plural(plan.settings.defaultHorizonDays, 'day') + '. Confirm your semester dates to make it exact.';
    return { phase, inside, selected, period: selected, periodName: hz.period || '', options, horizon: hz, provisional: hz.provisional, startDay: selected ? D.parse(selected.start) : null, endDay: H, nextBreak, nextSemester, note };
  };

  // The student chooses which term (or the whole school year) the semester view runs to. Returns a new plan.
  E.setPlanningPeriod = function (plan, T, id) {
    const per = plan.periods.find(p => p.id === id);
    if (!per || per.kind !== 'semester') return fail(plan, 'Choose one of your semesters.');
    if (D.parse(per.end) < T) return fail(plan, 'That semester has already ended.');
    const p = E.clone(plan); p.horizon = Object.assign({}, p.horizon, { endPeriodId: id });
    return { ok: true, plan: E.normalizePlan(p).plan };
  };

  /* ---------- one-time planned expenses (tuition, textbooks, a trip) ---------- */
  E.PLANNED_CATEGORIES = [
    { category: 'Tuition & fees', label: 'Tuition or fees', essential: true }, { category: 'School supplies', label: 'Textbooks and supplies', essential: true },
    { category: 'Travel', label: 'A trip', essential: false }, { category: 'Health', label: 'Medical or dental', essential: true }, { category: 'Other', label: 'Something else', essential: false }
  ];
  E.addPlannedExpense = function (plan, o) {
    o = o || {};
    const cat = E.PLANNED_CATEGORIES.find(c => c.category === o.category);
    if (!cat) return fail(plan, 'Choose what kind of expense it is.');
    const name = E.safeStr(o.name, 60);
    if (!name) return fail(plan, 'Give it a short name, like "Chemistry textbook".');
    const amt = Math.round(Number(o.amountCents));
    if (!Number.isSafeInteger(amt) || amt <= 0 || amt > 5e7) return fail(plan, 'Enter an amount above $0.');
    const day = D.parse(o.date);
    if (day === null) return fail(plan, 'Pick a date.');
    const anchor = D.parse(plan.account.asOf);
    if (anchor !== null && day <= anchor) return fail(plan, 'Pick a date after ' + label(anchor) + ', the day of your last balance check. Anything earlier is already inside your balance.');
    if (plan.obligations.length >= 200) return fail(plan, 'That is the most expenses this plan can hold.');
    const p = E.clone(plan), id = E.newId(p, 'ob', new Set(p.obligations.map(x => x.id)));
    p.obligations.push({ id, name, category: cat.category, kind: cat.category === 'Tuition & fees' ? 'tuition' : 'oneTime', schedule: { freq: 'once', anchor: D.fmt(day) }, amountCents: amt, highCents: null, essential: !!o.essential, source: 'user', verified: true, reliability: 'certain', vendorKey: '', note: '' });
    return { ok: true, plan: E.normalizePlan(p).plan, id };
  };
  E.removePlannedExpense = function (plan, id) {
    const ob = plan.obligations.find(x => x.id === id);
    if (!ob || !ob.schedule || ob.schedule.freq !== 'once') return fail(plan, 'That one-time expense no longer exists.');
    const p = E.clone(plan); p.obligations = p.obligations.filter(x => x.id !== id);
    return { ok: true, plan: p };
  };
  E.plannedExpenses = function (plan, T) {
    return plan.obligations.filter(o => o.schedule && o.schedule.freq === 'once' && D.parse(o.schedule.anchor) !== null && D.parse(o.schedule.anchor) >= T)
      .map(o => ({ id: o.id, name: o.name, category: o.category, amountCents: o.amountCents, day: D.parse(o.schedule.anchor), essential: !!o.essential, verified: !!o.verified })).sort((a, b) => a.day - b.day);
  };

  /* ---------- fast verification: the four forecasts that decide "short or not" ---------- */
  // planned = bills + essentials + the student's approved (or estimated) discretionary budgets, spent in full; commit = bills + essentials only
  function quick(plan, T) {
    const det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det), out = {};
    for (const sc of ['cautious', 'expected']) {
      const pl = E.forecast(plan, { today: T, scenario: sc, flex: 'budget', det, base }); if (!pl.ok) return null;
      const cm = E.forecast(plan, { today: T, scenario: sc, flex: 'none', det, base });
      out[sc] = { planned: mk(pl.metrics), commit: mk(cm.metrics) };
    }
    out.C = plan.account.cushionCents; out.endDay = E.horizonInfo(plan, T).endDay;
    return out;
  }
  const fixesIt = (q, extra) => q.cautious.planned.minCents >= q.C + (extra || 0);

  /* ---------- is the semester on track? ---------- */
  // status: needs_info | on_track | tight | depends_on_income | over_budget | short_bills
  function standingOf(plan, T, snap, trust) {
    const C = plan.account.cushionCents, H = snap.cautious.fc.endDay, end = label(H), cap = snap.cautious.capacity;
    const cc = snap.cautious.fc.metrics, ec = snap.expected.fc.metrics, cp = snap.cautious.planned.metrics, ep = snap.expected.planned.metrics;
    const out = (status, tone, headline, detail) => ({ status, tone, headline, detail, onTrack: status === 'on_track' || status === 'tight' });
    if (trust && !trust.showAllowance) return out('needs_info', 'amber', 'We cannot judge your semester yet', (trust.missing && trust.missing[0] ? trust.missing[0].why || trust.missing[0].label : 'Some information is missing.') + ' Answer it on Today and this page will fill in.');
    if (cc.minCents < C) {
      const bothShort = ec.minCents < C, below = cc.minCents < 0;
      return out('short_bills', 'warn', 'Bills and essentials are not covered through ' + end,
        'Even if you spend nothing on extras, your balance would fall to ' + fmt(cc.minCents) + ' on ' + label(cc.minDay) + ', which is ' + (below ? 'below $0 (overdrawn)' : fmt(C - cc.minCents) + ' below your ' + fmt(C) + ' cushion') + (bothShort ? ', even if everything arrives on time' : ' in the cautious view (the expected view stays above your cushion)') + '. First check that all your income and aid are entered. Then see the ideas below.');
    }
    if (cp.minCents < C) {
      const expectedShort = ep.minCents < C, pace = cap.todayLimit.allowanceCents;
      if (expectedShort) return out('over_budget', 'amber', 'Bills are covered, but your approved spending is more than the plan supports',
        'If you spend every approved budget in full, your balance would reach ' + fmt(cp.minCents) + ' on ' + label(cp.minDay) + ', ' + (cp.minCents < 0 ? 'below $0' : fmt(C - cp.minCents) + ' below your ' + fmt(C) + ' cushion') + '. Spending about your daily pace (' + fmt(pace) + ') keeps you on track.');
      return out('depends_on_income', 'amber', 'On track only if your income and aid arrive as hoped',
        'If everything arrives as expected, your lowest balance is ' + fmt(ep.minCents) + ' on ' + label(ep.minDay) + '. In the cautious view it is ' + fmt(cp.minCents) + ' on ' + label(cp.minDay) + ', ' + (cp.minCents < 0 ? 'below $0' : fmt(C - cp.minCents) + ' below your cushion') + '. Plan with the cautious number.');
    }
    const headroom = cp.minCents - C;
    if (headroom < 5000) return out('tight', 'amber', 'On track, with very little slack', 'Your lowest balance is ' + fmt(cp.minCents) + ' on ' + label(cp.minDay) + ', only ' + fmt(headroom) + ' above your ' + fmt(C) + ' cushion, even in the cautious view. One unexpected expense would put you below it.');
    return out('on_track', 'good', 'On track through ' + end, 'Your lowest balance is ' + fmt(cp.minCents) + ' on ' + label(cp.minDay) + ', ' + fmt(headroom) + ' above your ' + fmt(C) + ' cushion, even in the cautious view, if you spend your approved budgets.');
  }
  E.semesterStanding = function (plan, T, snap) { snap = snap || E.snapshot(plan, T); return snap.ok ? standingOf(plan, T, snap, E.trust(plan, T, snap)) : null; };

  /* ---------- timeline helpers ---------- */
  const KIND_LABEL = { pay: 'Paycheck', aid: 'Financial aid', income: 'Income', rent: 'Rent', tuition: 'Tuition or fees', books: 'Textbooks and supplies', oneTime: 'One-time expense', bill: 'Bill', subscription: 'Subscription', debt: 'Debt payment', savings: 'Savings transfer', other: 'Payment' };
  function eventKind(plan, e) {
    if (e.type === 'income') return e.itype === 'aid' || e.itype === 'scholarship' ? 'aid' : e.itype === 'job' || e.itype === 'workstudy' || e.itype === 'gig' ? 'pay' : 'income';
    if (e.type === 'savings') return 'savings';
    const ob = plan.obligations.find(o => o.id === e.id), cat = e.category || (ob && ob.category) || '';
    if (ob && ob.schedule && ob.schedule.freq === 'once' && cat !== 'Tuition & fees' && cat !== 'School supplies') return 'oneTime';
    if (cat === 'Housing') return 'rent'; if (cat === 'Tuition & fees') return 'tuition'; if (cat === 'School supplies') return 'books';
    if (cat === 'Subscriptions') return 'subscription'; if (cat === 'Debt payment') return 'debt';
    return 'bill';
  }
  function itemOf(plan, e) { return e.type === 'income' ? plan.incomes.find(x => x.id === e.id) : e.type === 'bill' ? plan.obligations.find(x => x.id === e.id) : e.type === 'savings' ? plan.goals.find(x => x.id === e.id) : null; }

  function timelineEvents(plan, T, cp, ep) {
    const byExp = {}; for (const e of ep.events) (byExp[e.type + '|' + e.id] = byExp[e.type + '|' + e.id] || []).push(e);
    const seen = {}, out = [];
    for (const e of cp.events) {
      if (e.type === 'purchase') continue;
      const k = e.type + '|' + e.id, i = seen[k] = (seen[k] || 0) + 1, ex = (byExp[k] || [])[i - 1] || null, item = itemOf(plan, e);
      const nature = E.natureOf ? E.natureOf({ type: e.type }, item) : 'expected', kind = eventKind(plan, e), idx = e.day - T;
      const row = { day: e.day, dayLabel: label(e.day), name: e.name, kind, kindLabel: KIND_LABEL[kind], money: e.amountCents > 0 ? 'in' : 'out', amountCents: e.amountCents, nature, natureLabel: E.NATURE[nature].label, balanceAfterCents: cp.days[idx] ? cp.days[idx].bal : null, reliability: e.reliability, verified: !!e.verified, expected: null, note: '' };
      if (ex && (ex.day !== e.day || ex.amountCents !== e.amountCents)) {
        row.expected = { day: ex.day, amountCents: ex.amountCents };
        const bits = []; if (ex.day < e.day) bits.push('arrives ' + plural(e.day - ex.day, 'day') + ' later than expected'); if (ex.amountCents > e.amountCents) bits.push('counted at ' + fmt(Math.abs(e.amountCents)) + ' instead of ' + fmt(Math.abs(ex.amountCents)));
        row.note = 'In the cautious view it ' + bits.join(' and ') + '.';
      }
      out.push(row);
    }
    return out;
  }

  const cap1 = (t, up) => up ? t.charAt(0).toUpperCase() + t.slice(1) : t;
  // Local lows of the balance, explained: what happened since money last arrived, and when money next arrives.
  function pressurePoints(fc, T, C, limit) {
    const d = fc.days, N = d.length, cand = [];
    for (let i = 0; i < N; i++) { const b = d[i].bal, p = i > 0 ? d[i - 1].bal : Infinity, n = i < N - 1 ? d[i + 1].bal : Infinity; if (b <= p && b < n) cand.push(i); }
    if (!cand.length) return [];
    let globalMin = cand[0]; for (const i of cand) if (d[i].bal < d[globalMin].bal) globalMin = i;
    let pick = cand.filter(i => i === globalMin || d[i].bal < C + 20000).sort((a, b) => d[a].bal - d[b].bal);
    const kept = []; for (const i of pick) if (!kept.some(j => Math.abs(j - i) <= 3)) kept.push(i);
    const out = [];
    for (const i of kept.slice(0, limit || 4).sort((a, b) => a - b)) {
      let k = -1; for (let x = i; x >= 0; x--) if (d[x].inc > 0) { k = x; break; }
      const from = k + 1, startBal = k >= 0 ? d[k].bal : fc.open.cents;
      let obl = 0, ess = 0, flx = 0, sav = 0, pur = 0; for (let x = from; x <= i; x++) { obl += d[x].obl; ess += d[x].ess; flx += d[x].flx; sav += d[x].sav; pur += d[x].pur; }
      const drivers = fc.events.filter(e => e.amountCents < 0 && e.type !== 'purchase' && e.day >= d[from].day && e.day <= d[i].day).sort((a, b) => a.amountCents - b.amountCents).slice(0, 3).map(e => ({ name: e.name, day: e.day, amountCents: -e.amountCents }));
      const last = k >= 0 ? fc.events.filter(e => e.amountCents > 0 && e.day === d[k].day).sort((a, b) => b.amountCents - a.amountCents)[0] : null;
      let nx = null; for (let x = i + 1; x < N; x++) if (d[x].inc > 0) { const e = fc.events.filter(y => y.amountCents > 0 && y.day === d[x].day).sort((a, b) => b.amountCents - a.amountCents)[0]; nx = { name: e ? e.name : 'Income', day: d[x].day, amountCents: d[x].inc, daysLater: d[x].day - d[i].day }; break; }
      const bal = d[i].bal, kind = bal < 0 ? 'short' : bal < C ? 'below_cushion' : 'watch', everyday = ess + flx;
      const parts = drivers.map(x => x.name + ' (' + fmt(x.amountCents) + ' on ' + label(x.day) + ')'); if (everyday > 0) parts.push('about ' + fmt(everyday) + ' of everyday essentials and budgeted spending');
      const why = (last ? 'After ' + last.name + ' on ' + label(last.day) + ' your balance is ' + fmt(startBal) + '. ' : 'Starting from today\'s ' + fmt(startBal) + ', ')
        + (parts.length ? cap1(parts.join(', ').replace(/, ([^,]*)$/, ' and $1'), !!last) + (parts.length > 1 ? ' bring it to ' : ' brings it to ') : (last ? 'It falls to ' : 'it falls to ')) + fmt(bal) + ' on ' + label(d[i].day) + '.'
        + (nx ? ' Next money: ' + nx.name + ' (' + fmt(nx.amountCents) + ') on ' + label(nx.day) + ', ' + plural(nx.daysLater, 'day') + ' later.' : ' No money is scheduled before the end of the term.');
      out.push({ day: d[i].day, balanceCents: bal, kind, isLowest: i === globalMin, lastIncome: last ? { name: last.name, day: last.day, amountCents: last.amountCents, balanceCents: startBal } : null, drivers, billsCents: obl + sav + pur, everydayCents: everyday, nextIncome: nx, why });
    }
    return out;
  }

  // Rent (and other housing) against paychecks: how long after the last pay does it land, and does the balance hold until the next pay?
  function rentGaps(fc, T, C) {
    const d = fc.days, rows = [];
    for (const e of fc.events) {
      if (e.type !== 'bill' || e.category !== 'Housing' || e.amountCents >= 0) continue;
      const idx = e.day - T; if (idx < 0 || idx >= d.length) continue;
      let lastI = -1; for (let x = idx; x >= 0; x--) if (d[x].inc > 0) { lastI = x; break; }
      let nextI = -1; for (let x = idx + 1; x < d.length; x++) if (d[x].inc > 0) { nextI = x; break; }
      let low = d[idx].bal, lowDay = e.day; for (let x = idx; x < (nextI < 0 ? d.length : nextI); x++) if (d[x].bal < low) { low = d[x].bal; lowDay = d[x].day; }
      const pe = (i2) => fc.events.filter(y => y.amountCents > 0 && y.day === d[i2].day).sort((a, b) => b.amountCents - a.amountCents)[0];
      rows.push({ name: e.name, day: e.day, amountCents: -e.amountCents, balanceAfterCents: d[idx].bal, lastPay: lastI >= 0 ? { name: pe(lastI) ? pe(lastI).name : 'Income', day: d[lastI].day, daysBefore: e.day - d[lastI].day } : null, nextPay: nextI >= 0 ? { name: pe(nextI) ? pe(nextI).name : 'Income', day: d[nextI].day, daysAfter: d[nextI].day - e.day } : null, lowestBeforeNextPayCents: low, lowestDay: lowDay, holds: low >= C, belowZero: low < 0 });
    }
    return rows;
  }

  /* ---------- the Semester view ---------- */
  const usable = plan => !!(plan && typeof plan === 'object' && plan.account && Array.isArray(plan.incomes) && Array.isArray(plan.obligations) && Array.isArray(plan.transactions) && Array.isArray(plan.periods));
  E.semesterView = function (plan, T) {
    if (!usable(plan)) return { ok: false, error: 'no_plan', today: T };
    const snap = E.snapshot(plan, T);
    if (!snap.ok) return { ok: false, error: snap.error || 'no_balance', today: T };
    const trust = E.trust(plan, T, snap), ctx = E.termContext(plan, T), C = plan.account.cushionCents;
    const cc = snap.cautious.fc, ec = snap.expected.fc, cp = snap.cautious.planned, ep = snap.expected.planned, cap = snap.cautious.capacity, capE = snap.expected.capacity;
    const H = cc.endDay, N = cc.N, standing = standingOf(plan, T, snap, trust);
    const forecasts = { cautious: { planned: mk(cp.metrics), commitments: mk(cc.metrics) }, expected: { planned: mk(ep.metrics), commitments: mk(ec.metrics) } };
    const differs = forecasts.cautious.planned.endCents !== forecasts.expected.planned.endCents || forecasts.cautious.planned.minCents !== forecasts.expected.planned.minCents;

    // what makes the cautious view cautious (only what actually differs)
    const assumptions = [];
    for (const inc of plan.incomes) {
      if (!inc.schedule || inc.amountCents <= 0 || inc.reliability === 'uncertain') continue;
      const cAmt = E.cautiousIncomeCents(plan, inc), aidLike = inc.type === 'aid' || inc.type === 'scholarship', late = inc.delayDays + (inc.reliability === 'likely' && aidLike ? plan.settings.cautiousLateDays : 0);
      if (cAmt !== inc.amountCents) assumptions.push({ kind: 'amount', name: inc.name, text: inc.name + ' is counted at ' + fmt(cAmt) + ' per payment instead of ' + fmt(inc.amountCents) + ' (' + E.cautiousReason(plan, inc) + ').' });
      if (late > inc.delayDays) assumptions.push({ kind: 'late', name: inc.name, text: inc.name + ' is assumed to arrive ' + plural(plan.settings.cautiousLateDays, 'day') + ' later than scheduled.' });
    }
    for (const o of plan.obligations) if (o.highCents != null && o.highCents > o.amountCents) assumptions.push({ kind: 'bill', name: o.name, text: o.name + ' is counted at its high amount, ' + fmt(o.highCents) + '.' });

    // cushion
    const p0 = E.clone(plan); p0.account.cushionCents = 0;
    const capNo = E.capacity(E.normalizePlan(p0).plan, { today: T, scenario: 'cautious' });
    const cushion = { cents: C, headroomCents: cp.metrics.minCents - C, aboveZeroCents: Math.max(0, cp.metrics.minCents), absorbsCents: Math.max(0, cp.metrics.minCents - C), roomCents: cap.semester.allowanceCents, roomWithoutCents: capNo.ok ? capNo.semester.allowanceCents : null, heldBackCents: capNo.ok ? capNo.semester.allowanceCents - cap.semester.allowanceCents : C,
      spendingNothingExtra: { lowestCents: cc.metrics.minCents, lowestDay: cc.metrics.minDay, headroomCents: cc.metrics.minCents - C } };

    // the money the semester rests on, by how sure we are
    const events = timelineEvents(plan, T, cp, ep);
    const sums = { confirmed: { inCents: 0, outCents: 0, n: 0 }, scheduled: { inCents: 0, outCents: 0, n: 0 }, expected: { inCents: 0, outCents: 0, n: 0 } };
    for (const e of events) { const s = sums[e.nature] || sums.expected; if (e.money === 'in') s.inCents += e.amountCents; else s.outCents -= e.amountCents; s.n++; }
    const estimatedOutCents = E.sum(cp.days, r => r.ess + r.flx), uncounted = cc.uncounted.filter(u => u.day >= T && u.day <= H && u.reason !== 'unconfirmed_deposit').map(u => ({ name: u.name, day: u.day, amountCents: u.amountCents, income: u.type === 'income', text: u.type === 'income' ? 'Not counted: you were not sure it will arrive.' : 'Not counted: found in your transactions with low confidence.' }));
    const rests = { confirmed: sums.confirmed, scheduled: sums.scheduled, expected: sums.expected, estimatedOutCents, estimatedDays: N + 1, uncertainInCents: E.sum(uncounted.filter(u => u.income), u => u.amountCents), uncounted };

    // months (the cautious view is the plan; the expected view sits beside it)
    const emap = {}; for (const m of ep.months) emap[m.key] = m;
    const flexRows = cp.budgetsUsed.filter(b => b.kind === 'flexible');
    const basis = !flexRows.length ? 'none' : flexRows.every(b => b.basis === 'approved') ? 'approved' : flexRows.some(b => b.basis === 'approved') ? 'mixed' : 'estimated';
    const months = cp.months.map(m => {
      const e = emap[m.key] || m, evs = events.filter(x => D.monthKey(x.day) === m.key), billsCents = m.obl + m.sav + m.pur;
      const row = { key: m.key, label: monthLabel(m.key), short: monthLabel(m.key).slice(0, 3), startDay: m.startDay, endDay: m.endDay, partial: m.partial,
        partialNote: m.partial ? (m.startDay === T ? 'From ' + label(T) : 'From ' + label(m.startDay)) + (m.endDay === H ? ' through ' + label(H) : ' to ' + label(m.endDay)) : '',
        incomeCents: m.inc, expectedIncomeCents: e.inc, billsCents, essentialsCents: m.ess, discretionaryCents: m.flx, estimatedCents: m.ess + m.flx, netCents: m.net,
        startCents: m.startBal, endCents: m.endBal, minCents: m.minBal, minDay: m.minDay, status: m.status, expectedEndCents: e.endBal, expectedMinCents: e.minBal, expectedStatus: e.status,
        discretionaryBasis: basis, shortfallCents: Math.max(0, C - m.minBal), events: evs, narrative: '' };
      row.narrative = row.label + ': ' + fmt(row.incomeCents) + ' comes in, ' + fmt(row.billsCents) + ' goes to bills and required payments, about ' + fmt(row.essentialsCents) + ' to everyday essentials and ' + fmt(row.discretionaryCents) + ' to discretionary spending. You end ' + (row.partial && m.endDay === H ? 'the term' : 'the month') + ' with ' + fmt(row.endCents) + (row.minCents < row.endCents ? ' (lowest ' + fmt(row.minCents) + ' on ' + label(row.minDay) + ')' : '') + '.';
      return row;
    });
    const reconcile = { totalNetCents: E.sum(months, r => r.netCents), openCents: cc.open.cents, endCents: cp.metrics.endCents, firstStartCents: months.length ? months[0].startCents : null, lastEndCents: months.length ? months[months.length - 1].endCents : null };
    reconcile.ok = months.length > 0 && reconcile.firstStartCents === cp.days[0].bal - cp.days[0].inc + cp.days[0].obl + cp.days[0].sav + cp.days[0].ess + cp.days[0].flx + cp.days[0].pur && reconcile.lastEndCents === reconcile.endCents && reconcile.firstStartCents + reconcile.totalNetCents === reconcile.endCents;

    // discretionary vs what the plan supports (same function Today's monthly budget uses)
    const mp = E.monthlyPlan(plan, { today: T, scenario: 'cautious' });
    const budgetFit = mp.ok ? { status: mp.status, supportedCents: mp.supportedFlexibleCents, plannedCents: mp.plannedFlexibleCents, gapCents: mp.gapCents, periodEndDay: mp.month.endDay } : null;

    // income & aid
    const evC = cp.events.filter(e => e.type === 'income'), evE = ep.events.filter(e => e.type === 'income');
    const incomeRows = plan.incomes.filter(i => i.schedule && i.amountCents > 0).map(inc => {
      const c = evC.filter(e => e.id === inc.id), x = evE.filter(e => e.id === inc.id), counted = inc.reliability !== 'uncertain', aidLike = inc.type === 'aid' || inc.type === 'scholarship';
      const nature = E.natureOf ? E.natureOf({ type: 'income' }, inc) : 'expected', cAmt = E.cautiousIncomeCents(plan, inc);
      let afterTerm = null;
      if (counted && !x.length) { const o = E.occurrences(inc.schedule, H + 1, H + 150)[0]; if (o) { const late = inc.delayDays + (inc.reliability === 'likely' && aidLike ? plan.settings.cautiousLateDays : 0); afterTerm = { day: o.day + inc.delayDays, cautiousDay: o.day + late, amountCents: inc.amountCents }; } }
      const notes = [];
      if (afterTerm) notes.push('Arrives after the term ends (' + label(afterTerm.day) + (afterTerm.cautiousDay !== afterTerm.day ? '; ' + label(afterTerm.cautiousDay) + ' in the cautious view' : '') + '), so it is not part of this term\'s numbers. It sets how long you wait between terms.'); if (!counted) notes.push('Not counted in either view: you were not sure it will arrive. It is upside, not a promise.');
      else { if (cAmt !== inc.amountCents) notes.push('The cautious view counts ' + fmt(cAmt) + ' per payment (' + E.cautiousReason(plan, inc) + ').'); if (aidLike && inc.reliability === 'likely') notes.push('The cautious view assumes it arrives ' + plural(plan.settings.cautiousLateDays, 'day') + ' late.'); if (!inc.verified) notes.push('You have not verified this yet.'); }
      return { id: inc.id, name: inc.name, type: inc.type, kindLabel: aidLike ? 'Financial aid' : inc.type === 'job' || inc.type === 'workstudy' || inc.type === 'gig' ? 'Work' : 'Family or other', reliability: inc.reliability, verified: !!inc.verified, irregular: !!inc.irregular, counted, nature, natureLabel: E.NATURE[nature].label,
        termExpectedCents: E.sum(x, e => e.amountCents), termCautiousCents: E.sum(c, e => e.amountCents), countExpected: x.length, countCautious: c.length,
        nextExpected: x[0] ? { day: x[0].day, amountCents: x[0].amountCents } : null, nextCautious: c[0] ? { day: c[0].day, amountCents: c[0].amountCents } : null, notes, lumpSum: inc.schedule.freq === 'once', afterTerm };
    });
    const aidEvents = cp.events.filter(e => e.type === 'income' && (e.itype === 'aid' || e.itype === 'scholarship') && e.amountCents > 0);
    let aidDependence = null;
    if (aidEvents.length) {
      const p2 = E.clone(plan); p2.incomes = p2.incomes.filter(i => i.type !== 'aid' && i.type !== 'scholarship');
      const q = quick(E.normalizePlan(p2).plan, T);
      if (q) aidDependence = { aidCents: E.sum(aidEvents, e => e.amountCents), firstDay: aidEvents[0].day, withoutMinCents: q.cautious.planned.minCents, withoutMinDay: q.cautious.planned.minDay, withoutShortCents: Math.max(0, C - q.cautious.planned.minCents), needed: q.cautious.planned.minCents < C };
    }
    const irregular = plan.incomes.filter(i => i.irregular || i.lowCents != null);
    const income = { rows: incomeRows, aidDependence, rentGaps: rentGaps(cp, T, C), irregularNames: irregular.map(i => i.name), hasIrregular: irregular.length > 0, hasAid: incomeRows.some(r => r.type === 'aid' || r.type === 'scholarship'), totalExpectedCents: E.sum(incomeRows, r => r.termExpectedCents), totalCautiousCents: E.sum(incomeRows, r => r.termCautiousCents) };

    // between semesters (kept apart from the semester numbers on purpose)
    const soC = E.safetyOutlook(plan, { today: T, scenario: 'cautious', fc: cc, det: snap.det, base: snap.base, reserve: cap.reserve }), soE = E.safetyOutlook(plan, { today: T, scenario: 'expected', fc: ec, det: snap.det, base: snap.base });
    let after = { ok: false };
    if (soC.ok) {
      const po = E.paceOutlook(plan, T, snap, soC), b = soC.bridge, need = soC.needsBetweenTermsCents, endBal = cp.metrics.endCents, aboveCushion = Math.max(0, endBal - C);
      const offers = [];
      if (po.recommendReserve) {
        const full = po.ifSetAside, part = po.ifPartial, now = cap.todayLimit.allowanceCents, unrealistic = !!(full && full.paceCents < now * 0.5);
        if (unrealistic && part) offers.push({ id: 'partial', partial: true, label: 'Set aside ' + fmt(part.fixedCents) + ' to start', op: { type: 'reserveFixed', fixedCents: part.fixedCents, needCents: need }, coversCents: part.fixedCents, uncoveredCents: Math.max(0, need - part.fixedCents), paceBeforeCents: now, paceAfterCents: part.paceCents,
          note: 'This covers only part of the ' + fmt(need) + ' you will need between terms, so it may not fully cover your expenses then: about ' + fmt(Math.max(0, need - part.fixedCents)) + ' would remain uncovered. Your daily pace would change from ' + fmt(now) + ' to ' + fmt(part.paceCents) + '.' });
        else if (!unrealistic) offers.push({ id: 'full', partial: false, label: 'Set aside ' + fmt(need), op: { type: 'reserve' }, coversCents: need, uncoveredCents: 0, paceBeforeCents: now, paceAfterCents: full ? full.paceCents : now, note: full ? 'Your daily pace would change from ' + fmt(now) + ' to ' + fmt(full.paceCents) + '.' : '' });
      }
      let series = null;
      if (b && b.endDay > H) {
        const mkSeries = (sc, plannedFc, so) => { const long = E.forecast(plan, { today: T, scenario: sc, flex: 'none', det: snap.det, base: snap.base, endDay: so.bridge.endDay }); if (!long.ok || !long.days[N]) return null; const off = plannedFc.metrics.endCents - long.days[N].bal; return long.days.slice(N + 1).map(r => [r.day, r.bal + off]); };
        series = { cautious: mkSeries('cautious', cp, soC), expected: soE.ok && soE.bridge ? mkSeries('expected', ep, soE) : null };
      }
      const lowAfter = b ? endBal - need : endBal;
      const dates = soC.dates || E.planDateContext(plan, T, soC);
      after = { ok: true, semesterEndDay: H, needCents: need, needExpectedCents: soE.ok ? soE.needsBetweenTermsCents : need, bridge: b ? { startDay: b.startDay, endDay: b.endDay, days: b.days, endedBy: b.endedBy, aidName: b.aidName, aidDay: b.aidDay, aidScheduledDay: dates.aidScheduledDay, lowDay: b.lowDay, billsCents: b.billsCents, essentialsCents: b.essentialsCents, incomeCents: b.incomeCents } : null,
        items: b ? b.items.slice().sort((x, y) => y.amountCents - x.amountCents).slice(0, 8) : [], appliedReserveCents: soC.appliedReserveCents, gapCents: soC.gapCents, summary: soC.summary, explain: soC.explain, dates,
        nextBreak: ctx.nextBreak, nextSemester: ctx.nextSemester, offers, paceExplanation: po.explanation, paceSteps: po.steps, paceBig: po.big,
        coverage: { needCents: need, endBalanceIfBudgetsFollowedCents: endBal, aboveCushionCents: aboveCushion, lowestAfterCents: lowAfter, lowestAfterDay: b ? b.lowDay : H, belowCushionCents: Math.max(0, C - lowAfter), belowZeroCents: Math.max(0, -lowAfter), covered: need <= aboveCushion, uncoveredCents: Math.max(0, need - aboveCushion) },
        ifAllRoomSpent: soC.ifAllRoomSpent, reserveEnabled: soC.reserveEnabled, recommend: soC.recommend, series };
    }

    // the chart
    const chart = {
      startDay: T, endDay: H, cushionCents: C,
      cautious: cp.days.map(d => [d.day, d.bal]), expected: ep.days.map(d => [d.day, d.bal]), commitments: cc.days.map(d => [d.day, d.bal]),
      afterCautious: after.ok && after.series ? after.series.cautious : null, afterExpected: after.ok && after.series ? after.series.expected : null,
      events: events.map(e => ({ day: e.day, name: e.name, kind: e.kind, kindLabel: e.kindLabel, money: e.money, amountCents: e.amountCents })),
      lowest: { day: cp.metrics.minDay, cents: cp.metrics.minCents }
    };

    // how this ties to Today (safeLabelOk matches Today: commitments + approved budgets + after-term gap)
    const health = typeof E.planHealth === 'function' ? E.planHealth(plan, T, snap) : { ok: false, okCushion: true };
    const roomSplit = typeof E.semesterRoomSplit === 'function' ? E.semesterRoomSplit(cap, soC.ok ? soC : null) : null;
    if (roomSplit) {
      roomSplit.safeLabelOk = !!(health.ok && health.okCushion && roomSplit.afterTermProtected && cap.safe);
      roomSplit.safeToSpendCents = roomSplit.safeLabelOk ? roomSplit.unprotectedSpendCents : 0;
    }
    const today = {
      paceCents: cap.todayLimit.allowanceCents, paceExpectedCents: capE && capE.ok ? capE.todayLimit.allowanceCents : cap.todayLimit.allowanceCents,
      roomCents: cap.semester.remainingCents, roomAllowanceCents: cap.semester.allowanceCents, roomExpectedCents: capE && capE.ok ? capE.semester.remainingCents : cap.semester.remainingCents,
      monthRemainingCents: cap.month.remainingCents, oneTimeCents: cap.immediate.cents, safe: cap.safe, endDay: H,
      planHealth: health.ok ? health : null, roomSplit,
      safeLabelOk: !!(roomSplit && roomSplit.safeLabelOk)
    };

    const thinData = trust.showAllowance && (trust.level === 'provisional' || snap.base.status === 'provisional' || snap.base.status === 'limited');
    const dates = (after.ok && after.dates) || E.planDateContext(plan, T, soC.ok ? soC : null);
    return { ok: true, today: T, name: plan.meta.name || '', ctx, endDay: H, days: N, standing, thin: { is: thinData, days: snap.base.coverageDays, status: snap.base.status }, variable: { is: income.hasIrregular, names: income.irregularNames }, trust: { level: trust.level, showAllowance: trust.showAllowance, labels: trust.labels, reasons: trust.reasons, missing: trust.missing }, provisionalDates: ctx.provisional,
      forecasts, differs, assumptions, cushion, rests, months, reconcile, breakdown: E.semesterBreakdown(plan, T, snap), budgetFit, income, after, chart, events, pressure: pressurePoints(cp, T, C, 4), pressureCommitments: pressurePoints(cc, T, C, 2), todayLink: today, expenses: E.plannedExpenses(plan, T), discretionaryBasis: basis, dates,
      openCents: cc.open.cents, snapshotNote: 'Same engine as Today. Semester numbers use ' + dates.semesterRangeLabel + (dates.bridgeRangeLabel ? '; after-term safety uses ' + dates.bridgeRangeLabel + (dates.aidLabel ? ' (' + dates.aidLabel + ')' : '') : '') + '.' };
  };

  /* ---------- weekly and monthly breakdown of the whole semester (Stage 5B) ---------- */
  // One row per real calendar week (student's week-start day) and calendar month from the first day of the semester to its last day.
  //   history    days up to and including today: RECORDED transactions only (what was logged or imported), never an estimate.
  //              There is no daily balance history, so none is invented: the only balances shown for past days are the ones the
  //              student actually verified (their balance check and check-ins). Completeness is judged over FINISHED days
  //              (before today) against the dates the transactions on record actually span.
  //   projected  days from today on: sums of the cautious and expected daily forecast rows (the same rows as every other number).
  //              Today's already-recorded transactions are history; what is still expected today is projected, so nothing is in both.
  // Every week, month and the semester total come from E.sumDays over the same rows and from one pass over the same transactions,
  // so they reconcile to the cent; `reconcile` re-checks this and lists any mismatch.
  const REC_KEYS = ['incomeCents', 'aidCents', 'billsCents', 'essentialsCents', 'discretionaryCents', 'spendingCents', 'savedForGoalsCents', 'otherTransfersCents', 'cardPaymentsCents', 'checkingNetCents', 'count'];
  const PROJ_KEYS = ['inc', 'obl', 'sav', 'ess', 'flx', 'pur', 'net', 'days'];
  function recordedIn(txs, from, to) {
    const r = {}; for (const k of REC_KEYS) r[k] = 0;
    for (const t of txs) {
      if (t.day < from || t.day > to) continue;
      r.count++;
      if (t.account === 'checking') r.checkingNetCents += t.amountCents;
      if (t.flow === 'income') r.incomeCents += t.amountCents;
      else if (t.flow === 'aid') r.aidCents += t.amountCents;
      else if (t.flow === 'spend' || t.flow === 'refund') { const k = E.catKind(t.category || 'Other'), v = -t.amountCents; if (k === 'bill') r.billsCents += v; else if (k === 'essential') r.essentialsCents += v; else r.discretionaryCents += v; }
      else if (t.flow === 'transfer' && t.account === 'checking') { if (t.goalId) r.savedForGoalsCents += -t.amountCents; else r.otherTransfersCents += -t.amountCents; }
      else if (t.flow === 'card_payment') r.cardPaymentsCents += -t.amountCents;
    }
    r.spendingCents = r.billsCents + r.essentialsCents + r.discretionaryCents;
    return r;
  }
  const UNIT_WORD = { week: 'week', month: 'month', semester: 'semester' };
  E.semesterBreakdown = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    if (!snap || !snap.ok) return { ok: false, error: (snap && snap.error) || 'no_balance' };
    const ctx = E.termContext(plan, T), cp = snap.cautious.planned, ep = snap.expected.planned, H = cp.endDay, C = plan.account.cushionCents;
    const hasStart = ctx.startDay !== null && ctx.startDay <= H, S = hasStart ? ctx.startDay : T;
    const txs = E.activeTxs(plan).map(t => Object.assign({ day: D.parse(t.date) }, t)).filter(t => t.day <= T);
    const dataStart = txs.length ? Math.min.apply(null, txs.map(t => t.day)) : null, dataEnd = txs.length ? Math.max.apply(null, txs.map(t => t.day)) : null;
    const known = [];
    for (const c of plan.checkIns || []) known.push({ day: D.parse(c.date), cents: c.actualCents, source: 'check-in' });
    const anchor = D.parse(plan.account.asOf);
    if (anchor !== null && !known.some(k => k.day === anchor && k.cents === plan.account.balanceCents)) known.push({ day: anchor, cents: plan.account.balanceCents, source: 'balance' });
    known.sort((a, b) => a.day - b.day);
    const fromDay = Math.max(S, T);
    const build = p => {
      const unit = UNIT_WORD[p.unit], phase = p.endDay < T ? 'past' : p.startDay > T ? 'future' : 'current';
      const lbl = p.unit === 'month' ? monthLabel(p.key) : p.unit === 'semester' ? (ctx.periodName || 'This term') : label(p.startDay) + ' to ' + label(p.endDay);
      let history = null;
      if (p.startDay <= T) {
        const hTo = Math.min(p.endDay, T), done = Math.min(p.endDay, T - 1), n = Math.max(0, done - p.startDay + 1);
        const cFrom = dataStart === null ? null : Math.max(p.startDay, dataStart), cTo = dataEnd === null ? null : Math.min(done, dataEnd);
        const covered = cFrom === null || cTo < cFrom ? 0 : cTo - cFrom + 1;
        const status = n === 0 ? 'today_only' : covered === n ? 'recorded' : covered === 0 ? 'none' : 'partial';
        const text = status === 'recorded' ? 'Your transactions on record span this whole ' + unit + ' so far. Anything you did not log or import is not included.'
          : status === 'partial' ? 'Incomplete history: your transactions on record cover only ' + label(cFrom) + ' to ' + label(cTo) + ' of the ' + plural(n, 'finished day') + ' in this ' + unit + '.'
          : status === 'none' ? 'No history: there are no transactions on record for ' + label(p.startDay) + ' to ' + label(done) + '.'
          : 'Today is the first day of this ' + unit + '. Only what you have recorded today is shown.';
        history = { fromDay: p.startDay, toDay: hTo, finishedDays: n, coveredDays: covered, coveredFromDay: covered ? cFrom : null, coveredToDay: covered ? cTo : null, status, incomplete: status === 'partial' || status === 'none', label: text, recorded: recordedIn(txs, p.startDay, hTo) };
      }
      const proj = sc => { const fc = sc === 'cautious' ? cp : ep, s = p.endDay >= fromDay ? E.sumDays(fc.days, Math.max(p.startDay, fromDay), p.endDay) : null; if (s) s.status = s.minBal < 0 ? 'short' : s.minBal < C ? 'tight' : 'ok'; return s; };
      const projected = p.endDay >= fromDay ? { fromDay: Math.max(p.startDay, fromDay), cautious: proj('cautious'), expected: proj('expected') } : null;
      return Object.assign({}, p, { label: lbl, phase, history, projected, knownBalances: known.filter(k => k.day >= p.startDay && k.day <= p.endDay && k.day <= T) });
    };
    const weeks = E.calendarPeriods(S, H, 'week', plan.settings.weekStartsOn).map(build), months = E.calendarPeriods(S, H, 'month').map(build);
    const semester = build({ key: 'semester', unit: 'semester', startDay: S, endDay: H, days: H - S + 1, fullStartDay: S, fullEndDay: H, clipped: false });
    const preTerm = T < S ? { fromDay: T, toDay: S - 1, cautious: E.sumDays(cp.days, T, S - 1), expected: E.sumDays(ep.days, T, S - 1), note: 'Days before your term starts. They are in the forecast but not in the weekly or monthly rows.' } : null;

    // reconciliation: the same covered dates must give the same totals at every level, to the cent
    const bad = [];
    const sumOf = (rows, get, k) => E.sum(rows, r => { const x = get(r); return x ? x[k] : 0; });
    for (const sc of ['cautious', 'expected']) {
      const whole = E.sumDays((sc === 'cautious' ? cp : ep).days, fromDay, H), g = r => r.projected && r.projected[sc];
      for (const k of PROJ_KEYS) {
        const w = sumOf(weeks, g, k), m = sumOf(months, g, k), s = g(semester) ? g(semester)[k] : 0, d = whole ? whole[k] : 0;
        if (!(w === d && m === d && s === d)) bad.push({ what: sc + ' ' + k, days: d, weeks: w, months: m, semester: s });
      }
      for (const rows of [weeks, months]) {
        const pr = rows.map(g).filter(Boolean);
        for (let i = 1; i < pr.length; i++) if (pr[i].startBal !== pr[i - 1].endBal) bad.push({ what: sc + ' balance carries from ' + label(pr[i - 1].endDay) + ' to ' + label(pr[i].startDay) });
        if (pr.length && whole && (pr[0].startBal !== whole.startBal || pr[pr.length - 1].endBal !== whole.endBal)) bad.push({ what: sc + ' first and last balance' });
      }
    }
    const hAll = semester.history ? semester.history.recorded : null;
    if (hAll) for (const k of REC_KEYS) {
      const w = sumOf(weeks, r => r.history && r.history.recorded, k), m = sumOf(months, r => r.history && r.history.recorded, k);
      if (!(w === hAll[k] && m === hAll[k])) bad.push({ what: 'recorded ' + k, semester: hAll[k], weeks: w, months: m });
    }
    for (const rows of [weeks, months]) {
      if (!rows.length || rows[0].startDay !== S || rows[rows.length - 1].endDay !== H) bad.push({ what: rows[0] && rows[0].unit + ' rows do not span the semester' });
      for (let i = 1; i < rows.length; i++) if (rows[i].startDay !== rows[i - 1].endDay + 1) bad.push({ what: rows[i].unit + ' gap or overlap at ' + label(rows[i].startDay) });
    }
    const incompleteCount = weeks.filter(w => w.history && w.history.incomplete).length;
    return {
      ok: true, today: T, startDay: S, endDay: H, startKnown: hasStart, periodName: ctx.periodName, weekStartsOn: plan.settings.weekStartsOn, provisionalDates: ctx.provisional,
      weeks, months, semester, preTerm, knownBalances: known.filter(k => k.day >= S && k.day <= T), data: { fromDay: dataStart, toDay: dataEnd, count: txs.length },
      history: { incompleteWeeks: incompleteCount, note: hasStart ? (S < T ? 'Earlier ' + (incompleteCount ? 'weeks show what is on record; ' + plural(incompleteCount, 'week') + ' ' + (incompleteCount === 1 ? 'is' : 'are') + ' incomplete.' : 'weeks show the transactions on record.') + ' Past balances are not estimated; only balances you checked are shown.' : '') : 'No semester start date is known, so the breakdown starts today.' },
      reconcile: { ok: bad.length === 0, mismatches: bad }
    };
  };

  /* ---------- stress tests ---------- */
  // Every test re-runs the real forecast on a COPY of the plan. The saved plan is never touched.
  E.STRESS_MENU = [
    { id: 'aidLate', label: 'Financial aid arrives late', unit: 'days', options: [7, 14, 21, 30], dflt: 14, optionLabel: n => n + ' days late' },
    { id: 'workCut', label: 'Work hours or income drop', unit: '%', options: [10, 25, 40], dflt: 25, optionLabel: n => n + '% less' },
    { id: 'surprise', label: 'An unexpected expense', unit: '$', options: [10000, 30000, 50000, 100000], dflt: 30000, optionLabel: n => fmt(n) },
    { id: 'rentIncrease', label: 'Rent goes up', unit: '$/payment', options: [2500, 5000, 10000], dflt: 5000, optionLabel: n => '+' + fmt(n) + ' a month' },
    { id: 'postpone', label: 'A planned purchase is postponed', unit: 'days', options: [14, 30, 60], dflt: 30, optionLabel: n => n + ' days later' },
    { id: 'cutFlex', label: 'Discretionary spending decreases', unit: '%', options: [10, 20, 30], dflt: 20, optionLabel: n => n + '% less' }
  ];
  const STRESS_ORDER = ['aidLate', 'workCut', 'rentIncrease', 'surprise', 'postpone', 'cutFlex'];
  function postponable(plan, T) {
    const A = D.parse(plan.account.asOf), H = E.horizonInfo(plan, T).endDay;
    return plan.obligations.filter(o => o.schedule && o.schedule.freq === 'once' && !o.essential && D.parse(o.schedule.anchor) !== null && D.parse(o.schedule.anchor) > Math.max(T - 1, A === null ? 0 : A) && D.parse(o.schedule.anchor) <= H);
  }
  E.stressApplies = function (plan, T, id) {
    const H = E.horizonInfo(plan, T).endDay, far = H + (plan.settings.reserveBridgeMaxDays || 60);
    switch (id) {
      case 'aidLate': return plan.incomes.some(i => (i.type === 'aid' || i.type === 'scholarship') && i.schedule && i.reliability !== 'uncertain' && i.amountCents > 0) ? { ok: true } : { ok: false, reason: 'You have no financial aid or scholarship scheduled, so there is nothing to arrive late.' };
      case 'workCut': return plan.incomes.some(i => (i.type === 'job' || i.type === 'workstudy' || i.type === 'gig') && i.schedule && i.reliability !== 'uncertain' && i.amountCents > 0) ? { ok: true } : { ok: false, reason: 'You have no job, work-study or gig income entered.' };
      case 'surprise': return { ok: true };
      case 'rentIncrease': return plan.obligations.some(o => o.category === 'Housing' && o.amountCents > 0) ? { ok: true } : { ok: false, reason: 'You have no rent or housing payment entered.' };
      case 'postpone': return postponable(plan, T).length ? { ok: true } : { ok: false, reason: 'You have no nonessential one-time expense planned before the term ends. Add one below to try this.' };
      case 'cutFlex': return E.effectiveBudgets(plan, T).some(b => b.kind === 'flexible' && b.monthlyCents > 0) ? { ok: true } : { ok: false, reason: 'You have no discretionary budget to cut.' };
      default: return { ok: false, reason: 'Unknown test.' };
    }
  };
  E.stressMenu = function (plan, T) { return E.STRESS_MENU.map(m => Object.assign({}, m, { options: m.options.slice(), applies: E.stressApplies(plan, T, m.id) })); };
  function changeFor(plan, T, pick) {
    const v = Number(pick.param);
    switch (pick.id) {
      case 'aidLate': return [{ type: 'aidLate', days: v }];
      case 'workCut': return [{ type: 'workCut', pct: v }];
      case 'surprise': return [{ type: 'surprise', amountCents: v, label: 'Unexpected expense' }];
      case 'rentIncrease': return [{ type: 'rentIncrease', amountCents: v }];
      case 'postpone': return postponable(plan, T).map(o => ({ type: 'delayOneTime', id: o.id, days: v }));
      case 'cutFlex': return [{ type: 'cutFlex', pct: v }];
      default: return [];
    }
  }
  function summaryOf(plan, T) {
    const snap = E.snapshot(plan, T); if (!snap.ok) return null;
    const cc = snap.cautious.fc, cp = snap.cautious.planned, ep = snap.expected.planned, cap = snap.cautious.capacity;
    const so = E.safetyOutlook(plan, { today: T, scenario: 'cautious', fc: cc, det: snap.det, base: snap.base });
    return { standing: standingOf(plan, T, snap, null), cautious: mk(cp.metrics), expected: mk(ep.metrics), commitCautious: mk(cc.metrics), commitExpected: mk(snap.expected.fc.metrics), paceCents: cap.todayLimit.allowanceCents, roomCents: cap.semester.remainingCents, safe: cap.safe, needBetweenCents: so.ok ? so.needsBetweenTermsCents : 0, endDay: cc.endDay,
      series: { cautious: cp.days.map(d => [d.day, d.bal]), expected: ep.days.map(d => [d.day, d.bal]) } };
  }
  // picks: [{ id, param }]. Runs them together (one combined what-if) on a copy of the plan.
  E.stressRun = function (plan, T, picks) {
    picks = (Array.isArray(picks) ? picks : []).filter(p => p && STRESS_ORDER.indexOf(p.id) >= 0).sort((a, b) => STRESS_ORDER.indexOf(a.id) - STRESS_ORDER.indexOf(b.id));
    if (!picks.length) return { ok: false, error: 'Choose at least one stress test.' };
    const skipped = []; let p = plan; const assumptions = [], used = [];
    for (const pick of picks) {
      const strength = Number(pick.param), max = { aidLate: 120, workCut: 100, cutFlex: 100, postpone: 365, surprise: 5e7, rentIncrease: 5e6 }[pick.id];
      if (!Number.isFinite(strength) || strength <= 0 || strength > max) { skipped.push({ id: pick.id, reason: 'That strength is not valid.' }); continue; }
      const ap = E.stressApplies(plan, T, pick.id);
      if (!ap.ok) { skipped.push({ id: pick.id, reason: ap.reason }); continue; }
      for (const ch of changeFor(p, T, pick)) { const r = E.applyChange(p, Object.assign({}, ch, { today: T })); p = r.plan; for (const a of r.assumptions) assumptions.push(a); }
      used.push(pick);
    }
    const before = summaryOf(plan, T);
    if (!before) return { ok: false, error: 'no_balance' };
    if (!used.length) return { ok: true, empty: true, skipped, picks: [], assumptions: [], before, after: before, delta: null };
    const after = summaryOf(E.normalizePlan(p).plan, T);
    const C = plan.account.cushionCents;
    const delta = { minCents: after.cautious.minCents - before.cautious.minCents, endCents: after.cautious.endCents - before.cautious.endCents, expectedMinCents: after.expected.minCents - before.expected.minCents, paceCents: after.paceCents - before.paceCents, roomCents: after.roomCents - before.roomCents, needBetweenCents: after.needBetweenCents - before.needBetweenCents };
    const sentences = [];
    sentences.push('Lowest balance (cautious, approved budgets in full): ' + fmt(before.cautious.minCents) + ' on ' + label(before.cautious.minDay) + ' becomes ' + fmt(after.cautious.minCents) + ' on ' + label(after.cautious.minDay) + '.');
    if (after.paceCents !== before.paceCents) sentences.push('Your sustainable daily pace goes from ' + fmt(before.paceCents) + ' to ' + fmt(after.paceCents) + '.');
    if (after.needBetweenCents !== before.needBetweenCents) sentences.push('The money you will need between terms goes from ' + fmt(before.needBetweenCents) + ' to ' + fmt(after.needBetweenCents) + '.');
    const noEffect = delta.minCents === 0 && delta.endCents === 0 && delta.paceCents === 0 && delta.needBetweenCents === 0;
    if (noEffect) sentences.push('Nothing changed in the numbers above: this term\'s lowest balance, daily pace and the money you need between terms are the same.');
    return { ok: true, empty: false, picks: used, skipped, assumptions, before, after, delta, noEffect, sentences, standingChanged: before.standing.status !== after.standing.status, cushionCents: C,
      series: { baselineCautious: before.series.cautious, baselineExpected: before.series.expected, cautious: after.series.cautious, expected: after.series.expected }, planUnchanged: true };
  };
  // each applicable test at its default strength, alone
  E.stressTable = function (plan, T) {
    const rows = [], base = summaryOf(plan, T); if (!base) return { ok: false, error: 'no_balance', rows };
    for (const m of E.STRESS_MENU) {
      const ap = E.stressApplies(plan, T, m.id);
      if (!ap.ok) { rows.push({ id: m.id, label: m.label, param: m.dflt, paramLabel: m.optionLabel(m.dflt), applies: false, reason: ap.reason }); continue; }
      const r = E.stressRun(plan, T, [{ id: m.id, param: m.dflt }]);
      rows.push({ id: m.id, label: m.label, param: m.dflt, paramLabel: m.optionLabel(m.dflt), applies: true, minCents: r.after.cautious.minCents, minDay: r.after.cautious.minDay, deltaMinCents: r.delta.minCents, paceCents: r.after.paceCents, deltaPaceCents: r.delta.paceCents, deltaRoomCents: r.delta.roomCents, needBetweenCents: r.after.needBetweenCents, deltaNeedCents: r.delta.needBetweenCents, status: r.after.standing.status, statusChanged: r.standingChanged, noEffect: r.noEffect });
    }
    return { ok: true, baseline: { minCents: base.cautious.minCents, minDay: base.cautious.minDay, paceCents: base.paceCents, status: base.standing.status, needBetweenCents: base.needBetweenCents }, rows };
  };

  /* ---------- recommendations when the plan runs short (every number is a re-run of the forecast) ---------- */
  const usd0 = c => (c < 0 ? '\u2212$' : '$') + Math.round(Math.abs(c) / 100).toLocaleString('en-US');
  const weeklyOf = monthlyCents => Math.round(monthlyCents * 7 / DAYS_PER_MONTH);
  E.semesterRecommendations = function (plan, T, snap) {
    snap = snap || E.snapshot(plan, T);
    if (!snap.ok) return { ok: false, needed: false, items: [] };
    const C = plan.account.cushionCents, q0 = quick(plan, T), st = standingOf(plan, T, snap, E.trust(plan, T, snap));
    if (!q0 || st.status === 'on_track' || st.status === 'needs_info') return { ok: true, needed: false, status: st.status, items: [], note: st.status === 'on_track' ? 'Nothing to fix: your plan stays above your cushion through the end of the term.' : '' };
    const MARGIN = st.status === 'tight' ? 5000 : 0, shortC = Math.max(0, C + MARGIN - q0.cautious.planned.minCents);
    const brief = q => ({ cautiousMinCents: q.cautious.planned.minCents, cautiousMinDay: q.cautious.planned.minDay, cautiousEndCents: q.cautious.planned.endCents, expectedMinCents: q.expected.planned.minCents, expectedEndCents: q.expected.planned.endCents, shortCents: Math.max(0, q.C + MARGIN - q.cautious.planned.minCents) });
    const before = brief(q0), items = [];
    const mkRec = (o, q) => Object.assign({ before, after: brief(q), fullFix: fixesIt(q, MARGIN) }, o);
    const eff = E.effectiveBudgets(plan, T, snap.base), flex = eff.filter(b => b.kind === 'flexible' && b.monthlyCents > 0), flexTotal = E.sum(flex, b => b.monthlyCents);
    const commitsShort = q0.cautious.commit.minCents < C;

    // 1. discretionary spending: the smallest cut (in 5% steps) that keeps the cautious view above the cushion
    if (flex.length && !commitsShort) {
      let found = null, foundQ = null;
      for (let pct = 5; pct <= 100; pct += 5) { const r = E.applyChange(plan, { type: 'cutFlex', pct, today: T }), q = quick(r.plan, T); if (q && fixesIt(q, MARGIN)) { found = { pct, plan: r.plan }; foundQ = q; break; } }
      const use = found && found.pct <= 50 ? found : null, pct = use ? use.pct : 30;
      const r = use ? use.plan : E.applyChange(plan, { type: 'cutFlex', pct, today: T }).plan, q = use ? foundQ : quick(r, T), eff2 = E.effectiveBudgets(r, T);
      const changes = flex.map(b => { const n = eff2.find(x => x.category === b.category); return { category: b.category, fromCents: b.monthlyCents, toCents: n ? n.monthlyCents : b.monthlyCents }; }).filter(c => c.toCents !== c.fromCents);
      const cutMonthly = E.sum(changes, c => c.fromCents - c.toCents), weekly = weeklyOf(cutMonthly), fix = fixesIt(q, MARGIN);
      items.push(mkRec({ id: 'trimFlex', kind: 'trimFlex', rank: pct <= 30 ? 1 : 4, title: 'Spend about ' + usd0(Math.max(100, Math.round(weekly / 100) * 100)) + ' less per week on discretionary spending',
        detail: 'Your discretionary budgets add up to ' + fmt(flexTotal) + ' a month. Trimming them by ' + pct + '% (to ' + fmt(flexTotal - cutMonthly) + ' a month, about ' + usd0(Math.round(weekly / 100) * 100) + ' less each week) ' + (fix ? 'keeps your lowest balance at ' + fmt(q.cautious.planned.minCents) + ', ' + (MARGIN ? fmt(q.cautious.planned.minCents - C) + ' above your ' + fmt(C) + ' cushion' : 'above your ' + fmt(C) + ' cushion') + ', even in the cautious view.' : 'raises your lowest balance to ' + fmt(q.cautious.planned.minCents) + ', but it is still ' + fmt(Math.max(0, C + MARGIN - q.cautious.planned.minCents)) + ' ' + (MARGIN && q.cautious.planned.minCents >= C ? 'short of the $50 of slack we aimed for' : 'below your cushion') + ', so this alone is not enough.'),
        steps: changes.map(c => c.category + ': ' + fmt(c.fromCents) + ' to ' + fmt(c.toCents) + ' a month'), large: pct > 30, note: pct > 30 ? 'That is a big cut (' + pct + '% of your discretionary budget). It only touches dining out, fun, shopping and similar. Rent, groceries and other essentials are never cut.' : 'Only discretionary categories change. Rent, groceries and other essentials are never cut.',
        apply: { type: 'cutFlex', changes: changes.map(c => ({ category: c.category, toCents: c.toCents })), pct }, actionLabel: 'Change my approved budgets', pct, weeklyCents: weekly, monthlyCents: cutMonthly }, q));
    }

    // 2. postpone a nonessential one-time purchase
    for (const o of postponable(plan, T).slice(0, 3)) {
      let best = null;
      for (const days of [7, 14, 21, 30, 45, 60]) { const r = E.applyChange(plan, { type: 'delayOneTime', id: o.id, days, today: T }), q = quick(r.plan, T); if (!q) continue; const fix = fixesIt(q, MARGIN); if (fix) { best = { days, q, fix }; break; } if (!best || q.cautious.planned.minCents > best.q.cautious.planned.minCents) best = { days, q, fix }; }
      if (!best || best.q.cautious.planned.minCents <= q0.cautious.planned.minCents) continue;
      const to = D.parse(o.schedule.anchor) + best.days, H = q0.endDay, beyond = to > H;
      items.push(mkRec({ id: 'postpone_' + o.id, kind: 'postpone', rank: 2, title: 'Move "' + o.name + '" from ' + label(D.parse(o.schedule.anchor)) + ' to ' + label(to),
        detail: 'Paying ' + fmt(o.amountCents) + ' ' + plural(best.days, 'day') + ' later ' + (best.fix ? 'keeps your lowest balance at ' + fmt(best.q.cautious.planned.minCents) + ', above your cushion.' : 'raises your lowest balance to ' + fmt(best.q.cautious.planned.minCents) + ', but not all the way to your cushion.') + (beyond ? ' It would then fall after the term ends, so it adds to what you need between terms.' : ''),
        steps: [o.name + ': ' + label(D.parse(o.schedule.anchor)) + ' to ' + label(to)], large: false, note: 'It is a nonessential expense you planned, so moving it does not touch anything you must pay.', apply: { type: 'postpone', id: o.id, days: best.days }, actionLabel: 'Move this expense', days: best.days }, best.q));
    }

    // 3. savings contribution
    for (const g of plan.goals.filter(x => x.contribution && x.contribution.amountCents > 0).slice(0, 2)) {
      let best = null;
      for (const f of [0.5, 0]) { const p = E.clone(plan), gg = p.goals.find(x => x.id === g.id); gg.contribution = f === 0 ? null : Object.assign({}, gg.contribution, { amountCents: Math.round(gg.contribution.amountCents * f) }); const np = E.normalizePlan(p).plan, q = quick(np, T); if (!q) continue; const fix = fixesIt(q, MARGIN); if (fix || !best) { best = { f, q, fix }; if (fix) break; } }
      if (!best || best.q.cautious.planned.minCents <= q0.cautious.planned.minCents) continue;
      const to = Math.round(g.contribution.amountCents * best.f);
      items.push(mkRec({ id: 'goal_' + g.id, kind: 'goal', rank: 3, title: best.f === 0 ? 'Pause saving for "' + g.name + '" until the term ends' : 'Lower your saving for "' + g.name + '" from ' + fmt(g.contribution.amountCents) + ' to ' + fmt(to) + ' per payment',
        detail: (best.f === 0 ? 'Pausing it' : 'Halving it') + (best.fix ? ' keeps your lowest balance at ' + fmt(best.q.cautious.planned.minCents) + ', above your cushion.' : ' raises your lowest balance to ' + fmt(best.q.cautious.planned.minCents) + ', but not all the way to your cushion.'),
        steps: [g.name + ': ' + fmt(g.contribution.amountCents) + ' to ' + (to ? fmt(to) : '$0') + ' per payment'], large: false, note: 'Your saved balance stays; only the new transfers change.', apply: { type: 'goalContribution', id: g.id, amountCents: to }, actionLabel: 'Change this saving', factor: best.f }, best.q));
    }

    // 4. recurring costs that are not essential: review (never cancelled for you)
    const recurring = plan.obligations.filter(o => !o.essential && o.schedule && o.schedule.freq !== 'once' && o.amountCents > 0);
    if (recurring.length) {
      let p = plan; for (const o of recurring) p = E.applyChange(p, { type: 'cancelObligation', id: o.id, today: T }).plan;
      const q = quick(p, T);
      if (q && q.cautious.planned.minCents - q0.cautious.planned.minCents >= 500) {
        const monthly = E.sum(recurring, o => E.monthlyEquivalent(o.schedule, o.amountCents));
        items.push(mkRec({ id: 'review_recurring', kind: 'review', rank: 5, title: 'Review ' + recurring.map(o => o.name).slice(0, 3).join(', ') + (recurring.length > 3 ? ' and ' + (recurring.length - 3) + ' more' : ''),
          detail: 'These nonessential recurring costs total about ' + fmt(monthly) + ' a month. If you cancelled all of them, your lowest balance would be ' + fmt(q.cautious.planned.minCents) + ' instead of ' + fmt(q0.cautious.planned.minCents) + '.', steps: recurring.map(o => o.name + ': ' + fmt(o.amountCents) + ' (' + (o.schedule.freq === 'monthly' ? 'monthly' : o.schedule.freq) + ')'),
          large: false, note: 'Campus Compass will not cancel anything for you. Look at each one and decide.', apply: null, actionLabel: 'Review my bills', goto: { screen: 'optional', open: 'bills' }, monthlyCents: monthly }, q));
      }
    }
    items.sort((a, b) => (b.fullFix ? 1 : 0) - (a.fullFix ? 1 : 0) || a.rank - b.rank);

    // 5. no single step fixes it: show the realistic steps together, and be honest about what is left
    let together = null;
    if (!items.some(i => i.fullFix && i.apply)) {
      let p = plan; const steps = [], applies = [];
      for (const o of postponable(plan, T).slice(0, 3)) { const r = E.applyChange(p, { type: 'delayOneTime', id: o.id, days: 30, today: T }); p = r.plan; steps.push('Move "' + o.name + '" 30 days later'); applies.push({ type: 'postpone', id: o.id, days: 30 }); }
      if (flex.length) { const r = E.applyChange(p, { type: 'cutFlex', pct: 30, today: T }); const e2 = E.effectiveBudgets(r.plan, T), ch = flex.map(b => { const n = e2.find(x => x.category === b.category); return { category: b.category, toCents: n ? n.monthlyCents : b.monthlyCents, fromCents: b.monthlyCents }; }).filter(c => c.toCents !== c.fromCents); p = r.plan; steps.push('Trim discretionary spending by 30% (about ' + usd0(Math.round(weeklyOf(E.sum(ch, c => c.fromCents - c.toCents)) / 100) * 100) + ' less per week)'); applies.push({ type: 'cutFlex', changes: ch.map(c => ({ category: c.category, toCents: c.toCents })), pct: 30 }); }
      for (const g of plan.goals.filter(x => x.contribution && x.contribution.amountCents > 0).slice(0, 2)) { const pp = E.clone(p); pp.goals.find(x => x.id === g.id).contribution = null; p = E.normalizePlan(pp).plan; steps.push('Pause saving for "' + g.name + '"'); applies.push({ type: 'goalContribution', id: g.id, amountCents: 0 }); }
      const q = steps.length ? quick(p, T) : null;
      if (q && steps.length >= 2 && q.cautious.planned.minCents > q0.cautious.planned.minCents) {
        const left = Math.max(0, C + MARGIN - q.cautious.planned.minCents);
        together = mkRec({ id: 'together', kind: 'together', rank: 0, title: left === 0 ? 'Together, these steps close the gap' : 'These steps help, but they do not close the gap on their own',
          detail: left === 0 ? 'Doing all of them keeps your lowest balance at ' + fmt(q.cautious.planned.minCents) + ', above your cushion.' : 'Doing all of them raises your lowest balance to ' + fmt(q.cautious.planned.minCents) + ', still ' + fmt(left) + ' below your ' + fmt(C) + ' cushion. Closing the rest would take about ' + fmt(left) + ' more income before ' + label(q.cautious.planned.minDay) + ', a bigger refund or a lower bill. We will not suggest cutting essentials to make up the difference.',
          steps, large: false, note: 'Each step changes only discretionary spending, planned nonessential purchases or savings.', apply: { type: 'bundle', steps: applies }, actionLabel: 'Apply all of these', leftCents: left, needsIncomeCents: left, byDay: q.cautious.planned.minDay }, q);
      }
    }
    const noFix = !items.some(i => i.fullFix) && !(together && together.fullFix), bestLeft = Math.min(shortC, ...items.map(i => i.after.shortCents), together ? together.after.shortCents : Infinity);
    return { ok: true, needed: true, status: st.status, shortCents: shortC, commitsShort, items, together, noFix, remainder: noFix ? { leftCents: bestLeft, byDay: q0.cautious.planned.minDay } : null,
      intro: commitsShort ? 'Bills and essentials alone drop below your cushion, so trimming spending money cannot fix this. Check that all of your income is entered, then consider the steps below.'
        : st.status === 'tight' ? 'You are not projected to run short, but your lowest balance is only ' + fmt(q0.cautious.planned.minCents - C) + ' above your cushion. These ideas would build about $50 of slack. Each was checked by re-running your forecast with only that change.'
        : 'You are projected to run ' + fmt(shortC) + ' short of your cushion (cautious view)' + (st.status === 'depends_on_income' ? '. In the expected view you stay above it, so this is about protecting yourself if pay is low or aid is late' : '') + '. Each idea below was checked by re-running your forecast with only that change.' };
  };

  // Turns an accepted recommendation into a new plan. Called only when the student presses its button.
  E.applyRecommendation = function (plan, T, apply) {
    if (!apply || typeof apply !== 'object') return fail(plan, 'There is nothing to apply.');
    const one = (p, a) => {
      if (a.type === 'cutFlex') { for (const c of a.changes || []) { const r = E.setBudget(p, c.category, Math.round(c.toCents)); if (!r.ok) return fail(p, 'That budget could not be changed.'); p = r.plan; } return { ok: true, plan: p }; }
      if (a.type === 'postpone') { const ob = p.obligations.find(o => o.id === a.id); if (!ob || !ob.schedule || ob.schedule.freq !== 'once') return fail(p, 'That expense no longer exists.'); const q = E.clone(p), o2 = q.obligations.find(o => o.id === a.id); o2.schedule.anchor = D.fmt(D.parse(o2.schedule.anchor) + Math.round(a.days)); return { ok: true, plan: E.normalizePlan(q).plan }; }
      if (a.type === 'goalContribution') { const g = p.goals.find(x => x.id === a.id); if (!g || !g.contribution) return fail(p, 'That saving no longer exists.'); const q = E.clone(p), g2 = q.goals.find(x => x.id === a.id); g2.contribution = a.amountCents > 0 ? Object.assign({}, g2.contribution, { amountCents: Math.round(a.amountCents) }) : null; return { ok: true, plan: E.normalizePlan(q).plan }; }
      return fail(p, 'Unknown change.');
    };
    if (apply.type === 'bundle') { let p = plan; for (const s of apply.steps || []) { const r = one(p, s); if (!r.ok) return fail(plan, r.error); p = r.plan; } return { ok: true, plan: p }; }
    return one(plan, apply);
  };

  // Semester's projected cash shortfall: how far the cautious balance falls below $0 between terms.
  // This is not the amount needed to preserve the cushion, and not the amount earmarked in a reserve.
  function projectedCashShortfall(plan, T) {
    const v = E.semesterView(plan, T);
    if (!v || !v.ok || !v.after || !v.after.ok) return { ok: false };
    const bridge = v.after.bridge, c = v.after.coverage;
    if (!bridge || !c) return { ok: true, available: false, termEndDay: v.endDay };
    return {
      ok: true, available: true, cents: c.belowZeroCents, termEndDay: v.endDay,
      endedBy: bridge.endedBy, aidName: bridge.aidName || '', aidDay: bridge.aidDay,
      needCents: c.needCents, appliedReserveCents: v.after.appliedReserveCents
    };
  }

  // One Today warning when the cautious planned forecast falls below the cushion.
  // The recommendation is the same forecast-tested flex cut Semester already offers, and only when that cut keeps the cushion.
  // The between-semester result is that cut applied to a copy. The student's plan is not modified.
  E.todayShortfall = function (plan, T) {
    const snap = E.snapshot(plan, T);
    const health = E.planHealth(plan, T, snap);
    if (!health.ok) return { ok: false, show: false };
    if (health.okCushion) return { ok: true, show: false, lowCents: health.minCents, lowDay: health.minDay, cushionCents: health.cushionCents, recommendation: null };
    const fc = snap.ok && snap.cautious.planned;
    const gaps = fc && fc.ok ? rentGaps(fc, T, health.cushionCents) : [];
    const rent = gaps.find(r => r.lowestDay === health.minDay) || null;
    const payday = rent && rent.nextPay ? { name: rent.nextPay.name, day: rent.nextPay.day, daysBefore: rent.nextPay.day - health.minDay } : null;
    const so = E.safetyOutlook(plan, { today: T, scenario: 'cautious' });
    const gapCents = so && so.ok ? so.gapCents : 0;
    const recs = E.semesterRecommendations(plan, T, snap);
    let recommendation = null;
    if (recs.ok && recs.needed && !recs.commitsShort) {
      const flex = (recs.items || []).find(i => i.kind === 'trimFlex' && i.fullFix && i.apply && i.after && i.after.cautiousMinCents >= health.cushionCents);
      if (flex && flex.weeklyCents > 0) {
        const before = projectedCashShortfall(plan, T);
        const applied = E.applyRecommendation(plan, T, flex.apply);
        const after = applied.ok ? projectedCashShortfall(applied.plan, T) : { ok: false };
        const between = before.ok && after.ok && before.available && after.available
          ? { available: true, beforeCents: before.cents, afterCents: after.cents, termEndDay: before.termEndDay, endedBy: after.endedBy, aidName: after.aidName, aidDay: after.aidDay, needCents: after.needCents, appliedReserveCents: after.appliedReserveCents }
          : { available: false, termEndDay: before.ok ? before.termEndDay : null };
        recommendation = {
          supported: true, kind: 'trimFlex',
          aboutWeeklyCents: Math.max(100, Math.round(flex.weeklyCents / 100) * 100),
          afterMinCents: flex.after.cautiousMinCents, afterMinDay: flex.after.cautiousMinDay,
          protectsCushion: true,
          aboveCushionCents: flex.after.cautiousMinCents - health.cushionCents,
          pct: flex.pct, steps: (flex.steps || []).slice(), note: flex.note || '',
          between
        };
      }
    }
    return {
      ok: true, show: true, lowCents: health.minCents, lowDay: health.minDay, cushionCents: health.cushionCents,
      rent: rent ? { name: rent.name, amountCents: rent.amountCents, day: rent.day } : null,
      payday: payday && payday.daysBefore > 0 ? payday : null,
      gapCents, recommendation
    };
  };
})(CCE);

;
/* ===== engine/14-goals.js ===== */
/* =========================================================================
   14 goals — what is saved for each goal, and which savings are spoken for
   -------------------------------------------------------------------------
   GOAL PROGRESS (what the student has actually saved for a goal) is
       savedCents        the amount the student stated, at the end of savedAsOf
     + linked transfers  transactions the student confirmed for this goal (tx.goalId), dated after that
   Nothing else moves it. A scheduled contribution never counts as saved until the student confirms it
   (E.resolveOccurrence 'paid' creates a linked transfer) or links a real transfer row to the goal
   (E.confirmGoalContribution). A check-in never changes it.

   CASH PLANNING is a separate question and keeps the forecast's cautious rule: a scheduled transfer
   since the last verified balance is assumed to have left checking. That assumption is about cash only;
   it is never shown as goal progress.

   SAVINGS ACCOUNT. Savings that belong to goals are ALLOCATED. Only the unallocated rest can ever be
   treated as spendable (and only if the student opted in with account.savingsSpendable). The safety
   cushion is a checking-account floor and is never counted as goal savings, and goal savings never count
   toward the cushion.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const fail = (plan, error) => ({ ok: false, error, plan });

  // Is this transaction a confirmed movement for goal g that is NOT already inside g.savedCents?
  const afterStatement = (g, t) => {
    if (!g.savedAsOf) return true;
    const sd = D.parse(g.savedAsOf), td = D.parse(t.date);
    return td > sd || (td === sd && t.seq > (g.savedSeq || 0));
  };

  E.goalProgress = function (plan, g) {
    const rows = [];
    let linked = 0;
    for (const t of E.activeTxs(plan)) {
      if (t.goalId !== g.id || t.flow !== 'transfer' || !afterStatement(g, t)) continue;
      linked += -t.amountCents;
      rows.push({ txId: t.id, date: t.date, amountCents: -t.amountCents, desc: t.desc });
    }
    const progress = Math.max(0, g.savedCents + linked);
    return {
      goalId: g.id, savedCents: g.savedCents, savedAsOf: g.savedAsOf || '', linkedCents: linked, progressCents: progress, targetCents: g.targetCents,
      remainingCents: g.targetCents > 0 ? Math.max(0, g.targetCents - progress) : null, reached: g.targetCents > 0 && progress >= g.targetCents, linked: rows
    };
  };

  // The savings balance NOW = the stated balance (end of account.savingsAsOf) + goal-linked transfers recorded after it.
  // Only goal-linked transfers are known to land in savings; other transfers could go anywhere, so they are never added (that would
  // overstate what is spendable). Goal progress includes the same linked transfers, so a contribution recorded after both statements
  // adds to savings and to allocated savings equally and leaves the unallocated amount unchanged.
  // With no savingsAsOf (older plans) the stated balance is taken as current, exactly as before.
  E.savingsSummary = function (plan) {
    const a = plan.account, stated = a.savingsCents || 0;
    let since = 0;
    if (a.savingsAsOf) {
      const sd = D.parse(a.savingsAsOf);
      for (const t of E.activeTxs(plan)) {
        if (!t.goalId || t.flow !== 'transfer') continue;
        const td = D.parse(t.date);
        if (td > sd || (td === sd && t.seq > (a.savingsSeq || 0))) since += -t.amountCents;
      }
    }
    const savings = Math.max(0, stated + since), allocated = E.sum(plan.goals, g => E.goalProgress(plan, g).progressCents);
    const unallocated = Math.max(0, savings - allocated);
    return { savingsCents: stated, savingsAsOf: a.savingsAsOf || '', linkedSinceCents: since, savingsNowCents: savings, allocatedCents: allocated, unallocatedCents: unallocated, overAllocatedCents: Math.max(0, allocated - savings), spendableCents: a.savingsSpendable ? unallocated : 0 };
  };

  // The student states the savings-account balance right now. Returns a new plan.
  E.setSavingsBalance = function (plan, cents, today) {
    const c = Math.round(Number(cents));
    if (!Number.isSafeInteger(c) || c < 0 || c > 1e9) return fail(plan, 'Enter an amount of $0 or more.');
    if (typeof today !== 'number') return fail(plan, 'Internal error: setting the savings balance needs today\'s date.');
    const p = E.clone(plan);
    p.account.savingsCents = c; p.account.savingsAsOf = D.fmt(today); p.account.savingsSeq = ++p.seq;
    return { ok: true, plan: p };
  };

  // Transfers out of checking that MIGHT be contributions to a goal, for the student to confirm. Never applied automatically.
  E.goalContributionCandidates = function (plan, T) {
    const goals = plan.goals.filter(g => g.contribution), dismissed = new Set(plan.dismissed || []), out = [];
    if (!goals.length) return out;
    for (const t of E.activeTxs(plan)) {
      if (t.goalId || t.flow !== 'transfer' || t.amountCents >= 0 || t.account !== 'checking') continue;
      const day = D.parse(t.date); if (typeof T === 'number' && day > T) continue;
      const amt = -t.amountCents;
      for (const g of goals) {
        if (!afterStatement(g, t) || dismissed.has('goaltx:' + t.id + ':' + g.id)) continue;
        const near = E.occurrences(g.contribution.schedule, day - 4, day + 4).length > 0;
        const ratio = Math.abs(amt - g.contribution.amountCents) / Math.max(1, g.contribution.amountCents);
        if (!(near && ratio <= 0.12) && !(ratio <= 0.02)) continue;
        out.push({ txId: t.id, goalId: g.id, goalName: g.name, date: t.date, amountCents: amt, desc: t.desc, onSchedule: near });
      }
    }
    return out.sort((a, b) => (a.date < b.date ? -1 : 1));
  };

  // The student confirms (goalId) or un-confirms ('') that a transfer row was money saved for a goal. Returns a new plan.
  E.confirmGoalContribution = function (plan, txId, goalId) {
    const t = plan.transactions.find(x => x.id === txId);
    if (!t) return fail(plan, 'That transaction no longer exists.');
    if (goalId && !plan.goals.some(g => g.id === goalId)) return fail(plan, 'That goal no longer exists.');
    if (goalId && t.flow !== 'transfer') return fail(plan, 'Only a transfer between your own accounts can be money saved for a goal.');
    const p = E.clone(plan);
    p.transactions.find(x => x.id === txId).goalId = goalId || '';
    return { ok: true, plan: p };
  };

  // The student states how much is saved for a goal right now. Linked transfers recorded before this moment are inside the new amount.
  E.setGoalSaved = function (plan, goalId, savedCents, today) {
    const c = Math.round(Number(savedCents));
    if (!Number.isSafeInteger(c) || c < 0 || c > 1e9) return fail(plan, 'Enter an amount of $0 or more.');
    if (typeof today !== 'number') return fail(plan, 'Internal error: setting a saved amount needs today\'s date.');
    const p = E.clone(plan), g = p.goals.find(x => x.id === goalId);
    if (!g) return fail(plan, 'That goal no longer exists.');
    g.savedCents = c; g.savedAsOf = D.fmt(today); g.savedSeq = ++p.seq;
    return { ok: true, plan: p };
  };

  /* =========================================================================
     WHAT EACH GOAL NEEDS, WHAT THE PLAN CAN AFFORD, AND WHAT THE STUDENT COULD CHANGE
     -------------------------------------------------------------------------
     NEED (E.goalStatus). For one goal:
       still needed  = target − confirmed progress − transfers that match its schedule but are not confirmed yet
       transfers     = unconfirmed scheduled transfers on or before today (the cash forecast already counts them as moved)
                       + the goal's schedule dates after today, up to the deadline
       per transfer  = still needed / transfers, rounded UP to a whole dollar (the forecast trims the last one)
     The schedule is the goal's own contribution schedule; for a goal without one it is the student's payday (a regular job),
     otherwise weekly, and it starts tomorrow so nothing is assumed to have happened already.

     AFFORDABLE (E.goalAllocation). Planned discretionary spending is kept exactly as it is: it is never lowered to fund a goal.
     Let s(k) = projected end-of-day balance on day k − cushion (− the end-of-term reserve on the last day), from the full daily
     forecast with planned spending. A plan is SAFE when s(k) ≥ 0 on every day. Goals are funded one at a time, in the student's
     priority order (earlier deadline breaks a tie). Each gets the largest contribution, up to what it needs, for which the
     RE-RUN forecast is still SAFE. A contribution is never recommended if any day would fall below the cushion. If the plan is
     already below the cushion, nothing is recommended: that is a shortfall to fix, not a feasible goal plan. The student may
     still apply an unsafe hypothetical (`acceptShortfall`), but it is labelled as risk, never as feasible or recommended.
     The first guess comes from one formula, the smallest over days of (room left) / (transfers by that day); the forecast then
     confirms it. Room left after that is not assigned: it is the student's to give to a goal or to spending.

     Goal savings are outflows to savings and never discretionary money. The cushion is a checking floor: an emergency goal never
     counts toward it and it never counts as goal progress.

     STATUS of each goal:
       feasible       reaches the target by the deadline AND the cautious forecast stays at or above the cushion
       needs_changes  not under the plan as it is, but it can be, if the student chooses a change (alternatives)
       unreachable    not even with every other goal paused and discretionary spending at the student's weekly minimum
                      (or the plan is already below the cushion, so no safe contribution exists)
     Nothing here changes the plan. E.applyGoalPlan is the only function that writes a goal allocation, and it is only called when
     the student accepts one.
     ========================================================================= */
  const URGENT_DAYS = 28, FLOOR_SUGGEST_PCT = 50, DOLLAR = 100, PROJECT_DAYS = 1100;
  E.GOAL_URGENT_DAYS = URGENT_DAYS; E.DISCRETIONARY_FLOOR_SUGGEST_PCT = FLOOR_SUGGEST_PCT;
  const fmt = E.fmt, label = D.label;
  const toWeekly = m => Math.round(m * 7 / 30.4375), toMonthly = w => Math.round(w * 30.4375 / 7);
  const ceilTo = (c, s) => Math.ceil(c / s) * s, floorTo = (c, s) => Math.floor(c / s) * s;
  const dueOf = g => D.parse(g.dueDate);
  const plural = (n, w) => n + ' ' + w + (n === 1 ? '' : 's');

  // Funding order: the student's priority (1 = first), then the earlier deadline, then the order the goals were entered. `ids` overrides it.
  E.goalOrder = function (plan, ids) {
    const at = {}; plan.goals.forEach((g, i) => { at[g.id] = i; });
    const dueKey = g => { const d = dueOf(g); return d === null ? Infinity : d; };
    const pos = id => { const k = ids ? ids.indexOf(id) : -1; return k < 0 ? Infinity : k; };
    return plan.goals.slice().sort((a, b) => {
      if (ids) { const x = pos(a.id), y = pos(b.id); if (x !== y) return x < y ? -1 : 1; }
      if (a.priority !== b.priority) return a.priority - b.priority;
      const x = dueKey(a), y = dueKey(b); if (x !== y) return x < y ? -1 : 1;
      return at[a.id] - at[b.id];
    });
  };

  // When a goal without its own savings schedule would get its transfers: on paydays of a regular job, otherwise weekly. Starts tomorrow.
  E.suggestedGoalSchedule = function (plan, T) {
    const start = D.fmt(T + 1);
    const pay = plan.incomes.find(i => i.schedule && i.amountCents > 0 && i.reliability !== 'uncertain' && ['job', 'workstudy'].indexOf(i.type) >= 0 &&
      ['weekly', 'biweekly', 'semimonthly', 'monthly'].indexOf(i.schedule.freq) >= 0 && E.occurrences(i.schedule, T + 1, T + 45).length > 0);
    if (pay) {
      const s = E.clone(pay.schedule), st = D.parse(s.start);
      s.start = st !== null && st > T + 1 ? s.start : start;
      return { schedule: s, basis: 'payday', incomeName: pay.name };
    }
    return { schedule: { freq: 'weekly', anchor: D.fmt(D.weekStart(T, plan.settings.weekStartsOn) + 7), start }, basis: 'weekly', incomeName: '' };
  };

  /* ---------- discretionary spending and the student's weekly minimum ---------- */
  E.discretionaryPlan = function (plan, T, base) {
    const rows = E.effectiveBudgets(plan, T, base).filter(b => b.kind === 'flexible');
    const monthly = E.sum(rows, b => b.monthlyCents), weekly = toWeekly(monthly), set = plan.settings.discretionaryFloorWeeklyCents;
    const suggested = floorTo(Math.round(weekly * FLOOR_SUGGEST_PCT / 100), 500), floor = set == null ? suggested : set;
    return {
      plannedMonthlyCents: monthly, plannedWeeklyCents: weekly, categories: rows.map(b => ({ category: b.category, monthlyCents: b.monthlyCents, basis: b.basis })),
      suggestedFloorWeeklyCents: suggested, floorWeeklyCents: floor, floorSource: set == null ? 'suggested' : 'student', effectiveFloorWeeklyCents: Math.min(floor, weekly),
      explain: 'Your planned discretionary spending is about ' + fmt(weekly) + ' a week, and Campus Compass never lowers it to fund a goal. ' +
        (set == null ? 'The suggested weekly minimum is ' + FLOOR_SUGGEST_PCT + '% of it (' + fmt(suggested) + '); you can change it.' : 'Your weekly minimum is ' + fmt(set) + '.') +
        ' Spending is only lowered toward that minimum if you choose to.'
    };
  };
  // The student sets (or clears, with null) their weekly minimum. Returns a new plan.
  E.setDiscretionaryFloor = function (plan, weeklyCents) {
    const p = E.clone(plan);
    if (weeklyCents === null) { p.settings.discretionaryFloorWeeklyCents = null; return { ok: true, plan: p }; }
    const c = Math.round(Number(weeklyCents));
    if (!Number.isSafeInteger(c) || c < 0 || c > 1e9) return fail(plan, 'Enter an amount of $0 or more.');
    p.settings.discretionaryFloorWeeklyCents = c;
    return { ok: true, plan: p };
  };
  // Sets the discretionary categories so they add up to weeklyCents a week, keeping their proportions. Mutates p (a copy).
  function setDiscretionary(p, T, base, weeklyCents) {
    const info = E.discretionaryPlan(p, T, base);
    if (weeklyCents === info.plannedWeeklyCents || !info.categories.length) return;
    const w = {}; for (const c of info.categories) w[c.category] = c.monthlyCents;
    const alloc = E.allocate(toMonthly(weeklyCents), w);
    for (const c of info.categories) {
      let b = p.budgets.find(x => x.category === c.category);
      if (!b) { b = { category: c.category, approvedCents: null, recommendedCents: null, source: 'student' }; p.budgets.push(b); }
      b.approvedCents = alloc[c.category] || 0; b.source = 'student';
    }
  }

  // A goal plan: { goals: [{ id, amountCents (0 = no transfers), schedule?, dueDate?, priority? }], discretionary?: { weeklyCents } }.
  // Writes it to a COPY of the plan. Shared by the allocation, the what-if engine and E.applyGoalPlan, so what is checked is what is applied.
  E.writeGoalChoice = function (plan, choice, T, base) {
    const p = E.clone(plan);
    for (const c of (choice && choice.goals) || []) {
      const g = p.goals.find(x => x.id === c.id); if (!g) continue;
      if (c.dueDate !== undefined) g.dueDate = c.dueDate || '';
      if (c.priority !== undefined) g.priority = c.priority;
      if (c.amountCents !== undefined) {
        const a = Math.max(0, Math.round(c.amountCents));
        if (a <= 0) g.contribution = null;
        else {
          const sch = c.schedule || (g.contribution && g.contribution.schedule) || (typeof T === 'number' ? E.suggestedGoalSchedule(plan, T).schedule : null);
          if (sch) g.contribution = { amountCents: a, schedule: E.clone(sch) };
        }
      }
    }
    if (choice && choice.discretionary && choice.discretionary.weeklyCents != null) setDiscretionary(p, T, base, Math.max(0, Math.round(choice.discretionary.weeklyCents)));
    return E.normalizePlan(p).plan;
  };

  /* ---------- what each goal needs ---------- */
  function statusRow(plan, g, T, fc, H, txById, rank) {
    const pr = E.goalProgress(plan, g), due = dueOf(g), ws = plan.settings.weekStartsOn;
    const own = g.contribution ? { schedule: g.contribution.schedule, basis: 'yours', incomeName: '' } : E.suggestedGoalSchedule(plan, T);
    const sch = own.schedule, inForecast = !!(g.contribution && g.status === 'active' && fc && fc.ok);
    // what the cash forecast already moves for this goal: scheduled transfers on or before today that are not confirmed, and transfers that match the schedule
    let pastCount = 0, pastCents = 0, matchedCents = 0; const matchedNom = new Set();
    if (inForecast) for (const o of fc.occurrences) {
      if (o.type !== 'savings' || o.id !== g.id) continue;
      if (o.txId) { matchedNom.add(o.nominal); const t = txById[o.txId]; if (t && t.goalId !== g.id) matchedCents += -t.amountCents; }
      else if (o.nominal <= T && o.counted) { pastCount++; pastCents += o.amountCents; }
    }
    const remaining = pr.remainingCents, need = remaining == null ? null : Math.max(0, remaining - matchedCents);
    const future = due !== null && due > T ? E.occurrences(sch, T + 1, due).filter(o => !matchedNom.has(o.nominal)) : [];
    const n = pastCount + future.length;
    let problem = null;
    if (g.status !== 'active') problem = g.status;
    else if (g.targetCents <= 0) problem = 'no_target';
    else if (pr.reached) problem = 'reached';
    else if (need === 0) problem = 'awaiting_confirmation';
    else if (due === null) problem = 'no_deadline';
    else if (due <= T) problem = 'deadline_passed';
    else if (n === 0) problem = 'no_dates_left';
    let required = null;
    if (need > 0 && due !== null && due > T && n > 0) {
      const per = ceilTo(Math.ceil(need / n), DOLLAR), list = [];
      let left = need;
      if (pastCount) { const a = Math.min(left, per * pastCount); list.push({ day: T, count: pastCount, amountCents: a, earlier: true }); left -= a; }
      for (const o of future) { if (left <= 0) break; const a = Math.min(left, per); list.push({ day: o.day, count: 1, amountCents: a, earlier: false }); left -= a; }
      const byMonth = [];
      for (const c of list) { const k = D.monthKey(c.day); let m = byMonth[byMonth.length - 1]; if (!m || m.key !== k) { m = { key: k, contributions: 0, amountCents: 0 }; byMonth.push(m); } m.contributions += c.count; m.amountCents += c.amountCents; }
      const weeks = E.calendarPeriods(T, due, 'week', ws).length, months = E.calendarPeriods(T, due, 'month').length;
      required = { perContributionCents: per, contributions: n, earlierUnconfirmed: pastCount, firstDay: list.length ? list[0].day : T, lastDay: list.length ? list[list.length - 1].day : T,
        weeks, months, weeklyCents: Math.ceil(need / weeks), monthlyCents: Math.ceil(need / months), contributionsList: list, byMonth };
    }
    const cur = g.contribution && g.status === 'active' ? g.contribution.amountCents : 0;
    const completionDay = need === null ? null : projectCompletion(sch, T, need, pastCents, cur, matchedNom);
    const onTrack = problem === 'reached' || problem === 'awaiting_confirmation' || (g.status === 'active' && completionDay !== null && (due === null || completionDay <= due));
    return {
      goalId: g.id, name: g.name, type: g.type, priority: g.priority, rank, goalStatus: g.status, targetCents: g.targetCents, confirmedCents: pr.progressCents, remainingCents: remaining,
      unconfirmedMatchedCents: matchedCents, unconfirmedScheduledCents: pastCents, earlierScheduled: pastCount, needCents: need, dueDate: g.dueDate || '', dueDay: due, daysLeft: due === null ? null : due - T,
      urgent: due !== null && due > T && due - T <= URGENT_DAYS && need > 0, afterTerm: due !== null && due > H, schedule: sch, scheduleBasis: own.basis, scheduleIncome: own.incomeName,
      currentContributionCents: cur, required, completionDay, onTrack, problem, reached: pr.reached, _matchedNom: matchedNom
    };
  }
  // The day the cumulative transfers (already counted + `per` on each later schedule date) first reach `need`. null if they never do (within ~3 years).
  function projectCompletion(sch, T, need, counted, per, skip) {
    if (need <= 0 || counted >= need) return T;
    if (!(per > 0)) return null;
    let cum = counted;
    for (const o of E.occurrences(sch, T + 1, T + PROJECT_DAYS)) { if (skip && skip.has(o.nominal)) continue; cum += per; if (cum >= need) return o.day; }
    return null;
  }

  // opts: { fc (a forecast of this plan, to reuse) }
  E.goalStatus = function (plan, T, opts) {
    opts = opts || {};
    const fc = opts.fc || E.forecast(plan, { today: T, scenario: 'cautious', flex: 'none' });
    const H = fc && fc.ok ? fc.endDay : E.horizonInfo(plan, T).endDay;
    const txById = {}; for (const t of plan.transactions) txById[t.id] = t;
    const rows = E.goalOrder(plan).map((g, i) => statusRow(plan, g, T, fc, H, txById, i));
    const act = rows.filter(r => r.goalStatus === 'active' && r.dueDay !== null && r.needCents > 0), conflicts = [];
    for (let i = 0; i < act.length; i++) for (let j = i + 1; j < act.length; j++) {
      if (act[i].dueDay <= act[j].dueDay) continue;
      conflicts.push({ firstId: act[i].goalId, laterId: act[j].goalId,
        text: '"' + act[i].name + '" is ranked above "' + act[j].name + '", but "' + act[j].name + '" is due sooner (' + label(act[j].dueDay) + ' vs ' + label(act[i].dueDay) + '). "' + act[i].name + '" is funded first, and "' + act[j].name + '" gets what is left.' });
    }
    for (const r of rows) delete r._matchedNom;
    return { ok: true, today: T, endDay: H, goals: rows, conflicts, urgent: rows.filter(r => r.urgent).map(r => r.goalId) };
  };

  /* ---------- the allocation ---------- */
  function context(plan, T, scenario) {
    const det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det);
    const fcNone = E.forecast(plan, { today: T, scenario, flex: 'none', det, base });
    if (!fcNone.ok) return null;
    const R = E.endReserve(plan, { today: T, scenario, fc: fcNone, det, base }).totalCents;
    return { T, scenario, det, base, C: plan.account.cushionCents, R, fcNone, runs: 0 };
  }
  const plannedFc = (ctx, p) => { ctx.runs++; return E.forecast(p, { today: ctx.T, scenario: ctx.scenario, flex: 'budget', det: ctx.det, base: ctx.base }); };
  const slackOf = (ctx, fc) => fc.days.map((d, i) => d.bal - ctx.C - (i === fc.N ? ctx.R : 0));
  const firstShort = (s, s0) => { for (let i = 0; i < s.length; i++) if (s[i] < Math.min(0, s0[i])) return i; return -1; };
  const firstUnsafe = s => { for (let i = 0; i < s.length; i++) if (s[i] < 0) return i; return -1; };
  const isSafe = s => firstUnsafe(s) < 0;
  // Cash the forecast moves to goal g, not already in its confirmed progress, on or before `until`.
  function movedFor(fc, plan, gid, until) {
    let s = 0;
    for (const o of fc.occurrences) {
      if (o.type !== 'savings' || o.id !== gid || o.day > until) continue;
      if (o.txId) { const t = plan.transactions.find(x => x.id === o.txId); if (t && t.goalId !== gid) s += -t.amountCents; }
      else if (o.counted) s += o.amountCents;
    }
    return s;
  }

  // Read the proposed transfer dates and deadline result from the same cautious forecast used by allocation.
  E.goalTransferPreview = function (plan, T, goalId, choice) {
    const ctx = context(plan, T, 'cautious');
    if (!ctx) return null;
    const proposed = E.writeGoalChoice(plan, choice, T, ctx.base), goal = proposed.goals.find(g => g.id === goalId);
    if (!goal) return null;
    const fc = plannedFc(ctx, proposed), dueDay = dueOf(goal);
    const remaining = E.goalProgress(proposed, goal).remainingCents;
    return {
      dueDay, endDay: fc.endDay,
      meetsDeadline: dueDay == null || dueDay > fc.endDay || remaining == null ? null : movedFor(fc, proposed, goalId, dueDay) >= remaining,
      transfers: fc.occurrences.filter(o => o.type === 'savings' && o.id === goalId && o.counted && !o.txId)
        .map(o => ({ day: o.day, amountCents: o.amountCents }))
    };
  };
  const eligibleRow = r => r.goalStatus === 'active' && r.targetCents > 0 && !r.reached && r.problem !== 'awaiting_confirmation' && (!!r.required || r.currentContributionCents > 0);
  const targetOf = r => r.required ? r.required.perContributionCents : r.currentContributionCents;

  // The largest per-transfer amount the formula allows: transfers by day k are min(x · c(k), need), and must fit in the room left on day k.
  function formulaMax(ctx, r, sch, s, matchedNom) {
    if (!isSafe(s)) return 0;          // already below the cushion: adding transfers cannot make the plan safe
    const T = ctx.T, N = s.length - 1, c = new Array(N + 1).fill(0);
    let k0 = r.scheduleBasis === 'yours' ? r.earlierScheduled : 0;
    for (const o of E.occurrences(sch, T + 1, T + N)) if (!matchedNom || !matchedNom.has(o.nominal)) c[o.day - T]++;
    let best = Infinity;
    for (let k = 0; k <= N; k++) {
      k0 += c[k]; if (k0 === 0) continue;
      const avail = s[k];
      if (avail >= r.needCents) continue;
      if (avail < 0) return 0;
      best = Math.min(best, Math.floor(avail / k0));
    }
    return best;
  }

  // Fund `order` one goal at a time. `eligible` is every goal this allocation decides (they all start with no transfers).
  function fundGoals(plan, ctx, eligible, order, rows) {
    let cur = E.writeGoalChoice(plan, { goals: eligible.map(r => ({ id: r.goalId, amountCents: 0 })) }, ctx.T, ctx.base);
    const fc0 = plannedFc(ctx, cur), s0 = slackOf(ctx, fc0);
    let fc = fc0, s = s0;
    const amounts = {};
    for (const r of order) {
      const target = targetOf(r);
      amounts[r.goalId] = 0;
      if (!(target > 0)) continue;
      const guess = formulaMax(ctx, r, r.schedule, s, r._matchedNom);
      let x = guess >= target ? target : floorTo(guess, DOLLAR);
      const tryAmt = a => { const p = E.writeGoalChoice(cur, { goals: [{ id: r.goalId, amountCents: a, schedule: r.schedule }] }, ctx.T, ctx.base), f = plannedFc(ctx, p), sl = slackOf(ctx, f); return isSafe(sl) ? { p, f, sl } : null; };
      let hit = x > 0 ? tryAmt(x) : null;
      if (x > 0 && !hit) {            // the forecast found something the formula could not see: the largest whole-dollar amount below the guess that fits
        let lo = 0, hi = Math.floor((x - 1) / DOLLAR); x = 0;
        while (lo < hi) { const mid = Math.ceil((lo + hi) / 2), h = tryAmt(mid * DOLLAR); if (h) { lo = mid; hit = h; x = mid * DOLLAR; } else hi = mid - 1; }
      }
      if (hit && x > 0) { cur = hit.p; fc = hit.f; s = hit.sl; amounts[r.goalId] = x; }
    }
    return { plan: cur, fc, fc0, s0, s, amounts };
  }
  const fundedIn = (run, r, H) => {
    const x = run.amounts[r.goalId] || 0;
    if (!r.required) return x >= r.currentContributionCents;
    if (r.dueDay > H) return x >= r.required.perContributionCents;
    return movedFor(run.fc, run.plan, r.goalId, r.dueDay) >= r.remainingCents;
  };

  // opts: { scenario ('cautious' default), order: [goalIds] (overrides priority), overrides: [{ id, dueDate?, priority? }],
  //         discretionaryWeeklyCents (evaluate with lower discretionary spending: only for alternatives the student may choose),
  //         classify (default true), expected (default true: also run the expected scenario) }
  E.goalAllocation = function (plan, T, opts) {
    opts = opts || {};
    const scenario = opts.scenario || 'cautious', ctx = context(plan, T, scenario);
    if (!ctx) return { ok: false, error: 'no_balance' };
    const H = ctx.fcNone.endDay, disc = E.discretionaryPlan(plan, T, ctx.base);
    let usedWeekly = disc.plannedWeeklyCents, base = plan;
    const extra = {};
    if (opts.discretionaryWeeklyCents != null && opts.discretionaryWeeklyCents < disc.plannedWeeklyCents) {
      usedWeekly = Math.max(disc.effectiveFloorWeeklyCents, Math.round(opts.discretionaryWeeklyCents));
      extra.discretionary = { weeklyCents: usedWeekly };
    }
    if (opts.order) { const ord = E.goalOrder(plan, opts.order); extra.goals = ord.map((g, i) => ({ id: g.id, priority: Math.min(99, i + 1) })); }
    if (opts.overrides) { extra.goals = extra.goals || []; for (const o of opts.overrides) { const e = extra.goals.find(x => x.id === o.id); const v = {}; if (o.dueDate !== undefined) v.dueDate = o.dueDate; if (o.priority !== undefined) v.priority = o.priority; if (e) Object.assign(e, v); else extra.goals.push(Object.assign({ id: o.id }, v)); } }
    if (extra.goals || extra.discretionary) base = E.writeGoalChoice(plan, extra, T, ctx.base);
    const txById = {}; for (const t of base.transactions) txById[t.id] = t;
    const ordered = E.goalOrder(base, opts.order), rows = ordered.map((g, i) => statusRow(base, g, T, ctx.fcNone, H, txById, i));
    const eligible = rows.filter(eligibleRow);
    const run = fundGoals(base, ctx, eligible, eligible, rows);
    const curFc = plannedFc(ctx, base), currentShort = firstShort(slackOf(ctx, curFc), run.s0);

    // can a goal that is short be reached at all? Only this goal funded, discretionary spending at the student's weekly minimum.
    let floorPlan = null;
    const maxPossible = r => {
      if (!floorPlan) floorPlan = disc.effectiveFloorWeeklyCents < usedWeekly ? E.writeGoalChoice(base, { discretionary: { weeklyCents: disc.effectiveFloorWeeklyCents } }, T, ctx.base) : base;
      const m = fundGoals(floorPlan, ctx, eligible, [r], rows);
      return { cents: m.amounts[r.goalId] || 0, funded: fundedIn(m, r, H) };
    };
    const alone = r => { const m = fundGoals(base, ctx, eligible, [r], rows); return m.amounts[r.goalId] || 0; };

    const goals = rows.map(r => {
      const x = run.amounts[r.goalId], el = eligible.indexOf(r) >= 0;
      const o = { goalId: r.goalId, name: r.name, type: r.type, priority: r.priority, rank: r.rank, targetCents: r.targetCents, confirmedCents: r.confirmedCents, remainingCents: r.remainingCents,
        needCents: r.needCents, dueDate: r.dueDate, dueDay: r.dueDay, urgent: r.urgent, afterTerm: r.afterTerm, checkedThroughDay: H, schedule: r.schedule, scheduleBasis: r.scheduleBasis,
        requiredCents: r.required ? r.required.perContributionCents : null, required: r.required, currentContributionCents: r.currentContributionCents, recommendedCents: el ? x : r.currentContributionCents,
        status: '', funded: false, limitedByHigherPriority: false, standaloneCents: null, maxPossibleCents: null, completionDay: null, reason: '' };
      if (!el) {
        o.status = r.problem === 'reached' ? 'reached' : r.problem === 'awaiting_confirmation' ? 'reached_unconfirmed' : r.goalStatus !== 'active' ? r.goalStatus : r.problem === 'no_target' ? 'no_target' : r.problem === 'no_deadline' ? 'no_deadline' : 'unreachable';
        o.funded = o.status === 'reached';
        o.reason = o.status === 'reached' ? 'Reached: your confirmed savings cover the target.' : o.status === 'reached_unconfirmed' ? 'Transfers that look like contributions cover the rest. Confirm them to count them as saved.'
          : o.status === 'paused' ? 'Paused: no transfers are planned.' : o.status === 'done' ? 'Marked done.' : o.status === 'no_target' ? 'No target amount yet.'
          : o.status === 'no_deadline' ? 'No deadline and no transfers yet. Add a date and Campus Compass can work out what it needs.'
          : r.problem === 'deadline_passed' ? 'The deadline has passed. Choose a new date.' : 'There are no transfer dates left before the deadline. Choose a later date.';
        return o;
      }
      o.funded = fundedIn(run, r, H);
      o.completionDay = projectCompletion(r.schedule, T, r.needCents, x * (r.scheduleBasis === 'yours' ? r.earlierScheduled : 0), x, null);
      const runSafe = isSafe(run.s);
      if (!r.required) {
        o.status = r.problem === 'no_deadline' ? (o.funded && runSafe ? 'feasible' : 'needs_changes') : 'unreachable';
        o.reason = r.problem !== 'no_deadline' ? (r.problem === 'deadline_passed' ? 'The deadline has passed. Choose a new date.' : 'There are no transfer dates left before the deadline. Choose a later date.')
          : o.funded && runSafe ? 'No deadline. Your ' + fmt(r.currentContributionCents) + ' per transfer stays at or above your cushion.' : 'No deadline. Your plan can set aside ' + fmt(x) + ' per transfer, not the ' + fmt(r.currentContributionCents) + ' you chose.';
        return o;
      }
      const per = r.required.perContributionCents, dl = label(r.dueDay);
      if (o.funded && runSafe) {
        o.status = 'feasible';
        o.reason = fmt(per) + ' per transfer (' + plural(r.required.contributions, 'transfer') + ') reaches ' + fmt(r.targetCents) + ' by ' + dl + ' and keeps every day at or above your cushion. Your discretionary spending stays at ' + fmt(usedWeekly) + ' a week.';
      } else if (opts.classify === false) {
        o.status = 'short';
      } else {
        o.standaloneCents = alone(r);
        o.limitedByHigherPriority = o.standaloneCents > x;
        const mp = maxPossible(r);
        o.maxPossibleCents = mp.cents;
        o.status = mp.funded ? 'needs_changes' : 'unreachable';
        o.reason = o.status === 'needs_changes'
          ? 'Your plan can set aside ' + fmt(x) + ' per transfer, not the ' + fmt(per) + ' it needs by ' + dl + (o.limitedByHigherPriority ? ', because the goals ranked above it use the room first' : '') + '. It can still be reached on time if you choose a change.'
          : 'Even with every other goal paused and discretionary spending at your weekly minimum (' + fmt(disc.effectiveFloorWeeklyCents) + '), the most the plan can set aside is ' + fmt(mp.cents) + ' per transfer, short of the ' + fmt(per) + ' needed by ' + dl + '.';
      }
      if (r.afterTerm) o.reason += ' The deadline is after the term ends, so the forecast checks the transfers only through ' + label(H) + '.';
      return o;
    });

    // the plan to accept: every decided goal's transfers, plus any deadline or priority this allocation assumed
    const choice = { goals: eligible.map(r => ({ id: r.goalId, amountCents: run.amounts[r.goalId], schedule: r.schedule })) };
    for (const e of extra.goals || []) { const c = choice.goals.find(x => x.id === e.id); if (c) Object.assign(c, e); else choice.goals.push(Object.assign({}, e)); }
    if (extra.discretionary) choice.discretionary = { weeklyCents: usedWeekly };
    const changes = eligible.map(r => {
      const g = plan.goals.find(x => x.id === r.goalId), now = g.contribution && g.status === 'active' ? g.contribution : null, x = run.amounts[r.goalId];
      return { goalId: r.goalId, name: r.name, fromCents: now ? now.amountCents : 0, toCents: x, scheduleChanged: !!(x > 0 && (!now || JSON.stringify(now.schedule) !== JSON.stringify(r.schedule))) };
    }).filter(c => c.fromCents !== c.toCents || c.scheduleChanged);

    const sumF = k => E.sum(run.fc.days, d => d[k]), days = run.fc.days.length, wk = v => Math.round(v * 7 / days);
    const split = { fromDay: T, toDay: H, days, weeks: run.fc.weeks.length, goalsCents: sumF('sav'), discretionaryCents: sumF('flx'), essentialsCents: sumF('ess'), billsCents: sumF('obl'), incomeCents: sumF('inc'),
      leftoverCents: Math.max(0, Math.min.apply(null, run.s)), perWeek: null };
    split.perWeek = { goalsCents: wk(split.goalsCents), discretionaryCents: wk(split.discretionaryCents), essentialsCents: wk(split.essentialsCents), billsCents: wk(split.billsCents) };
    const st = E.goalStatus(base, T, { fc: ctx.fcNone });

    const out = {
      ok: true, scenario, today: T, endDay: H, cushionCents: ctx.C, reserveCents: ctx.R, discretionary: Object.assign({}, disc, { usedWeeklyCents: usedWeekly, reduced: usedWeekly < disc.plannedWeeklyCents }),
      order: rows.map(r => r.goalId), conflicts: st.conflicts, urgent: st.urgent, goals, choice, changes, changesNeeded: changes.length > 0, split,
      current: { fits: currentShort < 0, safe: isSafe(slackOf(ctx, curFc)), firstShortDay: currentShort < 0 ? null : T + currentShort, onTrack: st.goals.filter(r => r.onTrack).map(r => r.goalId) },
      summary: { feasible: goals.filter(g => g.status === 'feasible').map(g => g.goalId), needsChanges: goals.filter(g => g.status === 'needs_changes').map(g => g.goalId), unreachable: goals.filter(g => g.status === 'unreachable').map(g => g.goalId) },
      planned: { minCents: run.fc.metrics.minCents, minDay: run.fc.metrics.minDay, endCents: run.fc.metrics.endCents },
      safe: isSafe(run.s), recommended: isSafe(run.s), forecastRuns: 0, validation: null, expected: null
    };
    // every recommendation is re-checked the way it would be applied: written to the student's plan, both scenarios re-run in full
    out.validation = E.checkGoalPlan(plan, choice, T);
    if (out.safe !== out.validation.safe) out.safe = out.validation.safe;
    if (!out.safe) { out.recommended = false; for (const g of goals) if (g.status === 'feasible') { g.status = 'needs_changes'; g.reason = 'Your plan is already below your cushion, so this is not a feasible allocation. Fix the shortfall first, or look at the alternatives.'; } out.summary.feasible = []; out.summary.needsChanges = goals.filter(g => g.status === 'needs_changes').map(g => g.goalId); }
    if (opts.expected !== false && scenario === 'cautious') {
      const ex = E.goalAllocation(plan, T, Object.assign({}, opts, { scenario: 'expected', expected: false, classify: false }));
      if (ex.ok) out.expected = { goals: ex.goals.map(g => ({ goalId: g.goalId, recommendedCents: g.recommendedCents, funded: g.funded })), holds: out.validation.ok && out.validation.scenarios.expected.safe };
    }
    out.forecastRuns = ctx.runs;
    return out;
  };

  // Re-runs the complete daily forecast (cautious and expected, planned spending) on the plan with `choice` written to it.
  //   safe  every day stays at or above the cushion (and the end-of-term reserve on the last day). This is financial feasibility.
  //   fits  the goals in the choice do not create a new shortfall or deepen one the plan already has. An already-short plan can
  //         still `fit` in this narrower sense; that is acknowledgeable risk, never feasibility.
  E.checkGoalPlan = function (plan, choice, T) {
    const out = { ok: true, scenarios: {}, fits: false, safe: false };
    for (const sc of ['cautious', 'expected']) {
      const ctx = context(plan, T, sc); if (!ctx) return { ok: false, error: 'no_balance', scenarios: {}, fits: false, safe: false };
      const p = E.writeGoalChoice(plan, choice, T, ctx.base);
      const zero = E.writeGoalChoice(p, { goals: ((choice && choice.goals) || []).filter(c => c.amountCents !== undefined).map(c => ({ id: c.id, amountCents: 0 })) }, T, ctx.base);
      const fc = plannedFc(ctx, p), s = slackOf(ctx, fc), sz = slackOf(ctx, plannedFc(ctx, zero)), k = firstShort(s, sz), u = firstUnsafe(s);
      out.scenarios[sc] = { fits: k < 0, safe: u < 0, firstShortDay: k < 0 ? null : T + k, firstUnsafeDay: u < 0 ? null : T + u, minCents: fc.metrics.minCents, minDay: fc.metrics.minDay, endCents: fc.metrics.endCents, lowestRoomCents: Math.min.apply(null, s), cushionCents: ctx.C, reserveCents: ctx.R };
    }
    out.fits = out.scenarios.cautious.fits;
    out.safe = out.scenarios.cautious.safe;
    return out;
  };

  /* ---------- alternatives for goals that do not fit ---------- */
  function effectsOf(a, b) {
    return a.goals.map(g => { const h = b.goals.find(x => x.goalId === g.goalId) || {}; return { goalId: g.goalId, name: g.name, before: { status: g.status, recommendedCents: g.recommendedCents }, after: { status: h.status, recommendedCents: h.recommendedCents }, changed: g.status !== h.status || g.recommendedCents !== h.recommendedCents }; });
  }
  const isFunded = (alloc, id) => { const g = alloc.ok && alloc.goals.find(x => x.goalId === id); return !!(g && g.funded); };

  // opts: { scenario, goalId (only this goal), allocation (reuse one) }
  E.goalAlternatives = function (plan, T, opts) {
    opts = opts || {};
    const scenario = opts.scenario || 'cautious', alloc = opts.allocation || E.goalAllocation(plan, T, { scenario });
    if (!alloc.ok) return alloc;
    const light = o => E.goalAllocation(plan, T, Object.assign({ scenario, classify: false, expected: false }, o));
    const pack = (kind, alt, extra) => Object.assign({ kind, available: true, choice: alt.choice, validation: alt.validation, effects: effectsOf(alloc, alt) }, extra);
    const res = [];
    for (const r of alloc.goals) {
      if (r.status !== 'needs_changes' && r.status !== 'unreachable') continue;
      if (opts.goalId && r.goalId !== opts.goalId) continue;
      const options = [];
      // 1. a lower contribution: what the plan supports now (this IS the recommended allocation)
      if (r.recommendedCents > 0) options.push({ kind: 'lower_contribution', available: true, amountCents: r.recommendedCents, completionDay: r.completionDay, completionAfterTerm: r.completionDay !== null && r.completionDay > alloc.endDay, meetsDeadline: false,
        text: 'Save ' + fmt(r.recommendedCents) + ' per transfer, what your plan supports now.' + (r.completionDay === null ? '' : ' At that pace you would reach ' + fmt(r.targetCents) + ' around ' + label(r.completionDay) + (r.completionDay > alloc.endDay ? ' (after the term, so the forecast cannot check it yet)' : '') + '.'),
        choice: alloc.choice, validation: alloc.validation, effects: effectsOf(alloc, alloc) });
      else options.push({ kind: 'lower_contribution', available: false, text: 'Right now your plan has no room to set anything aside for it without going below your cushion.' });
      // 2. a later deadline: the earliest of its transfer dates, up to the end of the term, by which it can be fully funded
      if (r.dueDay !== null) {
        const cands = E.occurrences(r.schedule, Math.max(r.dueDay, T) + 1, alloc.endDay).map(o => o.day);
        const test = i => light({ overrides: [{ id: r.goalId, dueDate: D.fmt(cands[i]) }] });
        let found = null;
        if (cands.length) {
          const last = test(cands.length - 1);
          if (isFunded(last, r.goalId)) {
            let lo = 0, hi = cands.length - 1, best = last;
            while (lo < hi) { const mid = (lo + hi) >> 1, a = test(mid); if (isFunded(a, r.goalId)) { hi = mid; best = a; } else lo = mid + 1; }
            found = { day: cands[lo], alt: lo === cands.length - 1 ? last : best };
          }
        }
        if (found) { const g2 = found.alt.goals.find(x => x.goalId === r.goalId); options.push(pack('later_deadline', found.alt, { dueDate: D.fmt(found.day), amountCents: g2.recommendedCents, contributions: g2.required ? g2.required.contributions : null, text: 'Move the deadline to ' + label(found.day) + ' and save ' + fmt(g2.recommendedCents) + ' per transfer.' })); }
        else options.push({ kind: 'later_deadline', available: false, completionDay: r.completionDay, text: 'No date before the end of the term (' + label(alloc.endDay) + ') works with your current plan.' + (r.completionDay ? ' At ' + fmt(r.recommendedCents) + ' per transfer it would be reached around ' + label(r.completionDay) + ', which the forecast cannot check yet.' : '') });
      }
      // 3. a different priority: fund this goal first
      if (r.rank > 0) {
        const order = [r.goalId].concat(alloc.order.filter(id => id !== r.goalId)), alt = light({ order }), g2 = alt.goals.find(x => x.goalId === r.goalId);
        if (g2 && g2.recommendedCents > r.recommendedCents) {
          const hurt = effectsOf(alloc, alt).filter(e => e.goalId !== r.goalId && e.changed && e.after.recommendedCents < e.before.recommendedCents);
          options.push(pack('priority', alt, { order, reachesGoal: g2.funded, amountCents: g2.recommendedCents,
            text: 'Fund "' + r.name + '" first: it would get ' + fmt(g2.recommendedCents) + ' per transfer' + (g2.funded ? ' and be reached on time' : ', still short of what it needs') + '.' + (hurt.length ? ' ' + hurt.map(e => '"' + e.name + '" would drop from ' + fmt(e.before.recommendedCents) + ' to ' + fmt(e.after.recommendedCents) + ' per transfer').join('; ') + '.' : '') }));
        }
      }
      // 4. less discretionary spending: ONLY if the student chooses it, and never below their weekly minimum
      const d = alloc.discretionary, lo0 = d.effectiveFloorWeeklyCents, hi0 = d.plannedWeeklyCents;
      if (hi0 > lo0) {
        const atFloor = light({ discretionaryWeeklyCents: lo0 });
        if (isFunded(atFloor, r.goalId)) {
          let lo = Math.ceil(lo0 / DOLLAR), hi = Math.floor((hi0 - 1) / DOLLAR), best = { w: lo0, alt: atFloor };
          while (lo <= hi) { const mid = (lo + hi) >> 1, a = light({ discretionaryWeeklyCents: mid * DOLLAR }); if (isFunded(a, r.goalId)) { best = { w: mid * DOLLAR, alt: a }; lo = mid + 1; } else hi = mid - 1; }
          const g2 = best.alt.goals.find(x => x.goalId === r.goalId);
          options.push(pack('reduce_discretionary', best.alt, { requiresExplicitChoice: true, weeklyCents: best.w, cutWeeklyCents: hi0 - best.w, floorWeeklyCents: lo0, amountCents: g2.recommendedCents,
            text: 'Only if you choose it: spend ' + fmt(hi0 - best.w) + ' a week less on discretionary things (' + fmt(best.w) + ' instead of ' + fmt(hi0) + ') and save ' + fmt(g2.recommendedCents) + ' per transfer. Campus Compass never lowers your spending on its own.' }));
        } else options.push({ kind: 'reduce_discretionary', available: false, requiresExplicitChoice: true, floorWeeklyCents: lo0, text: 'Even at your weekly minimum of ' + fmt(lo0) + ' for discretionary spending, it would not fit.' });
      } else options.push({ kind: 'reduce_discretionary', available: false, requiresExplicitChoice: true, floorWeeklyCents: lo0, text: 'Your discretionary spending is already at your weekly minimum.' });
      res.push({ goalId: r.goalId, name: r.name, status: r.status, reason: r.reason, options });
    }
    return { ok: true, today: T, scenario, allocation: alloc, goals: res,
      note: 'Nothing here changes your plan. Every option was checked by re-running your full daily forecast, and only takes effect if you choose it.' };
  };

  /* ---------- the student accepts a goal plan (the ONLY writer) ---------- */
  // choice: as E.writeGoalChoice, plus discretionary.confirmed (required to lower discretionary spending) and acceptShortfall
  // (required to apply a plan that would push a day below the cushion). Returns { ok, plan, check, status } or { ok:false, error, plan }.
  E.applyGoalPlan = function (plan, choice, T) {
    if (typeof T !== 'number') return fail(plan, 'Internal error: applying a goal plan needs today\'s date.');
    if (!choice || typeof choice !== 'object') return fail(plan, 'There is nothing to apply.');
    const goals = Array.isArray(choice.goals) ? choice.goals : [];
    for (const c of goals) {
      if (!c || !plan.goals.some(g => g.id === c.id)) return fail(plan, 'That goal no longer exists.');
      if (c.amountCents !== undefined && !(Number.isSafeInteger(c.amountCents) && c.amountCents >= 0 && c.amountCents <= 1e9)) return fail(plan, 'Enter a contribution of $0 or more.');
      if (c.dueDate !== undefined && c.dueDate !== '' && D.parse(c.dueDate) === null) return fail(plan, 'That deadline is not a valid date.');
      if (c.priority !== undefined && !(Number.isInteger(c.priority) && c.priority >= 1 && c.priority <= 99)) return fail(plan, 'Priority must be between 1 and 99.');
      if (c.schedule !== undefined && c.schedule !== null && (typeof c.schedule !== 'object' || E.FREQS.indexOf(c.schedule.freq) < 0)) return fail(plan, 'That savings schedule is not valid.');
    }
    const det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det);
    if (choice.discretionary) {
      const w = choice.discretionary.weeklyCents, info = E.discretionaryPlan(plan, T, base);
      if (!Number.isSafeInteger(w) || w < 0) return fail(plan, 'Enter a weekly amount of $0 or more.');
      if (w < info.plannedWeeklyCents) {
        if (choice.discretionary.confirmed !== true) return fail(plan, 'Lowering your discretionary spending is your decision. Confirm it to apply it; Campus Compass never lowers it on its own.');
        if (w < info.effectiveFloorWeeklyCents) return fail(plan, 'That is below your weekly minimum of ' + fmt(info.effectiveFloorWeeklyCents) + '. Change your minimum first if you want to go lower.');
      }
    }
    const check = E.checkGoalPlan(plan, choice, T);
    if (!check.ok) return fail(plan, 'Set your starting balance first.');
    const below = !check.safe, day = check.scenarios.cautious && (check.scenarios.cautious.firstUnsafeDay || check.scenarios.cautious.firstShortDay);
    if (below && choice.acceptShortfall !== true) return Object.assign(fail(plan, 'This would leave your balance below your cushion' + (day != null ? ' on ' + label(day) : '') + ' in the cautious forecast. That is not a feasible plan. Nothing was changed.'), { check, safe: false, risk: 'below_cushion' });
    const p = E.writeGoalChoice(plan, choice, T, base);
    return { ok: true, plan: p, check, safe: check.safe, risk: below ? 'below_cushion' : null, status: E.goalStatus(p, T),
      note: below ? 'You asked to apply a plan that stays below your cushion. That is a hypothetical you accepted, not a feasible or recommended allocation.' : '' };
  };

  /* ---------- the student adds, edits, pauses or completes a goal (Stage E writers) ---------- */
  E.addGoal = function (plan, o, today) {
    o = o || {};
    const name = E.safeStr(o.name, 60);
    if (!name) return fail(plan, 'Give this goal a short name, like "Laptop".');
    const target = Math.round(Number(o.targetCents));
    if (!Number.isSafeInteger(target) || target <= 0 || target > 1e9) return fail(plan, 'Enter a target above $0.');
    if (o.dueDate && D.parse(o.dueDate) === null) return fail(plan, 'That deadline is not a valid date.');
    const saved = o.savedCents == null || o.savedCents === '' ? 0 : Math.round(Number(o.savedCents));
    if (!Number.isSafeInteger(saved) || saved < 0 || saved > 1e9) return fail(plan, 'Enter how much is already saved as $0 or more.');
    if (plan.goals.length >= 40) return fail(plan, 'That is the most goals this plan can hold.');
    const p = E.clone(plan), id = E.newId(p, 'gl', new Set(p.goals.map(g => g.id)));
    let pri = o.priority == null || o.priority === '' ? p.goals.length + 1 : Math.round(Number(o.priority));
    if (!Number.isInteger(pri) || pri < 1 || pri > 99) return fail(plan, 'Priority must be between 1 and 99.');
    p.goals.push({
      id, name, type: E.GOAL_TYPES.indexOf(o.type) >= 0 ? o.type : 'other', targetCents: target, savedCents: saved,
      savedAsOf: saved > 0 && typeof today === 'number' ? D.fmt(today) : '', savedSeq: saved > 0 ? ++p.seq : 0,
      dueDate: o.dueDate && D.parse(o.dueDate) !== null ? D.fmt(D.parse(o.dueDate)) : '', contribution: null, priority: pri, status: 'active'
    });
    return { ok: true, plan: E.normalizePlan(p).plan, id };
  };
  E.updateGoal = function (plan, id, patch, today) {
    patch = patch || {};
    const g0 = plan.goals.find(x => x.id === id);
    if (!g0) return fail(plan, 'That goal no longer exists.');
    const p = E.clone(plan), g = p.goals.find(x => x.id === id);
    if (patch.name !== undefined) {
      const name = E.safeStr(patch.name, 60);
      if (!name) return fail(plan, 'Give this goal a short name, like "Laptop".');
      g.name = name;
    }
    if (patch.type !== undefined) { if (E.GOAL_TYPES.indexOf(patch.type) < 0) return fail(plan, 'Choose what kind of goal it is.'); g.type = patch.type; }
    if (patch.targetCents !== undefined) {
      const target = Math.round(Number(patch.targetCents));
      if (!Number.isSafeInteger(target) || target <= 0 || target > 1e9) return fail(plan, 'Enter a target above $0.');
      g.targetCents = target;
    }
    if (patch.dueDate !== undefined) {
      if (patch.dueDate === '' || patch.dueDate == null) g.dueDate = '';
      else { const d = D.parse(patch.dueDate); if (d === null) return fail(plan, 'That deadline is not a valid date.'); g.dueDate = D.fmt(d); }
    }
    if (patch.priority !== undefined) {
      const pri = Math.round(Number(patch.priority));
      if (!Number.isInteger(pri) || pri < 1 || pri > 99) return fail(plan, 'Priority must be between 1 and 99.');
      g.priority = pri;
    }
    if (patch.savedCents !== undefined) {
      const r = E.setGoalSaved(p, id, patch.savedCents, today);
      if (!r.ok) return r;
      return { ok: true, plan: E.normalizePlan(r.plan).plan };
    }
    return { ok: true, plan: E.normalizePlan(p).plan };
  };
  E.setGoalStatus = function (plan, id, status) {
    if (E.GOAL_STATUSES.indexOf(status) < 0) return fail(plan, 'That is not a valid goal status.');
    const g0 = plan.goals.find(x => x.id === id);
    if (!g0) return fail(plan, 'That goal no longer exists.');
    const p = E.clone(plan), g = p.goals.find(x => x.id === id);
    g.status = status;
    if (status !== 'active') g.contribution = null;
    return { ok: true, plan: E.normalizePlan(p).plan };
  };
})(CCE);

;
/* ===== engine/15-spending.js ===== */
/* =========================================================================
   15 spending — where the money went (recorded transactions only)
   -------------------------------------------------------------------------
   A look back, never a forecast: every amount here is a transaction the
   student logged or imported. Nothing is estimated or filled in, and days
   with no records are reported as missing rather than counted as $0 days.
   Card payments, transfers and income are not spending, so a purchase made
   on a card and then paid off from checking is counted once.
   ========================================================================= */
(function (E) {
  'use strict';
  const D = E.D;
  const dayOf = t => D.parse(t.date);
  const KIND_LABEL = { bill: 'Bills and subscriptions', essential: 'Everyday essentials', flexible: 'Flexible spending' };

  function byCategory(txs, from, to) {
    const out = {};
    for (const t of txs) {
      const d = dayOf(t);
      if (d === null || d < from || d > to || !(t.flow === 'spend' || (t.flow === 'refund' && t.amountCents > 0))) continue;
      const c = t.category || 'Other', r = out[c] = out[c] || { spent: 0, refunds: 0, count: 0 };
      if (t.flow === 'spend') { r.spent += -t.amountCents; r.count++; } else r.refunds += t.amountCents;
    }
    const net = {};
    for (const c of Object.keys(out)) net[c] = { cents: Math.max(0, out[c].spent - out[c].refunds), count: out[c].count };
    return net;
  }

  // plan, T (day number). Returns { ok, windowDays, from, to, monthStart, totalCents, monthTotalCents, rows, kinds, fixed, coverage, unusual, reconcile }
  E.spendingSummary = function (plan, T) {
    if (!plan || typeof T !== 'number') return { ok: false, error: 'No plan.' };
    const WINDOW = 30, from = T - WINDOW + 1, ms = D.monthStart(T);
    const txs = E.activeTxs(plan).filter(t => { const d = dayOf(t); return d !== null && d <= T; });
    const last = byCategory(txs, from, T), month = byCategory(txs, ms, T);
    const det = E.detectRecurring(plan, T), base = E.baseline(plan, T, det);
    const budgets = {}; for (const b of E.budgetStatus(plan, T, base)) budgets[b.category] = b;
    const approved = c => plan.budgets.some(b => b.category === c && b.approvedCents != null);

    const cats = Array.from(new Set(Object.keys(last).concat(Object.keys(month))));
    const totalCents = E.sum(cats, c => last[c] ? last[c].cents : 0), monthTotalCents = E.sum(cats, c => month[c] ? month[c].cents : 0);
    const rows = cats.map(c => {
      const b = budgets[c], hasBudget = !!b && approved(c);
      return {
        category: c, kind: E.catKind(c), kindLabel: KIND_LABEL[E.catKind(c)],
        cents: last[c] ? last[c].cents : 0, count: last[c] ? last[c].count : 0,
        sharePct: totalCents > 0 && last[c] ? Math.round(last[c].cents * 100 / totalCents) : 0,
        monthCents: month[c] ? month[c].cents : 0,
        budget: hasBudget ? { plannedCents: b.plannedCents, spentCents: b.spentCents, remainingCents: b.remainingCents, status: b.status } : null
      };
    }).sort((a, b) => b.cents - a.cents || b.monthCents - a.monthCents || (a.category < b.category ? -1 : 1));
    const kinds = ['bill', 'essential', 'flexible'].map(k => ({ kind: k, label: KIND_LABEL[k], cents: E.sum(rows.filter(r => r.kind === k), r => r.cents) }));

    // what is already committed every month, whether or not it shows up in the window
    const subs = [], billsList = [];
    for (const o of plan.obligations) {
      const m = E.monthlyEquivalent(o.schedule, o.amountCents); if (!m) continue;
      const row = { name: o.name, category: o.category, monthlyCents: m, source: o.source === 'detected' ? 'detected' : 'listed' };
      (o.kind === 'subscription' || o.category === 'Subscriptions' ? subs : billsList).push(row);
    }
    for (const r of det) {
      if (r.matched || r.ignored || r.category !== 'Subscriptions') continue;
      subs.push({ name: r.name, category: r.category, monthlyCents: E.monthlyEquivalent(r.schedule, r.amountCents), source: 'found', unconfirmed: true });
    }
    subs.sort((a, b) => b.monthlyCents - a.monthlyCents); billsList.sort((a, b) => b.monthlyCents - a.monthlyCents);
    const fixed = {
      subscriptions: subs, subscriptionsMonthlyCents: E.sum(subs, s => s.monthlyCents), unconfirmedSubscriptions: subs.filter(s => s.unconfirmed).length,
      bills: billsList, billsMonthlyCents: E.sum(billsList, s => s.monthlyCents)
    };

    // how much of the window is actually on record
    const firstDay = txs.length ? Math.min.apply(null, txs.map(dayOf)) : null, lastDay = txs.length ? Math.max.apply(null, txs.map(dayOf)) : null;
    const coveredDays = firstDay === null ? 0 : Math.min(WINDOW, T - Math.max(firstDay, from) + 1);
    const staleDays = lastDay === null ? null : T - lastDay;
    const complete = coveredDays >= WINDOW && staleDays !== null && staleDays <= 3;
    const note = firstDay === null ? 'No spending is on record yet. Log purchases or import a bank file to see where your money goes.'
      : complete ? 'Based on ' + txs.filter(t => dayOf(t) >= from).length + ' recorded transactions from the last 30 days.'
        : coveredDays < WINDOW ? 'Only ' + coveredDays + ' of the last 30 days are on record, so this is a partial picture.'
          : 'Nothing has been recorded in the last ' + staleDays + ' days, so recent spending is missing.';
    const coverage = { firstDay, lastDay, coveredDays, windowDays: WINDOW, staleDays, complete, note };

    const unusual = base.unusual.filter(u => { const d = D.parse(u.date); return d >= from && d <= T; }).sort((a, b) => b.amountCents - a.amountCents);
    const top = rows.find(r => r.kind === 'flexible' && r.cents > 0) || null;
    const reconcile = { ok: E.sum(rows, r => r.cents) === totalCents && E.sum(kinds, k => k.cents) === totalCents && E.sum(rows, r => r.monthCents) === monthTotalCents };
    return { ok: true, today: T, windowDays: WINDOW, from, to: T, monthStart: ms, totalCents, monthTotalCents, rows, kinds, fixed, coverage, unusual, topFlexible: top, reconcile };
  };
})(CCE);

;
/* ===== ui/01-core.js ===== */
/* =========================================================================
   Campus Compass v3 (Stage 2) — UI core
   -------------------------------------------------------------------------
   * Every piece of text reaches the page through text nodes (the h() builder below). There is no innerHTML anywhere,
     so imported descriptions, names and file contents cannot become markup or script.
   * No network access of any kind. State lives in this tab and, if the browser allows it, in localStorage.
   * All numbers come from the engine (CCE). The UI never does money arithmetic of its own.
   ========================================================================= */
const App = { screens: {}, state: null };
(function () {
  'use strict';
  const E = CCE, D = E.D;
  const KEY = 'campus-compass-v3-stage2';

  /* ---------- DOM builder: text nodes only ---------- */
  function add(el, c) {
    if (c == null || c === false) return;
    if (Array.isArray(c)) { for (const x of c) add(el, x); return; }
    if (c.nodeType) { el.appendChild(c); return; }
    el.appendChild(document.createTextNode(String(c)));
  }
  function h(tag, attrs) {
    const el = document.createElement(tag);
    if (attrs) for (const k of Object.keys(attrs)) {
      const v = attrs[k];
      if (v == null || v === false) continue;
      if (k === 'class') el.className = v;
      else if (k === 'text') el.textContent = String(v);
      else if (k.slice(0, 2) === 'on') { if (typeof v === 'function') el.addEventListener(k.slice(2), v); }      // never a string handler
      else if (k === 'value') el.value = v;
      else if (k === 'checked' || k === 'disabled' || k === 'selected') el[k] = !!v;
      else el.setAttribute(k, v === true ? '' : String(v));
    }
    for (let i = 2; i < arguments.length; i++) add(el, arguments[i]);
    return el;
  }
  const NS = 'http://www.w3.org/2000/svg';
  const ICONS = {
    lock: 'M7 11V8a5 5 0 0110 0v3M6 11h12v9H6z', download: 'M12 4v11m0 0l-4.5-4.5M12 15l4.5-4.5M5 16v4h14v-4', check: 'M5 12.5l4.5 4.5L19 7', upload: 'M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5M5 16v4h14v-4', pencil: 'M4 20l4-1 11-11-3-3L5 16l-1 4z',
    arrow: 'M5 12h14m0 0l-5-5m5 5l-5 5', back: 'M19 12H5m0 0l5-5m-5 5l5 5', alert: 'M12 8v5m0 3.5v.01M10.3 3.9L2.6 17.5A2 2 0 004.3 20.5h15.4a2 2 0 001.7-3L13.7 3.9a2 2 0 00-3.4 0z',
    star: 'M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z', user: 'M12 12a4 4 0 100-8 4 4 0 000 8zm-7 8a7 7 0 0114 0', file: 'M7 3h7l5 5v13H7zM14 3v5h5', info: 'M12 11v6m0-9.5v.01M12 21a9 9 0 100-18 9 9 0 000 18z'
  };
  function icon(name, size) {
    const s = document.createElementNS(NS, 'svg'); s.setAttribute('viewBox', '0 0 24 24'); s.setAttribute('width', size || 18); s.setAttribute('height', size || 18); s.setAttribute('aria-hidden', 'true'); s.setAttribute('class', 'ico');
    const p = document.createElementNS(NS, 'path'); p.setAttribute('d', ICONS[name] || ICONS.info); p.setAttribute('fill', 'none'); p.setAttribute('stroke', 'currentColor'); p.setAttribute('stroke-width', '2'); p.setAttribute('stroke-linecap', 'round'); p.setAttribute('stroke-linejoin', 'round');
    s.appendChild(p); return s;
  }
  function logo(size) {
    const s = document.createElementNS(NS, 'svg'); s.setAttribute('viewBox', '0 0 40 40'); s.setAttribute('width', size || 34); s.setAttribute('height', size || 34); s.setAttribute('aria-hidden', 'true');
    const mk = (tag, a) => { const e = document.createElementNS(NS, tag); for (const k of Object.keys(a)) e.setAttribute(k, a[k]); return e; };
    s.appendChild(mk('rect', { width: 40, height: 40, rx: 12, fill: '#145e4d' })); const g = mk('g', { transform: 'rotate(38 20 20)' });
    g.appendChild(mk('path', { d: 'M20 7.5l4.6 12.5h-9.2z', fill: '#f2c14e' })); g.appendChild(mk('path', { d: 'M20 32.5L15.4 20h9.2z', fill: '#fff' })); s.appendChild(g); s.appendChild(mk('circle', { cx: 20, cy: 20, r: 2.1, fill: '#145e4d' })); return s;
  }
  function finleyMark(size) {
    const s = document.createElementNS(NS, 'svg'); s.setAttribute('viewBox', '0 0 40 40'); s.setAttribute('width', size || 36); s.setAttribute('height', size || 36); s.setAttribute('aria-hidden', 'true');
    const mk = (tag, a) => { const e = document.createElementNS(NS, tag); for (const k of Object.keys(a)) e.setAttribute(k, a[k]); return e; };
    s.appendChild(mk('rect', { width: 40, height: 40, rx: 12, fill: '#2c6f8d' })); const g = mk('g', { transform: 'rotate(38 20 20)' });
    g.appendChild(mk('path', { d: 'M20 8l4.2 11.4h-8.4z', fill: '#f2c14e' })); g.appendChild(mk('path', { d: 'M20 32L15.8 20.6h8.4z', fill: '#fff' })); s.appendChild(g); s.appendChild(mk('circle', { cx: 20, cy: 20, r: 2, fill: '#2c6f8d' })); return s;
  }
  function finley(say, extra) {
    return h('aside', { class: 'finley', role: 'note' },
      h('div', { class: 'fin-mark' }, finleyMark(36)),
      h('div', { class: 'fin-body' }, h('p', { class: 'fin-who', text: 'Finley' }), h('p', { class: 'fin-say', text: say }), extra || null));
  }
  function finleyBox(screen, ctx) {
    const advice = E.finleyAdvice(App.state.plan, App.today(), Object.assign({ screen: screen }, ctx || {}));
    const extra = advice.action && advice.action.label
      ? h('div', { class: 'fin-act' }, button(advice.action.label, { kind: 'ghost small', onclick: () => App.runFinley(advice.action) }))
      : null;
    return finley(advice.text, extra);
  }
  App.runFinley = function (act) {
    if (!act) return;
    const st = App.state;
    if (act.screen === 'import') st.path = 'csv';
    if (act.focus) App.focusId = act.focus;
    if (act.screen && act.screen !== st.step) App.go(act.screen, { reset: true, focus: act.focus });
    else App.render();
  };

  /* ---------- money and date helpers (formatting only) ---------- */
  const money = (c, o) => E.fmt(c, o);
  const dollarsText = c => (Math.round(c) / 100).toFixed(2);
  const readMoney = text => { const t = String(text == null ? '' : text).trim(); if (!t) return null; const v = E.parseMoney(t); return v == null || !Number.isSafeInteger(v) ? null : v; };
  const dayLabel = n => D.label(n);
  const longDay = n => { const t = D.ymd(n); return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][D.dow(n)] + ' ' + D.label(n) + ', ' + t.y; };

  /* ---------- today (the engine never reads the clock; the UI passes it in) ---------- */
  // `#today=YYYY-MM-DD` in the address lets a reviewer preview another date. When used, the page says so.
  App.previewDate = (function () { const m = /today=(\d{4}-\d{2}-\d{2})/.exec(String(location.hash || '')); const d = m ? D.parse(m[1]) : null; return d === null ? null : d; })();
  // previewDate (#today=) wins; then a fixed sample scenario view day (Maya judge sample); else the real calendar.
  App.today = function () {
    if (App.previewDate !== null) return App.previewDate;
    const dv = App.state && App.state.demoViewDay;
    if (dv != null && Number.isFinite(dv)) return dv;
    const n = new Date(); return D.make(n.getFullYear(), n.getMonth() + 1, n.getDate());
  };

  /* ---------- state ---------- */
  const STEPS = E.ONBOARDING.steps;
  function fresh() { return { plan: null, step: 'welcome', path: null, persona: null, done: false, hist: [], flash: null, csvText: '', rvOpts: {}, rv: null, decisions: {}, conf: {}, found: null, budgetEdits: null, openOptional: null, forms: {}, saveFailed: false, confirmErase: false, savedSig: null, sampleSig: null, fileMsg: null, pendingOpen: null, replaceAsk: null, demoViewDay: null }; }
  App.state = fresh();
  App.fresh = fresh;

  /* ---------- storage (localStorage when available; never required) ---------- */
  function save() {
    const s = App.state;
    try {
      if (!s.plan) { localStorage.removeItem(KEY); return; }
      localStorage.setItem(KEY, JSON.stringify({ v: 1, plan: s.plan, step: s.step, path: s.path, persona: s.persona, done: s.done, home: !!s.home, savedSig: s.savedSig || null, sampleSig: s.sampleSig || null, demoViewDay: s.demoViewDay != null ? D.fmt(s.demoViewDay) : null }));
      s.saveFailed = false;
    } catch (e) { s.saveFailed = true; }
  }
  function load() {
    try {
      const raw = localStorage.getItem(KEY); if (!raw) return false;
      const o = JSON.parse(raw); if (!o || o.v !== 1 || !o.plan) return false;
      const r = E.normalizePlan(o.plan); if (!r.plan || !r.plan.account.asOf) return false;
      const s = fresh(); s.plan = r.plan; s.path = o.path === 'manual' ? 'manual' : 'csv'; s.persona = typeof o.persona === 'string' ? o.persona : null; s.done = !!o.done; s.home = s.done;     // Stage 4: once onboarding is finished, Today is where a returning student lands as their home screen
      s.savedSig = typeof o.savedSig === 'string' ? o.savedSig : null;
      s.sampleSig = typeof o.sampleSig === 'string' ? o.sampleSig : null;
      s.demoViewDay = typeof o.demoViewDay === 'string' ? D.parse(o.demoViewDay) : null;
      if (s.demoViewDay === null) s.demoViewDay = null;
      const order = STEPS[s.path === 'manual' ? 'manual' : 'csv'];
      let step = order.indexOf(o.step) >= 0 ? o.step : 'welcome';
      if (s.home && (o.step === 'today' || o.step === 'plan')) step = 'today';
      if (s.home && o.step === 'semester') step = 'semester';
      if (s.home && o.step === 'goals') step = 'goals';
      if (s.home && o.step === 'about') step = 'today';
      if (step === 'review') step = 'import';       // a half-finished review is not saved; start that step again
      if (s.plan.transactions.length === 0 && (step === 'found')) step = 'import';
      s.step = step; App.state = s; return true;
    } catch (e) { return false; }
  }
  App.erase = function () { try { localStorage.removeItem(KEY); } catch (e) { /* ignore */ } App.state = fresh(); App.render(); };
  App.save = save; App.load = load;

  /* ---------- save to a file / open a file (Kentucky PFM Challenge Rule 5) ---------- */
  // 'saved' = matches the last file saved or opened; 'sample' = an untouched one-click sample (it can be opened again exactly, so nothing to lose)
  App.saveStatus = function () {
    const s = App.state; if (!s.plan) return 'none';
    const sig = E.planSignature(s.plan);
    return sig === s.savedSig ? 'saved' : s.sampleSig && sig === s.sampleSig ? 'sample' : 'unsaved';
  };
  App.unsaved = () => App.saveStatus() === 'unsaved';
  App.fileName = T => 'campus-compass-plan-' + D.fmt(T) + '.json';
  App.saveToFile = function () {
    const s = App.state, T = App.today(); if (!s.plan) return false;
    const text = E.exportPlan(s.plan, D.fmt(T), s.demoViewDay != null ? { sampleViewDay: D.fmt(s.demoViewDay) } : null);
    try {
      const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
      const a = document.createElement('a'); a.href = url; a.download = App.fileName(T); a.className = 'sr'; document.body.appendChild(a); a.click(); document.body.removeChild(a);
      setTimeout(() => URL.revokeObjectURL(url), 4000);
    } catch (e) { s.fileMsg = { kind: 'bad', msg: 'This browser would not create the file. Your plan is unchanged.' }; App.render(); return false; }
    s.savedSig = E.planSignature(s.plan); s.fileMsg = { kind: 'good', msg: 'Saved your plan to ' + App.fileName(T) + ' (check your Downloads folder). Use "Open file" to continue from it later.' };
    App.lastExport = text; save(); App.focusId = 'file-msg'; App.render(); return true;
  };
  const MAX_FILE = 12e6;
  // The picker is created when it is needed and lives outside #app, so re-rendering never removes it mid-choice.
  App.pickFile = function () {
    let inp = document.getElementById('cc-open-file');
    if (!inp) {
      inp = document.createElement('input');
      inp.type = 'file'; inp.id = 'cc-open-file'; inp.accept = '.json,application/json,text/plain'; inp.hidden = true; inp.tabIndex = -1;
      inp.setAttribute('aria-label', 'Choose a saved Campus Compass file');
      inp.addEventListener('change', () => { const f = inp.files && inp.files[0]; if (f) App.openFileObject(f); });
      document.body.appendChild(inp);
    }
    inp.value = ''; inp.click();
  };
  App.openFileObject = function (file) {
    const s = App.state;
    if (!file) return;
    if (file.size > MAX_FILE) { s.fileMsg = { kind: 'bad', msg: 'That file is too large to be a Campus Compass plan. Nothing on this device was changed.' }; App.focusId = 'file-msg'; return App.render(); }
    const rd = new FileReader();
    rd.onload = () => App.openText(String(rd.result || ''), file.name);
    rd.onerror = () => { s.fileMsg = { kind: 'bad', msg: 'That file could not be read. Nothing on this device was changed.' }; App.focusId = 'file-msg'; App.render(); };
    rd.readAsText(file);
  };
  // Reads a file's text. A bad file changes nothing; a good one replaces the current plan only after the student agrees.
  App.openText = function (text, name) {
    const s = App.state, T = App.today(), r = E.importPlan(text, { today: T });
    s.pendingOpen = null;
    if (!r.ok) { s.fileMsg = { kind: 'bad', msg: (r.errors && r.errors[0] || 'That file is not a Campus Compass plan.') + ' Nothing on this device was changed.' }; App.focusId = 'file-msg'; return App.render(); }
    const pending = { plan: r.plan, name: E.safeStr(name, 80) || 'that file', warnings: r.warnings || [], sampleViewDay: r.sampleViewDay != null ? r.sampleViewDay : null };
    if (s.plan) { s.pendingOpen = pending; s.fileMsg = null; App.focusId = 'open-confirm'; return App.render(); }
    App.applyOpened(pending);
  };
  App.applyOpened = function (p) {
    const plan = p.plan, m = /^stage2-(maya|jordan|riley)$/.exec(plan.meta.demo || ''), s = fresh();
    s.plan = plan; s.persona = m ? m[1] : null; s.path = plan.transactions.length ? 'csv' : 'manual';
    s.done = !!plan.account.asOf; s.home = s.done; s.savedSig = E.planSignature(plan);
    s.demoViewDay = E.fixedSampleViewDay(plan, p.sampleViewDay != null ? p.sampleViewDay : null);
    s.fileMsg = { kind: 'good', msg: 'Opened ' + p.name + '. Everything below comes from that file.' + (p.warnings.length ? ' ' + p.warnings.length + ' item' + (p.warnings.length === 1 ? ' was' : 's were') + ' tidied while loading.' : '') };
    App.state = s; App.go(s.done ? 'today' : 'basics', { reset: true, focus: 'file-msg', keepFileMsg: true });
  };

  /* ---------- navigation ---------- */
  App.go = function (step, opts) {
    const s = App.state; opts = opts || {};
    if (opts.reset) s.hist = []; else if (s.step !== step && opts.noHistory !== true) s.hist.push(s.step);
    if (s.step !== step) s.sv = null;        // Semester-screen picks and its Undo never outlive the visit (an old Undo must not revert later changes)
    if (!opts.keepFileMsg) { s.fileMsg = null; s.pendingOpen = null; s.replaceAsk = null; }
    if (opts.focus) App.focusId = opts.focus;
    s.step = step; s.flash = opts.flash || null; save(); App.render(); window.scrollTo(0, 0);
  };
  App.back = function () { const s = App.state; if (!s.hist.length) return; s.sv = null; s.step = s.hist.pop(); s.flash = null; save(); App.render(); window.scrollTo(0, 0); };
  App.setPlan = function (plan) { App.state.plan = plan; save(); };
  App.flash = (msg, kind) => { App.state.flash = { msg, kind: kind || 'good' }; };
  App.homeStep = () => (App.state.home ? 'today' : 'plan');       // where "done" screens return to: Today once the student has opened it
  App.stepsOrder = () => STEPS[App.state.path === 'manual' ? 'manual' : 'csv'];

  /* ---------- reusable form pieces ---------- */
  let uid = 0; const nextId = p => 'f' + (++uid) + (p ? '-' + p : '');
  function field(label, input, hint, id) {
    return h('div', { class: 'field' }, h('label', { for: id, text: label }), input, hint ? h('p', { class: 'hint', id: id + '-hint', text: hint }) : null);
  }
  function moneyBox(o) {
    const id = nextId('m'), input = h('input', { id, type: 'text', inputmode: 'decimal', autocomplete: 'off', value: o.value == null ? '' : dollarsText(o.value), placeholder: o.placeholder || '0.00', 'aria-describedby': o.hint ? id + '-hint' : null });
    const wrap = h('div', { class: 'money' }, h('span', { class: 'cur', 'aria-hidden': 'true', text: '$' }), input);
    return { node: field(o.label, wrap, o.hint, id), input, get: () => readMoney(input.value), id };
  }
  function textBox(o) {
    const id = nextId('t'), input = h('input', { id, type: o.type || 'text', autocomplete: 'off', maxlength: o.max || 80, value: o.value || '', placeholder: o.placeholder || '', 'aria-describedby': o.hint ? id + '-hint' : null });
    return { node: field(o.label, input, o.hint, id), input, get: () => input.value.trim(), id };
  }
  function selectBox(o) {
    const id = nextId('s'), sel = h('select', { id });
    for (const opt of o.options) sel.appendChild(h('option', { value: opt.value, text: opt.label, selected: String(opt.value) === String(o.value) }));
    sel.value = o.value == null ? sel.value : String(o.value);
    return { node: field(o.label, sel, o.hint, id), input: sel, get: () => sel.value, id };
  }
  function chips(options, current, onpick, label) {
    const wrap = h('div', { class: 'chips', role: 'group', 'aria-label': label || 'Choices' });
    const btns = options.map(o => { const b = h('button', { type: 'button', class: 'chip' + (o.id === current ? ' on' : ''), 'aria-pressed': o.id === current ? 'true' : 'false', text: o.label, onclick: () => onpick(o.id) }); wrap.appendChild(b); return b; });
    return wrap;
  }
  function errorBox() { const n = h('p', { class: 'error', role: 'alert', hidden: '' }); return { node: n, show(msg) { n.textContent = msg; n.hidden = false; }, clear() { n.textContent = ''; n.hidden = true; } }; }
  function button(label, o) {
    o = o || {};
    return h('button', { type: 'button', id: o.id, class: 'btn ' + (o.kind || 'primary') + (o.big ? ' big' : ''), disabled: o.disabled, onclick: o.onclick, 'aria-label': o.aria }, o.icon ? icon(o.icon) : null, h('span', { text: label }), o.after ? icon(o.after) : null);
  }
  function badge(text, kind) { return h('span', { class: 'badge ' + (kind || ''), text }); }
  const levelKind = l => ({ needs_info: 'warn', provisional: 'amber', estimated: 'blue', confident: 'good', blocked: 'warn' }[l] || '');
  function card(title, sub, body, cls) { return h('section', { class: 'card ' + (cls || '') }, title ? h('h2', { class: 'card-title', text: title }) : null, sub ? h('p', { class: 'card-sub', text: sub }) : null, body); }

  Object.assign(App, { h, icon, logo, finleyMark, finley, finleyBox, money, dollarsText, readMoney, dayLabel, longDay, field, moneyBox, textBox, selectBox, chips, errorBox, button, badge, levelKind, card, add });
})();

;
/* ===== ui/02-shell.js ===== */
/* ---- UI shell: header, progress, flash, footer, error boundary, render loop ---- */
(function () {
  'use strict';
  const { h, icon, logo, button } = App;
  const PHASES = [
    { id: 'start', label: 'Start', steps: ['welcome', 'basics'] },
    { id: 'money', label: 'Your money', steps: ['import', 'review', 'found', 'income'] },
    { id: 'details', label: 'Quick answers', steps: ['needs', 'optional'] },
    { id: 'budgets', label: 'Budgets', steps: ['budgets'] },
    { id: 'plan', label: 'Your plan', steps: ['plan'] }
  ];

  function progress() {
    const s = App.state;
    // Returning users (home) never see onboarding step indicators, including on My plan.
    if (s.home || s.step === 'welcome' || (s.step === 'budgets' && s.done) || (s.step === 'optional' && s.done)) return null;
    const cur = PHASES.findIndex(p => p.steps.indexOf(s.step) >= 0);
    if (cur < 0) return null;       // the Today screen is not part of setup
    return h('nav', { class: 'progress', 'aria-label': 'Progress' }, h('ol', null, PHASES.map((p, i) => h('li', { class: i < cur ? 'done' : i === cur ? 'now' : '', 'aria-current': i === cur ? 'step' : null }, h('span', { class: 'dot', 'aria-hidden': 'true' }, i < cur ? icon('check', 12) : String(i + 1)), h('span', { class: 'lbl', text: p.label })))));
  }

  // Stage 4 + E: the main places once setup is done. Only shown after the student has reached Today.
  function mainNav() {
    const s = App.state; if (!s.home || ['today', 'semester', 'goals', 'plan'].indexOf(s.step) < 0) return null;
    const items = [['today', 'Today'], ['semester', 'Semester'], ['goals', 'Goals'], ['plan', 'My plan']];
    return h('nav', { class: 'mainnav', 'aria-label': 'Main' }, items.map(it => h('button', { type: 'button', class: 'tab' + (s.step === it[0] ? ' on' : ''), 'aria-current': s.step === it[0] ? 'page' : null, onclick: () => { if (s.step !== it[0]) App.go(it[0], { reset: true }); } }, it[1])));
  }

  function header() {
    const s = App.state;
    const eraseBox = !s.plan ? null : s.confirmErase
      ? h('span', { class: 'erase-confirm', role: 'group', 'aria-label': 'Confirm erase' }, h('span', { class: 'small', text: 'Erase everything on this device?' }), button('Yes, erase', { kind: 'danger small', onclick: () => App.erase() }), button('Keep it', { kind: 'ghost small', onclick: () => { s.confirmErase = false; App.render(); } }))
      : button('Start over', { kind: 'ghost small', onclick: () => { s.confirmErase = true; App.render(); } });
    const status = App.saveStatus(), unsaved = status === 'unsaved';
    const SAVE = {
      unsaved: ['Save to a file. You have changes that are not saved to a file yet.', 'You have changes that are not saved to a file', 'Unsaved changes'],
      saved: ['Save to a file. Everything is already saved to a file.', 'Saved to a file', 'Saved to file'],
      sample: ['Save to a file. This sample plan has no changes of yours yet.', 'Sample plan, no changes yet', 'Sample, unchanged']
    }[status];
    const saveBtn = s.plan ? h('button', { type: 'button', class: 'btn ghost small file-btn' + (unsaved ? ' unsaved' : ''), id: 'save-file', onclick: () => App.saveToFile(), 'aria-label': SAVE[0], title: SAVE[1] },
      icon('download', 16), h('span', { text: 'Save file' }), unsaved ? h('span', { class: 'dot-unsaved', 'aria-hidden': 'true' }) : null) : null;
    const state = s.plan ? h('span', { class: 'save-state' + (unsaved ? ' unsaved' : ''), 'aria-hidden': 'true', text: SAVE[2] }) : null;
    const openBtn = h('button', { type: 'button', class: 'btn ghost small file-btn', id: 'open-file', onclick: () => App.pickFile(), 'aria-label': 'Open a saved Campus Compass file' }, icon('file', 16), h('span', { text: 'Open file' }));
    const homeBtn = button('Home', { kind: 'ghost small', id: 'home-button', aria: 'Go to the welcome screen', onclick: () => App.go('welcome', { reset: true }) });
    return h('header', { class: 'top' },
      h('div', { class: 'brand' }, logo(34), h('div', { class: 'brand-text' }, h('span', { class: 'brand-name' }, 'campus', h('b', { text: 'compass' })), h('span', { class: 'brand-tag', text: 'Your money, made clear' }))),
      h('div', { class: 'top-right' }, h('span', { class: 'privacy-chip' }, icon('lock', 14), h('span', { text: 'Private: stays on this device' })), state, homeBtn, saveBtn, openBtn, eraseBox));
  }

  function fileNotes() {
    const s = App.state, out = [];
    if (s.fileMsg) out.push(h('div', { class: 'note ' + (s.fileMsg.kind === 'bad' ? 'amber' : 'good'), id: 'file-msg', tabindex: '-1', role: s.fileMsg.kind === 'bad' ? 'alert' : 'status' }, icon(s.fileMsg.kind === 'bad' ? 'alert' : 'check'), h('span', { text: s.fileMsg.msg }), button('Dismiss', { kind: 'ghost small', onclick: () => { s.fileMsg = null; App.render(); } })));
    const p = s.pendingOpen;
    if (p) {
      const unsaved = App.unsaved();
      out.push(h('div', { class: 'note amber confirm-open', id: 'open-confirm', tabindex: '-1', role: 'alertdialog', 'aria-label': 'Replace your plan?' }, icon('alert'),
        h('div', { class: 'co-body' },
          h('b', { text: 'Open "' + p.name + '"? It replaces the plan on this device.' }),
          h('p', { class: 'small', text: unsaved ? 'Your current plan has changes that are not saved to a file. Save it first if you might want it back.' : 'Your current plan is already saved to a file, so you can open it again later.' }),
          h('div', { class: 'row-actions' },
            unsaved ? button('Save my current plan first', { kind: 'ghost small', onclick: () => App.saveToFile() }) : null,
            button('Replace with this file', { kind: 'primary small', onclick: () => App.applyOpened(p) }),
            button('Cancel', { kind: 'ghost small', onclick: () => { s.pendingOpen = null; s.fileMsg = { kind: 'good', msg: 'Cancelled. Your current plan is unchanged.' }; App.focusId = 'file-msg'; App.render(); } })))));
    }
    return out;
  }

  function banners() {
    const s = App.state, out = [];
    if (App.previewDate !== null) out.push(h('div', { class: 'note blue', role: 'status' }, icon('info'), h('span', null, h('b', { text: 'Date preview. ' }), 'This page is pretending today is ' + App.longDay(App.previewDate) + '.')));
    if (s.saveFailed) out.push(h('div', { class: 'note amber', role: 'status' }, icon('alert'), h('span', null, h('b', { text: 'Not saved. ' }), 'This browser would not let the page save. Your plan lasts until you close this tab, so download a backup from the last screen.')));
    if (s.flash) out.push(h('div', { class: 'note ' + (s.flash.kind || 'good'), role: 'status' }, icon(s.flash.kind === 'amber' ? 'alert' : 'check'), h('span', { text: s.flash.msg })));
    return fileNotes().concat(out);
  }

  function footer() {
    return h('footer', { class: 'foot' },
      h('p', null, h('b', { text: 'Campus Compass is an educational budgeting tool, not a financial adviser. ' }), 'Every number is calculated by fixed, visible rules on this device. It is not artificial intelligence, and its forecasts are estimates, not promises. Check balances and due dates with your bank before relying on them.'),
      h('p', { class: 'small', text: 'Nothing you enter is sent anywhere. This page makes no network requests and has no accounts, analytics or tracking.' }),
      h('p', { class: 'small foot-links' }, h('span', { text: '\u00a9 ' + CC_LICENSE.year + ' ' + CC_LICENSE.author + '. Released under the MIT License.' }), App.state.step !== 'about' ? button('About, license and privacy', { kind: 'ghost small', onclick: () => App.go('about') }) : null));
  }

  function failure(err) {
    try { console.error(err); } catch (e) { /* ignore */ }
    return h('section', { class: 'card' }, h('h1', { id: 'title', tabindex: '-1', text: 'Something went wrong on this screen' }), h('p', { text: 'Your information is still saved on this device. You can try the screen again or go back to the start of setup.' }),
      h('div', { class: 'actions' }, button('Try again', { onclick: () => App.render() }), button('Go to the first screen', { kind: 'ghost', onclick: () => App.go('welcome', { reset: true }) })));
  }

  App.render = function () {
    const s = App.state, root = document.getElementById('app'); if (!root) return;
    root.textContent = '';
    const screen = App.screens[s.step] || App.screens.welcome; let body;
    try { body = screen(); } catch (err) { body = failure(err); }
    const main = h('main', { class: 'main', id: 'main' }, banners(), body);
    root.appendChild(h('div', { class: 'page' + (s.step === 'semester' ? ' wide' : '') }, header(), mainNav(), progress(), main, footer()));
    // After an action on Today, focus goes to the message or result the student just caused (App.focusId); otherwise to the page title.
    const fid = App.focusId; App.focusId = null;
    const t = (fid && document.getElementById(fid)) || document.getElementById('title'); if (t) { try { t.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }
  };

  // standard bottom navigation: Back (when there is somewhere to go) and a primary button
  App.nav = function (o) {
    o = o || {}; const s = App.state;
    return h('div', { class: 'actions' },
      s.hist.length && o.back !== false ? button('Back', { kind: 'ghost', icon: 'back', onclick: () => App.back() }) : null,
      o.secondary || null,
      o.next ? button(o.next.label, { big: true, after: o.next.noArrow ? null : 'arrow', disabled: o.next.disabled, onclick: o.next.onclick }) : null);
  };
})();

;
/* ===== ui/03-start.js ===== */
/* ---- Screens 1-2: welcome (three ways in) and the one mandatory question ---- */
(function () {
  'use strict';
  const E = CCE, D = E.D;
  const { h, icon, button, money, dayLabel, moneyBox, textBox, errorBox, field, badge, card } = App;

  // A student's own plan (not a sample) is never replaced without asking first.
  const ownPlan = () => { const p = App.state.plan; return !!(p && !p.meta.demo); };
  function begin(path, personaId, opts) {
    opts = opts || {};
    if (!opts.confirmed && ownPlan()) { App.state.replaceAsk = { path, personaId: personaId || null, finished: !!opts.finished, scenario: opts.scenario || null }; App.focusId = 'replace-ask'; return App.render(); }
    if (opts.finished) return openFinished(personaId, opts.scenario);
    const T = App.today(); App.state = App.fresh(); const s = App.state; s.path = path;
    if (personaId) {
      const r = E.demoStart(personaId, T); if (!r.ok) { App.flash(r.error, 'amber'); return App.render(); }
      s.plan = r.plan; s.persona = personaId; s.csvText = E.demoStatement(personaId, T);
    }
    App.go('basics');
  }
  // One click to a sample student's finished plan: the same engine calls as the walk-through, with every setup answer filled in.
  // Personas with a fixed scenario (Maya) lock build+view dates for judges. A #today= preview keeps date-relative demos for tests/review.
  // scenario 'start' (the welcome-screen demo) opens the fixed sample before its later edits, so it matches the card exactly.
  function openFinished(id, scenario) {
    const p = E.demoPersona(id), sc = E.demoScenarioDays(id);
    const start = !!(sc && scenario === 'start');
    const useFixed = !!(sc && (start || App.previewDate === null));
    const r = E.runDemo(id, App.today(), useFixed ? (start ? { fixed: true, walkthrough: false } : { fixed: true }) : {});
    if (!r.ok) { App.flash(r.error || 'That sample could not be opened.', 'amber'); return App.render(); }
    const s = App.fresh(); s.plan = r.plan; s.persona = id; s.path = 'csv'; s.csvText = r.csv; s.done = true; s.home = true; s.sampleSig = E.planSignature(r.plan);
    if (useFixed && r.viewDay != null) s.demoViewDay = r.viewDay;
    App.state = s;
    const when = useFixed && r.scenario ? ' Sample dates are fixed (' + r.scenario.viewLabel + ') so every judge sees the same numbers.' : '';
    const tail = start ? ' This is ' + p.name + ' as the welcome screen showed her, before any changes. Today shows the same projected low.' : ' Try "Can I afford this?" below, or open Semester and Goals.';
    App.go('today', { reset: true, flash: { msg: 'This is ' + p.name + '\'s finished plan. ' + p.name + ' is made up, and every setup answer is already filled in.' + when + tail, kind: 'good' } });
  }

  function replaceNote() {
    const st = App.state, a = st.replaceAsk; if (!a) return null;
    const p = a.personaId ? E.demoPersona(a.personaId) : null, unsaved = App.unsaved();
    const what = p ? 'Opening the sample student ' + p.name : a.path === 'manual' ? 'Setting up by hand' : 'Starting from a bank file';
    return h('div', { class: 'note amber confirm-open', id: 'replace-ask', tabindex: '-1', role: 'alertdialog', 'aria-label': 'Replace your plan?' }, icon('alert'),
      h('div', { class: 'co-body' },
        h('b', { text: what + ' replaces your own plan on this device.' }),
        h('p', { class: 'small', text: unsaved ? 'Your plan has changes that are not saved to a file. Save it first if you want it back later.' : 'Your plan is saved to a file, so you can open it again later.' }),
        h('div', { class: 'row-actions' },
          unsaved ? button('Save my plan to a file first', { kind: 'ghost small', onclick: () => App.saveToFile() }) : null,
          button('Replace it', { kind: 'danger small', onclick: () => { st.replaceAsk = null; begin(a.path, a.personaId, { confirmed: true, finished: a.finished, scenario: a.scenario }); } }),
          button('Keep my plan', { kind: 'ghost small', onclick: () => { st.replaceAsk = null; App.render(); } }))));
  }

  const samplesAboutOpen = new Set();

  App.screens.welcome = function () {
    const T = App.today(), st = App.state;
    const resume = st.plan && st.step === 'welcome' && !st.replaceAsk ? h('div', { class: 'note blue' }, icon('info'), h('span', { text: 'You have a plan saved on this device.' }), button(st.home ? 'Continue my plan' : 'Continue where I left off', { kind: 'ghost small', onclick: () => App.go(st.home ? 'today' : st.done ? App.homeStep() : 'basics') })) : null;
    const nameOf = p => p.label || p.name;
    const personas = E.DEMO_PERSONAS.map(p => h('div', { class: 'persona-card', id: 'sample-' + p.id },
      h('div', { class: 'pc-top' }, h('span', { class: 'avatar', 'aria-hidden': 'true', text: p.name.charAt(0) }), h('h3', { class: 'p-name', text: nameOf(p) })),
      h('div', { class: 'pc-actions' },
        h('button', { type: 'button', class: 'btn primary small', onclick: () => begin('csv', p.id, { finished: true }), 'aria-label': 'Open plan: ' + nameOf(p) }, h('span', { text: 'Open plan' }), icon('arrow', 16)),
        h('button', { type: 'button', class: 'persona', onclick: () => begin('csv', p.id), 'aria-label': 'Walk through setup: ' + p.name }, h('span', { text: 'Walk through setup' }))),
      h('details', { class: 'samples-about', id: 'about-' + p.id, open: samplesAboutOpen.has(p.id) ? '' : null, ontoggle: e => { if (e.target.open) samplesAboutOpen.add(p.id); else samplesAboutOpen.delete(p.id); } },
        h('summary', { text: 'Get to know ' + p.name }),
        h('p', { class: 'sa-text', text: p.about || (p.tagline + ' ' + p.story) }))));
    const diff = (title, body) => h('li', null, h('b', { text: title }), h('span', { text: body }));
    return h('div', { class: 'welcome' },
      resume, replaceNote(),
      h('section', { class: 'hero' },
        h('p', { class: 'eyebrow', text: E.DEMO_SCHOOL + ' edition' }),
        h('h1', { id: 'title', tabindex: '-1', text: 'Know what you can spend this semester' }),
        h('p', { class: 'lede', text: 'Campus Compass helps University of Kentucky students see whether their money will last through the semester. See when rent and bills could leave you short before your next paycheck or financial aid refund. Your plan stays on your device and works offline.' }),
        h('ul', { class: 'diffs', 'aria-label': 'What Campus Compass shows you' },
          diff('What can I spend?', 'Get a daily estimate that sets aside money for rent, bills, essentials, and a cash cushion.'),
          diff('Can I afford this purchase?', 'See whether buying something today could cause your estimated balance to fall below your safety cushion later in the semester.'),
          diff('Experiment with what ifs?', 'Start with a cautious forecast that accounts for late aid, a smaller paycheck, and other changes.')),
        h('p', { class: 'edu-notice' }, h('b', { text: 'For educational use only.' }), ' Campus Compass provides budgeting estimates.')),
      h('div', { class: 'choices' },
        h('button', { type: 'button', class: 'choice main', onclick: () => begin('csv'), 'aria-describedby': 'c1d' },
          h('span', { class: 'ci' }, icon('upload', 18)),
          h('span', { class: 'ct' }, h('span', { class: 'ch', text: 'Upload a bank file' }), h('span', { class: 'cd', id: 'c1d', text: 'Choose a bank CSV. Your file stays on this device.' }))),
        h('button', { type: 'button', class: 'choice', onclick: () => begin('manual'), 'aria-describedby': 'c2d' },
          h('span', { class: 'ci' }, icon('pencil', 18)),
          h('span', { class: 'ct' }, h('span', { class: 'ch', text: 'Set up by hand' }), h('span', { class: 'cd', id: 'c2d', text: 'Enter your balance, rent, and income.' })))),
      h('p', { class: 'open-line' }, h('span', { text: 'Already have a Campus Compass file?' }), button('Open a saved file', { kind: 'ghost small', icon: 'file', onclick: () => App.pickFile() })),
      h('section', { class: 'samples' }, h('h2', { text: 'Or see it with a sample student' }), h('p', { class: 'sub', text: 'Made-up students at ' + E.DEMO_SCHOOL + ', each with a realistic bank file and a different money problem. Open a finished plan in one click, or walk through setup exactly as a real student would.' }), h('div', { class: 'persona-grid' }, personas)),
      h('ul', { class: 'promises' },
        h('li', null, icon('lock', 16), h('span', null, h('b', { text: 'Private. ' }), 'No account, no internet needed, nothing uploaded.')),
        h('li', null, icon('check', 16), h('span', null, h('b', { text: 'Honest. ' }), 'Estimates are labelled as estimates. "Safe to spend" is only used when the cushion and after-term needs are protected — otherwise it stays $0.')),
        h('li', null, icon('user', 16), h('span', null, h('b', { text: 'You decide. ' }), 'Suggested budgets only count after you approve them.'))));
  };

  App.screens.basics = function () {
    const st = App.state, T = App.today(), p = st.plan, persona = st.persona ? E.demoPersona(st.persona) : null;
    const bal = moneyBox({ label: 'Checking balance right now', value: p ? p.account.balanceCents : null, placeholder: '842.50', hint: 'The number your bank app shows today. This is the only thing we have to ask.' });
    const school = textBox({ label: 'School', value: p ? p.meta.school : E.ONBOARDING.defaults.school, max: 80, hint: 'The University of Kentucky is the default. Changing it does not change any calculation.' });
    const err = errorBox();
    const per = p ? E.currentPeriod(p, T) : null, def = per || E.defaultPeriods(T).find(x => x.kind === 'semester' && D.parse(x.end) >= T);
    const go = () => {
      err.clear(); const cents = bal.get();
      if (cents == null) { err.show('Enter your checking balance as a number, for example 842.50.'); bal.input.focus(); return; }
      const keep = st.plan ? { name: st.plan.meta.name, living: st.plan.meta.living, demo: st.plan.meta.demo } : {};
      const r = E.startPlan({ today: T, balanceCents: cents, school: school.get(), name: keep.name || '', living: keep.living || 'Off campus', demo: keep.demo || '' });
      if (!r.ok) { err.show(r.error); return; }
      App.setPlan(r.plan); App.go(st.path === 'manual' ? 'income' : 'import');
    };
    return h('section', { class: 'card narrow' },
      h('p', { class: 'eyebrow', text: 'Step 1 of 4' }),
      h('h1', { id: 'title', tabindex: '-1', text: persona ? 'Starting with ' + persona.name : 'Where are you starting from?' }),
      persona ? h('div', { class: 'note blue' }, icon('info'), h('span', null, h('b', { text: 'Sample student. ' }), persona.name + ' is made up. The balance below and the bank file in the next step are demo data for ' + E.DEMO_SCHOOL + '.')) : null,
      bal.node, school.node,
      h('div', { class: 'fact' }, icon('info'), h('div', null, h('b', { text: 'Semester dates: ' }), def ? def.name + ', ' + App.dayLabel(D.parse(def.start)) + ' to ' + App.dayLabel(D.parse(def.end)) + '. ' : '', E.SCHOOLS[E.DEMO_SCHOOL].calendarNote, ' We label every number that depends on them until you confirm them.')),
      err.node,
      App.nav({ next: { label: st.path === 'manual' ? 'Continue' : 'Continue to my bank file', onclick: go } }));
  };
})();

;
/* ===== ui/04-import.js ===== */
/* ---- Screens 3-5: choose a bank file, review and confirm it, confirm what repeats ---- */
(function () {
  'use strict';
  const E = CCE, D = E.D;
  const { h, icon, button, errorBox, badge, card, money, dayLabel } = App;
  const MAX_BYTES = 3 * 1024 * 1024;
  const personaOf = () => (App.state.persona ? E.demoPersona(App.state.persona) : null);

  function runReview(text) {
    const st = App.state, T = App.today();
    return E.reviewStatement(st.plan, text, Object.assign({ today: T }, st.rvOpts));
  }
  function startReview(text, errBox) {
    const st = App.state;
    if (!text || !text.trim()) { errBox.show('Choose a file or paste some rows first.'); return; }
    st.csvText = text; st.rvOpts = {};
    const rv = runReview(text);
    if (!rv.ok) { errBox.show(rv.error || 'That file could not be read.'); return; }
    st.rv = rv; resetDecisions(); App.go('review');
  }
  function resetDecisions() {
    const st = App.state, rv = st.rv; st.conf = {}; st.decisions = {};
    const demo = st.persona ? E.demoDecisions(st.persona, rv) : null;
    for (const a of rv.attention) { const d = demo ? demo[a.idx] : { option: a.suggested }; st.decisions[a.idx] = { option: d.option, category: a.currentCategory && a.currentCategory !== '' ? a.currentCategory : 'Other' }; }
  }

  /* ---------- import ---------- */
  App.screens.import = function () {
    const st = App.state, persona = personaOf(), err = errorBox();
    const pasted = h('textarea', { id: 'paste', rows: 6, maxlength: MAX_BYTES, placeholder: 'Date,Description,Amount\n10/01/2026,KROGER 512,-42.18', 'aria-label': 'Paste statement rows' });
    const input = h('input', { type: 'file', id: 'file', accept: '.csv,.txt,text/csv,text/plain', class: 'sr', 'aria-label': 'Choose a bank file' });
    const readFile = f => {
      err.clear(); if (!f) return;
      if (f.size > MAX_BYTES) { err.show('That file is bigger than 3 MB. Export a shorter period (the last two or three months is plenty).'); return; }
      const fr = new FileReader(); fr.onerror = () => err.show('That file could not be read. Try exporting it again.');
      fr.onload = () => startReview(String(fr.result || ''), err); fr.readAsText(f);
    };
    input.addEventListener('change', () => readFile(input.files && input.files[0]));
    const drop = h('label', { class: 'drop', for: 'file', tabindex: '0' }, icon('upload', 30), h('span', { class: 'dt', text: 'Choose your bank file' }), h('span', { class: 'dd', text: 'or drag it here. CSV from your bank, last 1 to 3 months.' }));
    drop.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); input.click(); } });
    drop.addEventListener('dragover', e => { e.preventDefault(); drop.classList.add('over'); }); drop.addEventListener('dragleave', () => drop.classList.remove('over'));
    drop.addEventListener('drop', e => { e.preventDefault(); drop.classList.remove('over'); readFile(e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]); });
    const demoBlock = persona ? h('div', { class: 'note blue' }, icon('info'), h('span', null, h('b', { text: 'Sample bank file for ' + persona.name + '. ' }), 'It is made up, and its dates are relative to today. It goes through the same review as a real file.'), button('Review ' + persona.name + '\'s file', { kind: 'primary small', onclick: () => startReview(st.csvText, err) })) : null;
    return h('section', { class: 'card narrow' },
      h('p', { class: 'eyebrow', text: 'Step 2 of 4' }),
      h('h1', { id: 'title', tabindex: '-1', text: 'Add your bank activity' }),
      h('p', { class: 'lede', text: 'This is what makes your plan personal. Real purchases replace guesses.' }),
      demoBlock, input, drop,
      h('p', { class: 'hint', text: 'In most banks: open your checking account, choose Download or Export, pick CSV, and choose the last 1 to 3 months. The file is read in this browser tab and is never uploaded.' }),
      h('details', { class: 'paste' }, h('summary', { text: 'Paste rows instead' }), pasted, button('Review pasted rows', { kind: 'ghost', onclick: () => startReview(pasted.value, err) })),
      err.node,
      App.nav({ secondary: button('I have no file. Set up by hand', { kind: 'ghost', onclick: () => { st.path = 'manual'; App.setPlan(st.plan); App.go('income'); } }) }));
  };

  /* ---------- review ---------- */
  const CAT_CHOICES = Object.keys(E.CATEGORIES).filter(c => E.catKind(c) !== 'bill' || c === 'Housing');
  function rerun() { const st = App.state; const rv = runReview(st.csvText); if (!rv.ok) { App.flash(rv.error, 'amber'); } else { st.rv = rv; resetDecisions(); } App.render(); }

  function sampleTable(rows) {
    return h('table', { class: 'tbl' }, h('thead', null, h('tr', null, h('th', { text: 'Date' }), h('th', { text: 'Description' }), h('th', { class: 'r', text: 'Amount' }))),
      h('tbody', null, rows.map(r => h('tr', null, h('td', { text: typeof r.date === 'string' ? dayLabel(D.parse(r.date)) : '' }), h('td', { text: r.desc }), h('td', { class: 'r ' + (r.amountCents < 0 ? 'neg' : 'pos'), text: money(r.amountCents) })))));
  }
  function confirmBox(id, text, refresh) {
    const st = App.state, cb = h('input', { type: 'checkbox', id: 'c-' + id, checked: !!st.conf[id] });
    cb.addEventListener('change', () => { st.conf[id] = cb.checked; refresh(); });
    return h('label', { class: 'confirm', for: 'c-' + id }, cb, h('span', { text }));
  }
  function selectCol(label, rv, key) {
    const st = App.state, sel = h('select', { id: 'col-' + key, 'aria-label': label }), cur = rv.mapping.detected[key];
    for (const o of rv.mapping.options) sel.appendChild(h('option', { value: o.index, text: o.header || ('Column ' + (o.index + 1)), selected: o.index === cur }));
    sel.addEventListener('change', () => { st.rvOpts.mapping = Object.assign({}, st.rvOpts.mapping || {}, { date: rv.mapping.detected.date, desc: rv.mapping.detected.desc, amt: rv.mapping.detected.amt }, { [key]: Number(sel.value) }); rerun(); });
    return h('div', { class: 'field inline' }, h('label', { for: 'col-' + key, text: label }), sel);
  }

  App.screens.review = function () {
    const st = App.state, rv = st.rv, T = App.today(), err = errorBox();
    if (!rv) return (App.go('import', { noHistory: true }), h('div'));
    const need = rv.required.map(r => r.id), applyBtn = button('Add these to my plan', { big: true, after: 'arrow', disabled: true });
    const refresh = () => { const ok = need.every(id => st.conf[id]); applyBtn.disabled = !ok; };
    const apply = () => {
      err.clear(); const res = E.applyStatementReview(st.plan, rv, { confirmed: st.conf, rows: st.decisions }, T);
      if (!res.ok) { err.show(res.error || 'Please confirm each item first.'); return; }
      App.setPlan(res.plan); st.csvText = ''; st.rv = null; st.found = null; st.conf = {}; st.decisions = {};
      App.go('found', { reset: true, flash: { msg: 'Added ' + res.added + ' transactions' + (res.duplicates ? ' (' + res.duplicates + ' already there were skipped)' : '') + '.', kind: 'good' } });
    };
    applyBtn.addEventListener('click', apply);
    const c = rv.counts;
    const summary = card('What is in this file', null, h('div', null,
      h('p', { text: c.total + ' rows from ' + (rv.first ? dayLabel(D.parse(rv.first)) : '?') + ' to ' + (rv.last ? dayLabel(D.parse(rv.last)) : '?') + ' (' + rv.coverageDays + ' days).' }),
      h('ul', { class: 'facts' },
        h('li', null, h('b', { text: money(rv.totals.spendingCents) }), ' of spending in ' + c.spending + ' purchases'),
        h('li', null, h('b', { text: money(rv.totals.incomeCents) }), ' of income and aid in ' + (c.income + c.aid) + ' deposits'),
        (c.transfer + c.card_payment) ? h('li', null, h('b', { text: money(rv.totals.movedCents) }), ' moved between your own accounts or to pay a card (' + (c.transfer + c.card_payment) + ' rows). Not counted as spending.') : null,
        (c.duplicate + c.future) ? h('li', null, (c.duplicate ? c.duplicate + ' already in your plan' : '') + (c.duplicate && c.future ? ' and ' : '') + (c.future ? c.future + ' dated in the future' : '') + ' (left out)') : null)));
    // 1. columns
    const colsCard = card('1. Did we read the columns correctly?', 'Check that each row below looks like a real transaction.', h('div', null,
      sampleTable(rv.mapping.sample),
      h('details', { class: 'more' }, h('summary', { text: 'These look wrong' }), h('div', { class: 'selects' }, selectCol('Date column', rv, 'date'), selectCol('Description column', rv, 'desc'), selectCol('Amount column', rv, 'amt'))),
      confirmBox('mapping', 'The columns look right', refresh)));
    // 2. spending vs deposits
    const dir = rv.direction, signSel = h('select', { id: 'sign', 'aria-label': 'How to read amounts' });
    [['auto', 'Work it out for me'], ['neg', 'Negative numbers are spending'], ['pos', 'Positive numbers are spending (credit-card style)']].forEach(o => signSel.appendChild(h('option', { value: o[0], text: o[1], selected: (st.rvOpts.signMode || 'auto') === o[0] })));
    signSel.addEventListener('change', () => { st.rvOpts.signMode = signSel.value; rerun(); });
    const acctSel = h('select', { id: 'acct', 'aria-label': 'Account type' });
    [['checking', 'Checking account (moves my balance)'], ['card', 'Credit card (spending only)']].forEach(o => acctSel.appendChild(h('option', { value: o[0], text: o[1], selected: rv.account === o[0] })));
    acctSel.addEventListener('change', () => { st.rvOpts.account = acctSel.value; rerun(); });
    const list = (rows) => h('ul', { class: 'mini' }, rows.map(r => h('li', null, h('span', { text: r.desc }), h('b', { text: money(r.amountCents) }))));
    const dirCard = card('2. Spending versus deposits', dir.note ? dir.note : 'We read each amount as money out (spending) or money in (a deposit).', h('div', null,
      dir.risky ? h('div', { class: 'note amber', role: 'alert' }, icon('alert'), h('span', null, h('b', { text: 'Please check this one. ' }), 'Every amount in this file has the same sign, so we cannot be sure which are purchases. Look at the samples below and change the setting if they are backwards.')) : null,
      h('div', { class: 'two' }, h('div', null, h('h3', { text: 'Read as spending' }), dir.spendingSample.length ? list(dir.spendingSample) : h('p', { class: 'hint', text: 'None found' })), h('div', null, h('h3', { text: 'Read as deposits' }), dir.depositSample.length ? list(dir.depositSample) : h('p', { class: 'hint', text: 'None found' }))),
      h('div', { class: 'selects' }, h('div', { class: 'field inline' }, h('label', { for: 'sign', text: 'How to read amounts' }), signSel), h('div', { class: 'field inline' }, h('label', { for: 'acct', text: 'This file is from a' }), acctSel)),
      confirmBox('direction', 'Spending and deposits are read correctly', refresh)));
    // 3. dates (only when ambiguous)
    let datesCard = null;
    if (need.indexOf('dates') >= 0) {
      const dsel = h('select', { id: 'dord', 'aria-label': 'Date order' });
      [['mdy', 'Month first (03/04 is March 4)'], ['dmy', 'Day first (03/04 is April 3)']].forEach(o => dsel.appendChild(h('option', { value: o[0], text: o[1], selected: rv.dates.order === o[0] })));
      dsel.addEventListener('change', () => { st.rvOpts.dateOrder = dsel.value; rerun(); });
      datesCard = card('3. Which date format is this?', 'Some dates in this file could be read two ways.', h('div', null, h('div', { class: 'field inline' }, h('label', { for: 'dord', text: 'Date order' }), dsel), confirmBox('dates', 'The dates are read correctly', refresh)));
    }
    // 4. rows that need a human
    let rowsCard = null;
    if (rv.attention.length) {
      const items = rv.attention.map(a => {
        const dec = st.decisions[a.idx], name = 'row-' + a.idx;
        const catSel = h('select', { class: 'catsel', 'aria-label': 'Category for ' + a.desc, hidden: '' }); CAT_CHOICES.forEach(cn => catSel.appendChild(h('option', { value: cn, text: cn, selected: cn === dec.category })));
        catSel.addEventListener('change', () => { dec.category = catSel.value; });
        const opts = a.options.map(o => {
          const rb = h('input', { type: 'radio', name, id: name + '-' + o.id, value: o.id, checked: dec.option === o.id });
          const upd = () => { catSel.hidden = !a.options.some(x => x.id === dec.option && x.needsCategory); };
          rb.addEventListener('change', () => { dec.option = o.id; upd(); });
          return h('label', { class: 'opt', for: name + '-' + o.id }, rb, h('span', { text: o.label }), o.id === a.suggested ? badge('suggested', 'soft') : null);
        });
        catSel.hidden = !a.options.some(x => x.id === dec.option && x.needsCategory);
        return h('fieldset', { class: 'row-q' }, h('legend', null, h('span', { class: 'rd', text: dayLabel(D.parse(a.date)) }), h('b', { text: a.desc }), h('span', { class: a.amountCents < 0 ? 'neg' : 'pos', text: money(a.amountCents) })), h('p', { class: 'q', text: a.question }), h('div', { class: 'opts' }, opts), catSel);
      });
      rowsCard = card((datesCard ? '4' : '3') + '. ' + rv.attention.length + (rv.attention.length === 1 ? ' row needs' : ' rows need') + ' your eyes', 'We pre-selected the most likely answer. Change any that are wrong.', h('div', null, items, confirmBox('attention', 'I checked these rows', refresh)));
    }
    refresh();
    return h('div', { class: 'stack' },
      h('section', { class: 'card narrow-lg' }, h('p', { class: 'eyebrow', text: 'Step 2 of 4' }), h('h1', { id: 'title', tabindex: '-1', text: 'Check what we found before it counts' }), h('p', { class: 'lede', text: 'Nothing is added to your plan until you confirm each item below. You can read every row first.' })),
      summary, colsCard, dirCard, datesCard, rowsCard,
      h('section', { class: 'card narrow-lg' }, err.node, h('p', { class: 'hint', text: need.length + ' confirmation' + (need.length === 1 ? '' : 's') + ' needed before you can continue.' }), h('div', { class: 'actions' }, st.hist.length ? button('Back', { kind: 'ghost', icon: 'back', onclick: () => App.back() }) : null, applyBtn)));
  };

  /* ---------- what repeats ---------- */
  App.screens.found = function () {
    const st = App.state, T = App.today(), plan = st.plan, err = errorBox();
    const ds = E.detectedSetup(plan, T), persona = personaOf();
    if (!st.found) { st.found = { bills: {}, incomes: {} }; for (const b of ds.bills) st.found.bills[b.key] = persona ? true : b.preselected; for (const i of ds.incomes) st.found.incomes[i.key] = true; }
    const row = (kind, r, body) => {
      const cb = h('input', { type: 'checkbox', id: kind + '-' + r.key.replace(/\W/g, '_'), checked: !!st.found[kind][r.key] });
      cb.addEventListener('change', () => { st.found[kind][r.key] = cb.checked; });
      return h('label', { class: 'found-row', for: cb.id }, cb, h('span', { class: 'fr-main' }, h('span', { class: 'fr-name', text: r.name }), h('span', { class: 'fr-why', text: r.reason })), h('span', { class: 'fr-amt' }, h('b', { text: body }), r.confidence ? badge(r.confidence === 'high' ? 'sure' : r.confidence === 'medium' ? 'likely' : 'not sure', r.confidence === 'high' ? 'good' : r.confidence === 'medium' ? 'blue' : 'amber') : null));
    };
    const FREQ = { weekly: 'a week', biweekly: 'every 2 weeks', semimonthly: 'twice a month', monthly: 'a month', yearly: 'a year' };
    const billsCard = ds.bills.length ? card('Regular bills we noticed', 'Keep the ones that are real bills. Anything you untick is left out of your plan.', h('div', { class: 'found-list' }, ds.bills.map(b => row('bills', b, money(b.amountCents) + ' ' + (FREQ[b.cadence] || ''))))) : null;
    const incCard = ds.incomes.length ? card('Paychecks we noticed', 'Only income you confirm is counted.', h('div', { class: 'found-list' }, ds.incomes.map(i => row('incomes', i, (i.irregular ? 'about ' : '') + money(i.typicalCents) + ' ' + (FREQ[i.cadence] || '') + (i.irregular ? ' (varies)' : ''))))) : null;
    const empty = !billsCard && !incCard ? card('Nothing repeating yet', 'We did not see a bill or paycheck that repeats often enough to be sure. That is normal with a short history. You will add the important ones in the next steps.') : null;
    const go = () => {
      err.clear();
      const billKeys = ds.bills.filter(b => st.found.bills[b.key]).map(b => b.key), rejectBillKeys = ds.bills.filter(b => !st.found.bills[b.key]).map(b => b.key), incomeKeys = ds.incomes.filter(i => st.found.incomes[i.key]).map(i => i.key);
      const r = E.confirmDetected(plan, T, { billKeys, rejectBillKeys, incomeKeys });
      if (!r.ok) { err.show('Something went wrong saving that.'); return; }
      App.setPlan(r.plan); st.found = null; App.go(App.nextAfterIncome());
    };
    return h('div', { class: 'stack' },
      h('section', { class: 'card narrow-lg' }, h('p', { class: 'eyebrow', text: 'Step 2 of 4' }), h('h1', { id: 'title', tabindex: '-1', text: 'What repeats in your money?' }), h('p', { class: 'lede', text: 'We looked for charges and deposits that come around on a schedule. You decide which are real.' })),
      billsCard, incCard, empty,
      h('section', { class: 'card narrow-lg' }, err.node, App.nav({ back: false, next: { label: 'Save and continue', onclick: go } })));
  };

  // after the money step: ask only what blocks an honest number, otherwise go straight to the optional details
  App.nextAfterIncome = function () {
    const st = App.state, p = st.plan;
    // A file with no paycheck in it (or one the student unticked) still needs one quick, skippable income question.
    // Without it the plan would silently assume no money is coming in, which is the biggest swing in a first plan.
    if (st.step !== 'income' && p.incomes.length === 0 && p.answered.indexOf('no_income') < 0) return 'income';
    return E.trust(p, App.today()).missing.length ? 'needs' : 'optional';
  };
})();

;
/* ===== ui/05-setup.js ===== */
/* ---- Screens 6-8: income, the (at most two) needed answers, and optional details ---- */
(function () {
  'use strict';
  const E = CCE, D = E.D;
  const { h, icon, button, moneyBox, textBox, selectBox, chips, errorBox, badge, card, money, dayLabel } = App;
  const personaSetup = () => { const st = App.state; return st.persona ? E.demoSetup(st.persona, App.today()) : null; };
  const FREQS = [{ value: 'weekly', label: 'Every week' }, { value: 'biweekly', label: 'Every 2 weeks' }, { value: 'semimonthly', label: 'Twice a month' }, { value: 'monthly', label: 'Once a month' }, { value: 'once', label: 'Just one time' }];
  const FREQ_TEXT = { weekly: 'every week', biweekly: 'every 2 weeks', semimonthly: 'twice a month', monthly: 'every month', once: 'one time' };

  /* ---------- a reusable "money coming in" form ---------- */
  App.incomeForm = function (o) {
    o = o || {}; const T = App.today(), preset = o.preset || {};
    let type = preset.type || 'job';
    const typeRow = h('div', { class: 'type-row' }), name = textBox({ label: 'What should we call it? (optional)', value: preset.name || '', max: 60, placeholder: 'Campus job' });
    const amt = moneyBox({ label: 'How much each time (usual amount)', value: preset.amountCents, placeholder: '380.00', hint: 'After taxes, the amount that reaches your account.' });
    const freq = selectBox({ label: 'How often', options: FREQS, value: preset.freq || 'biweekly' });
    const next = textBox({ label: 'Next date it arrives', type: 'date', value: preset.nextDate || D.fmt(T + 7), hint: 'Your best guess is fine. You can correct it later.' });
    const rel = selectBox({ label: 'Can you count on it?', options: [{ value: 'likely', label: 'Yes, it arrives reliably' }, { value: 'uncertain', label: 'Not sure. Do not count it yet' }], value: preset.reliability || (type === 'family' ? 'uncertain' : 'likely'), hint: 'Money you are not sure about is left out of your plan until you say it is reliable.' });
    const irrId = 'irr-' + Math.random().toString(36).slice(2, 7), irr = h('input', { type: 'checkbox', id: irrId, checked: !!preset.irregular }), low = moneyBox({ label: 'The least it has been', value: preset.lowCents, placeholder: '120.00' });
    const irrRow = h('div', { class: 'irr' }, h('label', { class: 'confirm', for: irrId }, irr, h('span', { text: 'The amount changes a lot (hours vary)' })), low.node);
    const relRow = h('div', null, rel.node);
    const err = errorBox();
    const sync = () => { relRow.hidden = !(type === 'family' || type === 'gig' || type === 'other'); irrRow.hidden = !(type === 'job' || type === 'workstudy' || type === 'gig'); low.node.hidden = !irr.checked; };
    const paint = () => { typeRow.textContent = ''; typeRow.appendChild(chips(E.INCOME_CHOICES.map(c => ({ id: c.id, label: c.label })), type, id => { type = id; const c = E.INCOME_CHOICES.find(x => x.id === id); freq.input.value = c.freq; if (id === 'family') rel.input.value = 'uncertain'; else if (id !== 'gig') rel.input.value = 'likely'; paint(); }, 'What kind of money')); sync(); };
    irr.addEventListener('change', sync); paint();
    const submit = () => {
      err.clear(); const amount = amt.get();
      const v = { type, name: name.get(), amountCents: amount, freq: type === 'aid' || type === 'scholarship' ? 'once' : freq.get(), nextDate: next.get(), irregular: !irrRow.hidden && irr.checked, lowCents: !irrRow.hidden && irr.checked ? low.get() : null, reliability: relRow.hidden ? 'likely' : rel.get() };
      if (amount == null) { err.show('Enter how much it is, for example 380.00.'); amt.input.focus(); return; }
      const r = o.onSubmit(v); if (r && r.error) err.show(r.error);
    };
    return h('div', { class: 'form' }, typeRow, name.node, amt.node, h('div', { class: 'two' }, freq.node, next.node), relRow, irrRow, err.node, h('div', { class: 'actions' }, button(o.submitLabel || 'Add this', { kind: 'primary', onclick: submit }), o.extra || null));
  };

  const incomeLine = (inc, onRemove) => h('li', { class: 'item' }, h('span', { class: 'i-main' }, h('b', { text: inc.name }), h('span', { class: 'i-sub', text: money(inc.amountCents) + ' ' + (FREQ_TEXT[inc.schedule.freq] || '') + (inc.reliability === 'uncertain' ? ' · not counted yet (you are not sure)' : '') })), onRemove ? button('Remove', { kind: 'ghost small', aria: 'Remove ' + inc.name, onclick: onRemove }) : null);

  /* ---------- income (manual path, or a bank file with no paycheck in it) ---------- */
  App.screens.income = function () {
    const st = App.state, T = App.today(), setup = personaSetup(), preset = setup && setup.incomes[0] && st.plan.incomes.length === 0 ? setup.incomes[0] : null;
    const cont = () => App.go(App.nextAfterIncome());
    const list = st.plan.incomes.length ? h('ul', { class: 'items' }, st.plan.incomes.map(i => incomeLine(i, () => { const r = E.removeItem(st.plan, 'income', i.id); App.setPlan(r.plan); App.render(); }))) : null;
    const form = App.incomeForm({
      preset, submitLabel: st.plan.incomes.length ? 'Add another' : 'Add this income',
      onSubmit: v => { const r = E.addIncome(st.plan, v); if (!r.ok) return { error: r.error }; App.setPlan(r.plan); App.flash('Added ' + r.plan.incomes[r.plan.incomes.length - 1].name + '.'); App.render(); return null; }
    });
    return h('section', { class: 'card narrow' },
      h('p', { class: 'eyebrow', text: 'Step 2 of 4' }),
      h('h1', { id: 'title', tabindex: '-1', text: 'What money comes in?' }),
      h('p', { class: 'lede', text: 'Paychecks, work-study or help from family. Only what you list is counted, and money you are not sure about is held out until you say it is reliable.' }),
      list, form,
      App.nav({ secondary: button(st.plan.incomes.length ? 'Done adding income' : 'I have no regular income', { kind: 'ghost', onclick: () => { if (!st.plan.incomes.length) { const r = E.markAnswered(st.plan, 'no_income'); App.setPlan(r.plan); } cont(); } }) }));
  };

  /* ---------- the needed answers ---------- */
  function groceriesCard(plan, setup) {
    const err = errorBox(); let pick = null;
    const amt = moneyBox({ label: 'Or type your own monthly amount', value: setup && setup.groceriesCents, placeholder: '260.00' });
    const q = E.QUESTIONS.groceries, row = h('div', null);
    const save = cents => { const r = E.answerQuestion(App.state.plan, 'groceries', cents); if (!r.ok) { err.show(r.error); return; } App.setPlan(r.plan); App.flash('Saved your grocery estimate. You can change it on the budgets screen.'); App.render(); };
    const paint = () => { row.textContent = ''; row.appendChild(chips(q.choices.map(c => ({ id: String(c), label: money(c, { cents: false }) })), pick, id => { pick = id; save(Number(id)); }, 'Typical groceries per month')); };
    paint();
    return card(q.question, q.why, h('div', null, row, amt.node, err.node, button('Save this amount', { onclick: () => { err.clear(); const c = amt.get(); if (c == null || c < 0) { err.show('Enter a monthly amount of $0 or more.'); return; } save(c); } })), 'ask');
  }
  function housingCard(plan, setup) {
    const st = App.state, err = errorBox(), pre = setup && setup.housing && !setup.housing.none ? setup.housing : null;
    let living = plan.meta.living;
    const amt = moneyBox({ label: 'Monthly rent or housing bill', value: pre ? pre.amountCents : null, placeholder: '525.00' });
    const day = selectBox({ label: 'Due on day', options: Array.from({ length: 31 }, (_, i) => ({ value: i + 1, label: String(i + 1) })), value: pre ? pre.day : 1 });
    const noRentId = 'norent-' + Math.random().toString(36).slice(2, 6), noRent = h('input', { type: 'checkbox', id: noRentId });
    const pays = h('div', { class: 'rent-fields' }, h('div', { class: 'two' }, amt.node, day.node), h('label', { class: 'confirm', for: noRentId }, noRent, h('span', { text: 'I do not pay rent or a housing bill' })));
    const liveRow = h('div', null), sync = () => { pays.hidden = living === 'On campus' || living === 'Living with family'; };
    const paint = () => { liveRow.textContent = ''; liveRow.appendChild(chips(E.LIVING.map(l => ({ id: l, label: l })), living, id => { living = id; paint(); }, 'Where you live')); sync(); }; paint();
    const save = () => {
      err.clear(); let p = st.plan;
      if (living !== p.meta.living) { const r = E.setMeta(p, { living }); if (!r.ok) { err.show(r.error); return; } p = r.plan; }
      if (!pays.hidden) {
        let r;
        if (noRent.checked) r = E.answerQuestion(p, 'housing', { none: true });
        else { const c = amt.get(); if (c == null || c <= 0) { err.show('Enter your monthly rent as an amount above $0, or tick the box if you do not pay rent.'); return; } r = E.answerQuestion(p, 'housing', { amountCents: c, day: Number(day.get()), name: 'Rent' }); }
        if (!r.ok) { err.show(r.error); return; } p = r.plan;
      }
      App.setPlan(p); App.flash('Saved your housing answer.'); App.render();
    };
    return card(E.QUESTIONS.housing.question, E.QUESTIONS.housing.why, h('div', null, h('p', { class: 'hint', text: 'Where do you live?' }), liveRow, pays, err.node, button('Save', { onclick: save })), 'ask');
  }
  function matchCard(q) {
    const st = App.state, T = App.today();
    const decide = decision => { const r = E.confirmDepositMatch(st.plan, { incomeId: q.incomeId, nominal: q.nominal, txId: q.txId, decision }); if (r && r.ok) { App.setPlan(r.plan); App.flash('Thanks. That is remembered.'); } App.render(); };
    return card('Is this deposit your ' + q.name + '?', 'A deposit of ' + money(q.txCents) + ' on ' + dayLabel(D.parse(q.txDate)) + ' ("' + q.txDesc + '") might be the ' + money(q.expectedCents) + ' paycheck we expected. Until you say, it is counted once, as the deposit, and the scheduled paycheck is held out.', h('div', { class: 'actions' }, button('Yes, same paycheck', { kind: 'primary', onclick: () => decide('same') }), button('No, different money', { kind: 'ghost', onclick: () => decide('different') })), 'ask');
  }

  App.screens.needs = function () {
    const st = App.state, T = App.today(), plan = st.plan, setup = personaSetup(), t = E.trust(plan, T), cards = [];
    for (const m of t.missing) cards.push(m.id === 'groceries' ? groceriesCard(plan, setup) : m.id === 'housing' ? housingCard(plan, setup) : null);
    for (const q of t.questions.filter(x => !x.blocking && x.kind === 'deposit_match')) cards.push(matchCard(q));
    const open = t.missing.length;
    if (!cards.filter(Boolean).length) return (App.go('optional', { noHistory: true }), h('div'));
    return h('div', { class: 'stack' },
      h('section', { class: 'card narrow-lg' }, h('p', { class: 'eyebrow', text: 'Step 3 of 4' }), h('h1', { id: 'title', tabindex: '-1', text: open ? (open === 1 ? 'One quick answer' : 'Two quick answers') : 'One thing to confirm' }),
        h('p', { class: 'lede', text: open ? 'We could show you a spending number right now, but it would quietly leave something out. These ' + (open === 1 ? 'answer fixes' : 'answers fix') + ' that.' : 'Tell us if this deposit is the paycheck we expected, so it is never counted twice.' })),
      cards,
      h('section', { class: 'card narrow-lg' }, open ? h('p', { class: 'hint', text: 'You can skip this. Without it we will not show a daily spending amount, because it would be misleading.' }) : null, App.nav({ next: { label: open ? 'Skip for now' : 'Continue', onclick: () => App.go('optional') } })));
  };

  /* ---------- optional details ---------- */
  function optionalForm(q, plan, setup) {
    const st = App.state, T = App.today(), err = errorBox(), pre = setup && setup.optional ? setup.optional : {};
    const save = v => { const r = E.answerOptional(App.state.plan, T, q.id, v); if (!r.ok) { err.show((r.errors && r.errors[0]) || r.error || 'That did not save.'); return; } App.setPlan(r.plan); st.openOptional = null; App.flash('Saved: ' + q.title); App.render(); };
    const skip = (label, v) => button(label, { kind: 'ghost', onclick: () => save(v) });
    if (q.id === 'dates') {
      const per = E.currentPeriod(plan, T), s = textBox({ label: 'First day of ' + (per ? per.name : 'the semester'), type: 'date', value: per ? per.start : '' }), e = textBox({ label: 'Last day (finals end)', type: 'date', value: per ? per.end : '' });
      return h('div', { class: 'form' }, h('div', { class: 'two' }, s.node, e.node), err.node, button('Confirm these dates', { onclick: () => { err.clear(); save({ start: s.get(), end: e.get() }); } }));
    }
    if (q.id === 'income') return App.incomeForm({ preset: null, submitLabel: 'Add this income', onSubmit: v => { const r = E.answerOptional(App.state.plan, T, 'income', v); if (!r.ok) return { error: r.error }; App.setPlan(r.plan); st.openOptional = null; App.flash('Added that income.'); App.render(); return null; }, extra: skip('I have no regular income', { none: true }) });
    if (q.id === 'aid') {
      const p0 = pre.aid && !pre.aid.none ? pre.aid : {}, n = textBox({ label: 'Name', value: p0.name || 'Financial aid refund', max: 60 }), a = moneyBox({ label: 'Amount', value: p0.amountCents, placeholder: '1800.00' }), d = textBox({ label: 'Date it arrives', type: 'date', value: p0.date || '', hint: 'Often a week or two after classes start. Your best guess is fine.' });
      return h('div', { class: 'form' }, n.node, h('div', { class: 'two' }, a.node, d.node), err.node, h('div', { class: 'actions' }, button('Add this refund', { onclick: () => { err.clear(); const c = a.get(); if (c == null) { err.show('Enter the amount, for example 1800.00.'); return; } save({ name: n.get(), amountCents: c, date: d.get() }); } }), skip('No refund is coming', { none: true })));
    }
    if (q.id === 'bills') {
      const n = textBox({ label: 'Name', value: '', max: 60, placeholder: 'Phone plan' }), cat = selectBox({ label: 'Type', options: E.BILL_CATEGORIES.filter(c => c !== 'Housing').map(c => ({ value: c, label: c })), value: 'Phone' }), a = moneyBox({ label: 'Monthly amount', placeholder: '45.00' }), d = selectBox({ label: 'Due on day', options: Array.from({ length: 31 }, (_, i) => ({ value: i + 1, label: String(i + 1) })), value: 1 });
      const freq = selectBox({ label: 'Repeat frequency', options: [{ value: 'monthly', label: 'Once a month' }, { value: 'weekly', label: 'Every week' }, { value: 'biweekly', label: 'Every 2 weeks' }, { value: 'yearly', label: 'Once a year' }], value: 'monthly' });
      const next = textBox({ label: 'Next due date', type: 'date', value: D.fmt(T) });
      const sync = () => { const monthly = freq.get() === 'monthly'; d.node.hidden = !monthly; next.node.hidden = monthly; a.node.querySelector('label').textContent = monthly ? 'Monthly amount' : 'Amount each time'; };
      freq.input.addEventListener('change', sync); sync();
      return h('div', { class: 'form' }, n.node, h('div', { class: 'two' }, cat.node, a.node), freq.node, d.node, next.node, err.node, h('div', { class: 'actions' }, button('Add this bill', { onclick: () => { err.clear(); const c = a.get(); if (c == null || c <= 0) { err.show('Enter an amount above $0.'); return; } save({ name: n.get() || cat.get(), category: cat.get(), amountCents: c, day: Number(d.get()), freq: freq.get(), nextDate: next.get() }); } }), skip('No other regular bills', { none: true })));
    }
    if (q.id === 'transport') {
      const a = moneyBox({ label: 'About how much per month', placeholder: '80.00' });
      return h('div', { class: 'form' }, a.node, err.node, h('div', { class: 'actions' }, button('Save', { onclick: () => { err.clear(); const c = a.get(); if (c == null || c < 0) { err.show('Enter a monthly amount of $0 or more.'); return; } save({ cents: c }); } }), skip('I do not spend on this', { none: true })));
    }
    if (q.id === 'reserve') {
      const so = E.safetyOutlook(plan, { today: T, scenario: 'cautious' });
      return h('div', { class: 'form' }, h('p', { text: so.summary }), h('p', { class: 'hint', text: E.HORIZON_EXPLAIN.safety }), h('p', { class: 'hint', text: 'If you turn this on, ' + money(so.recommendedCents) + ' is held back from your spending room, and it shows up in your plan as "reserved". It is not turned on unless you choose it.' }), err.node,
        h('div', { class: 'actions' }, button('Set aside ' + money(so.recommendedCents), { onclick: () => save({ accept: true }) }), skip('Not now', { decline: true })));
    }
    if (q.id === 'cushion') {
      const a = moneyBox({ label: 'Cushion you never plan to spend', value: plan.account.cushionCents, hint: 'It starts at $100. A bigger cushion means a smaller daily amount and more breathing room.' });
      return h('div', { class: 'form' }, a.node, err.node, button('Save cushion', { onclick: () => { err.clear(); const c = a.get(); if (c == null || c < 0) { err.show('Choose $0 or more.'); return; } save({ cents: c }); } }));
    }
    if (q.id === 'name') { const n = textBox({ label: 'First name', value: plan.meta.name, max: 40 }); return h('div', { class: 'form' }, n.node, err.node, button('Save', { onclick: () => save({ name: n.get() }) })); }
    return null;
  }

  App.screens.optional = function () {
    const st = App.state, T = App.today(), plan = st.plan, setup = personaSetup(), qs = E.optionalQuestions(plan, T);
    const doneN = qs.filter(q => q.done).length;
    const items = qs.map(q => {
      const open = st.openOptional === q.id;
      const head = h('button', { type: 'button', class: 'opt-head', 'aria-expanded': open ? 'true' : 'false', onclick: () => { st.openOptional = open ? null : q.id; App.render(); } },
        h('span', { class: 'oh-main' }, h('span', { class: 'oh-title', text: q.title }), h('span', { class: 'oh-sub', text: 'Improves: ' + q.improves })),
        h('span', { class: 'oh-state' }, q.done ? badge('Done', 'good') : q.recommended ? badge('Recommended', 'amber') : badge('Optional', 'soft')));
      return h('div', { class: 'opt-card' + (q.done ? ' done' : '') }, head, open ? h('div', { class: 'opt-body' }, optionalForm(q, plan, setup)) : null);
    });
    const editing = !!st.done;
    return h('div', { class: 'stack' },
      h('section', { class: 'card narrow-lg' }, editing ? null : h('p', { class: 'eyebrow', text: 'Step 3 of 4' }), h('h1', { id: 'title', tabindex: '-1', text: editing ? 'Edit plan details' : 'Make it more accurate (optional)' }),
        h('p', { class: 'lede', text: editing ? 'Change income, bills, dates, cushion or reserve. Your plan updates when you save an item.' : 'Each one says what it improves. Skip any of them, you can come back from your plan.' }), h('p', { class: 'hint', text: doneN + ' of ' + qs.length + ' done' })),
      h('section', { class: 'card narrow-lg' }, h('div', { class: 'opt-list' }, items), App.nav({ next: { label: editing ? 'Back to My plan' : 'Show my budgets', onclick: () => App.go(editing ? 'plan' : 'budgets') } })));
  };
})();

;
/* ===== ui/06-budgets.js ===== */
/* ---- Screen 9: monthly category budgets (proposed by the app, approved by the student) ---- */
(function () {
  'use strict';
  const E = CCE;
  const { h, icon, button, errorBox, badge, card, money, dollarsText, readMoney, dayLabel } = App;
  const CONF_KIND = { student: 'good', high: 'good', medium: 'blue', low: 'amber', none: 'soft' };

  App.screens.budgets = function () {
    const st = App.state, T = App.today(), plan = st.plan, err = errorBox();
    const editing = st.done, snap = E.snapshot(plan, T), pr = E.proposeBudgets(plan, T, snap);
    if (!pr.ok) return card('We need your balance first', pr.error, button('Back to the start', { onclick: () => App.go('basics', { reset: true }) }));
    if (!st.budgetEdits) { st.budgetEdits = {}; for (const r of pr.rows) st.budgetEdits[r.category] = { checked: !editing && r.status === 'proposed' && (r.confidence === 'high' || r.confidence === 'medium'), cents: r.status === 'approved' ? r.amountCents : r.proposedCents }; }
    const edits = st.budgetEdits, totalNote = h('p', { class: 'fit', role: 'status' });
    const draft = () => {
      const items = [];
      let next = plan, removed = 0;
      for (const r of pr.rows) {
        const e = edits[r.category], approved = r.status === 'approved';
        if (!e) continue;
        if (approved && e.remove) { next = E.clearBudgetApproval(next, r.category).plan; removed++; continue; }
        if (!approved && !e.checked) continue;
        if (e.cents == null || e.cents < 0) return { error: 'Enter an amount of $0 or more for ' + r.category + ', or leave it unapproved.' };
        if (approved && e.cents === r.amountCents) continue;
        items.push({ category: r.category, cents: e.cents, fromProposal: !approved && r.status === 'proposed' && e.cents === r.proposedCents, basis: r.basis });
      }
      if (!items.length) return { plan: next, changes: removed };
      const approved = E.approveBudgets(next, items);
      return approved.ok ? { plan: approved.plan, changes: items.length + removed } : { error: approved.errors[0] || 'Could not save those budgets.' };
    };
    const refreshTotal = () => {
      totalNote.className = 'fit';
      const preview = draft();
      if (preview.error) { totalNote.textContent = 'Enter valid amounts to preview the forecast.'; return; }
      const forecast = preview.changes ? E.snapshot(preview.plan, T) : snap;
      const health = E.planHealth(preview.plan, T, forecast);
      if (!health.ok || !E.trust(preview.plan, T, forecast).showAllowance) {
        totalNote.textContent = 'Complete your plan details to check these budgets against your forecast.';
        return;
      }
      const horizon = forecast.cautious.fc.horizon, end = dayLabel(forecast.cautious.fc.endDay);
      const scope = horizon.period ? horizon.period + ' through ' + end : 'Through ' + end;
      const low = money(health.minCents).replace(/^-/, '−') + ' on ' + dayLabel(health.minDay);
      totalNote.className = 'fit ' + (health.okCushion ? 'good' : 'bad');
      totalNote.textContent = (preview.changes ? 'Unsaved budget preview' : 'Approved budgets') + ' · ' + scope + '. ' +
        (health.okCushion ? 'These budgets fit your cautious forecast.' : 'These budgets fall below your cushion in the cautious forecast.') +
        ' The projected low is ' + low + ', ' + (health.okCushion ? 'at or above' : money(health.shortfallCents) + ' below') + ' your ' + money(health.cushionCents) + ' cushion.';
    };
    const rowNode = r => {
      const e = edits[r.category], id = 'b-' + r.category.replace(/\W/g, '_'), approved = r.status === 'approved';
      const amt = h('input', { type: 'text', inputmode: 'decimal', id: id + '-amt', value: e.cents == null ? '' : dollarsText(e.cents), disabled: !!e.remove, 'aria-label': r.category + ' monthly budget in dollars', placeholder: '0.00' });
      amt.addEventListener('input', () => { e.cents = readMoney(amt.value); refreshTotal(); });
      const cb = approved ? null : h('input', { type: 'checkbox', id, checked: !!e.checked, 'aria-label': 'Use this budget for ' + r.category });
      if (cb) cb.addEventListener('change', () => { e.checked = cb.checked; refreshTotal(); });
      const state = approved ? badge(e.remove ? 'Removal pending' : 'Approved', e.remove ? 'amber' : 'good') : r.status === 'proposed' ? badge('Suggested', 'soft') : r.status === 'needs_answer' ? badge('Needs an amount', 'amber') : badge('No estimate', 'soft');
      return h('div', { class: 'brow ' + r.status },
        h('div', { class: 'b-head' }, h('span', { class: 'b-name', text: r.category }), h('span', { class: 'b-kind', text: r.kind === 'essential' ? 'Essential' : 'Flexible' }), state),
        h('div', { class: 'b-meta' }, r.basis !== 'none' ? badge(r.basisLabel, 'soft') : null, r.confidence !== 'none' ? badge(r.confidenceLabel, CONF_KIND[r.confidence]) : null, r.forwardOnly ? badge('Counts from today forward', 'soft') : null),
        r.why ? h('p', { class: 'b-why', text: r.why }) : h('p', { class: 'b-why', text: 'Nothing suggested. Type your own amount and tick the box if you want a budget here.' }),
        h('div', { class: 'b-input' }, h('span', { class: 'cur', 'aria-hidden': 'true', text: '$' }), amt, h('span', { class: 'per', text: 'a month' }), cb ? h('label', { class: 'use', for: id }, cb, h('span', { text: 'Use this' })) :
          h('button', { type: 'button', id: id + '-approval', class: 'btn ghost small', text: e.remove ? 'Keep approval' : 'Remove approval',
            'aria-label': (e.remove ? 'Keep approval for ' : 'Remove approval for ') + r.category,
            onclick: () => { e.remove = !e.remove; App.focusId = id + '-approval'; App.render(); } })));
    };
    const ess = pr.rows.filter(r => r.kind === 'essential'), flx = pr.rows.filter(r => r.kind === 'flexible');
    const save = (target) => {
      err.clear();
      const r = draft(); if (r.error) { err.show(r.error); return; }
      let next = r.plan;
      if (!editing && st.persona && typeof E.seedDemoGoal === 'function') { const g = E.seedDemoGoal(next, st.persona, T); if (g.ok) next = g.plan; }
      App.setPlan(next); st.budgetEdits = null; st.done = true;
      App.go(target, { flash: { msg: r.changes ? 'Budget changes saved.' : 'No budget changes to save.', kind: 'good' } });
    };
    refreshTotal();
    return h('div', { class: 'stack' },
      h('section', { class: 'card narrow-lg' }, editing ? null : h('p', { class: 'eyebrow', text: 'Step 4 of 4' }), h('h1', { id: 'title', tabindex: '-1', text: 'Your monthly budgets' }),
        h('p', { class: 'lede', text: editing ? 'Edit amounts or select budgets to approve. Your plan changes when you save.' : 'Choose which suggested budgets to approve, then save.' }),
        totalNote,
        pr.showAllowance ? h('details', { class: 'sure' }, h('summary', { text: 'How starter budgets are estimated' }),
          h('p', { class: 'hint', text: 'Average monthly equivalent of the saved plan’s flexible allowance from the start of today through term end ' + money(pr.supportedMonthlyFlexibleCents) + '. This estimate helps size starter budgets.' })) : null,
        pr.starterNote ? h('div', { class: 'note amber' }, icon('info'), h('span', { text: pr.starterNote })) : null),
      card('Essentials', 'Set aside first. They reduce your daily spending amount.', h('div', { class: 'brows' }, ess.map(rowNode))),
      card('Flexible spending', 'The cautious forecast includes spending in these categories.', h('div', { class: 'brows' }, flx.map(rowNode))),
      h('section', { class: 'card narrow-lg' }, h('p', { class: 'hint', text: pr.irregularNote }), err.node,
        h('div', { class: 'actions' }, st.hist.length ? button('Back', { kind: 'ghost', icon: 'back', onclick: () => { if (editing) st.budgetEdits = null; App.back(); } }) : null, editing ? null : button('Skip, I will do this later', { kind: 'ghost', onclick: () => { st.budgetEdits = null; st.done = true; if (st.persona && typeof E.seedDemoGoal === 'function') { const g = E.seedDemoGoal(st.plan, st.persona, T); if (g.ok) App.setPlan(g.plan); } App.go(App.homeStep()); } }), button(editing ? 'Save budget changes' : 'Save and show my plan', { big: true, after: 'arrow', onclick: () => save(App.homeStep()) }))));
  };
})();

;
/* ===== ui/07-plan.js ===== */
/* ---- My plan: budgets, income/bills, settings, spending history, forecast details ----
   Every money figure comes from the engine (firstPlan, planHealth, spendingSummary, semesterView.after).
   Nothing here changes a budget, bill, income, cushion or reserve unless the student presses a button that says so. */
(function () {
  'use strict';
  const E = CCE, D = E.D;
  const { h, button, badge, money, dayLabel } = App;

  function PV() {
    const st = App.state;
    if (!st.pv) st.pv = { open: {}, msg: {}, confirm: null, undo: null };
    return st.pv;
  }
  const amount = c => money(c).replace(/^-/, '−');
  const lines = rows => h('dl', { class: 'lines' }, rows.filter(Boolean).map(r => [h('dt', { text: r[0] }), h('dd', { class: r[2] || '', text: r[1] })]));
  const disclosure = (id, title, body, cls) => {
    const open = PV().open;
    return h('details', { id, class: 'sure ' + (cls || ''), open: !!open[id], ontoggle: e => { open[id] = e.target.open; } },
      h('summary', { text: title }), body);
  };
  const msgNode = where => {
    const pv = PV(), m = pv.msg[where]; if (!m) return null;
    return h('div', { class: 'tv-msg ' + m.kind, id: where + '-msg', tabindex: '-1', role: m.kind === 'bad' ? 'alert' : 'status' },
      h('span', { text: m.msg }),
      pv.undo && pv.undo.where === where && m.kind !== 'bad' ? button('Undo this change', { kind: 'ghost small', onclick: () => {
        const u = pv.undo; pv.undo = null; App.setPlan(u.plan); pv.msg = {}; pv.msg[where] = { msg: 'Undone. Your plan is back to how it was.', kind: 'good' };
        App.focusId = where + '-msg'; App.render();
      } }) : null);
  };
  function commit(res, where, msg, o) {
    o = o || {}; const pv = PV();
    if (!res || !res.ok) { pv.msg = {}; pv.msg[where] = { msg: (res && res.error) || 'That did not work. Nothing was changed.', kind: 'bad' }; App.focusId = where + '-msg'; App.render(); return false; }
    pv.undo = o.undo ? { plan: App.state.plan, where } : null;
    App.setPlan(res.plan); pv.msg = {}; if (msg) pv.msg[where] = { msg, kind: o.kind || 'good' }; pv.confirm = null;
    App.focusId = where + '-msg'; App.render(); return true;
  }
  const show = id => { App.state.openOptional = id; App.go('optional'); };
  function incomeBillsCard(fp) {
    const incomeItem = i => h('li', { class: 'item' },
      h('span', { class: 'i-main' },
        h('b', { text: i.name }),
        h('span', { class: 'i-sub', text: money(i.amountCents) + ' · ' + i.freq + (i.next ? ' · next ' + i.next : '') + (i.reliability === 'uncertain' ? ' (not counted: you were not sure)' : '') })),
      button('Edit', { kind: 'ghost small', aria: 'Edit income', onclick: () => show('income') }));
    const billItem = b => h('li', { class: 'item' },
      h('span', { class: 'i-main' },
        h('b', { text: b.name }),
        h('span', { class: 'i-sub', text: money(b.amountCents) + ' · ' + b.freq + (b.next ? ' · next ' + b.next : '') })),
      button('Edit', { kind: 'ghost small', aria: 'Edit bill ' + b.name, onclick: () => show('bills') }));
    return h('section', { class: 'card', 'aria-labelledby': 'ib-h', id: 'inputs' },
      h('h2', { class: 'card-title', id: 'ib-h', text: 'Income and bills' }),
      h('div', { class: 'two plan-inputs' },
        h('div', null,
          h('h3', { text: 'Money coming in' }),
          fp.income.length ? h('ul', { class: 'items' }, fp.income.map(incomeItem)) : h('p', { class: 'hint', text: 'None listed. Nothing is counted as income.' }),
          button('Add income', { kind: 'ghost small', onclick: () => show('income') })),
        h('div', null,
          h('h3', { text: 'Bills' }),
          fp.bills.length ? h('ul', { class: 'items' }, fp.bills.map(billItem)) : h('p', { class: 'hint', text: 'None listed.' }),
          button('Add a bill', { kind: 'ghost small', onclick: () => show('bills') }))));
  }

  function settingsCard(fp, plan, T) {
    const S = fp.safety, dates = fp.dates || S.dates;
    const termLabel = (fp.semester.verified ? fp.semester.name : fp.semester.name + ' (estimated)') +
      (dates && dates.semesterRangeLabel ? ' · ' + dates.semesterRangeLabel : ' · through ' + fp.semester.endLabel);
    return h('section', { class: 'card', 'aria-labelledby': 'ps-h' },
      h('h2', { class: 'card-title', id: 'ps-h', text: 'Plan settings' }),
      h('ul', { class: 'items plan-settings' },
        h('li', { class: 'item' },
          h('span', { class: 'i-main' }, h('b', { text: 'Semester dates' }), h('span', { class: 'i-sub', text: termLabel + (!fp.semester.verified ? ' · Estimated until you confirm' : '') })),
          button('Edit dates', { kind: 'ghost small', onclick: () => show('dates') })),
        h('li', { class: 'item' },
          h('span', { class: 'i-main' }, h('b', { text: 'Check Emergency Funds' }), h('span', { class: 'i-sub', text: money(plan.account.cushionCents) + ' held back — never planned for spending' })),
          button('Edit Amount', { kind: 'ghost small', onclick: () => show('cushion') }))));
  }

  function spendCard(plan, T) {
    const s = E.spendingSummary(plan, T);
    const title = h('h2', { class: 'card-title', id: 'spend-h', tabindex: '-1', text: 'Where your money goes' });
    if (!s.ok || !s.rows.length) return h('section', { class: 'card spend', 'aria-labelledby': 'spend-h' }, title, h('p', { class: 'card-sub', text: s.ok ? s.coverage.note : 'Nothing to show yet.' }));
    const top = Math.max(1, s.rows[0].cents);
    const budgetText = r => {
      if (!r.budget) return null;
      const b = r.budget, over = r.monthCents > b.plannedCents;
      return h('span', { class: 'sp-bud' + (over ? ' over' : ''), text: 'Month to date ' + money(r.monthCents) + ' of ' + money(b.plannedCents) + (over ? ', ' + money(r.monthCents - b.plannedCents) + ' over' : '') });
    };
    const list = h('ul', { class: 'spend-list' }, s.rows.filter(r => r.cents > 0 || r.monthCents > 0).map(r => h('li', { class: 'sp-row k-' + r.kind },
      h('div', { class: 'sp-line' }, h('span', { class: 'sp-cat' }, h('b', { text: r.category }), h('span', { class: 'i-sub', text: r.kindLabel + ' · ' + r.count + ' purchase' + (r.count === 1 ? '' : 's') })), h('span', { class: 'sp-amt' }, h('b', { text: money(r.cents) }), h('span', { class: 'i-sub', text: r.sharePct + '%' }))),
      h('span', { class: 'sp-track', 'aria-hidden': 'true' }, h('span', { class: 'sp-bar', style: 'width:' + Math.max(2, Math.round(r.cents * 100 / top)) + '%' })),
      budgetText(r))));
    const kinds = h('div', { class: 'sp-kinds' }, s.kinds.map(k => h('div', { class: 'sp-kind k-' + k.kind }, h('span', { class: 'sk-l', text: k.label }), h('span', { class: 'sk-v', text: money(k.cents) }))));
    const f = s.fixed, subs = f.subscriptions;
    const fixed = h('div', { class: 'sp-fixed' },
      h('p', null, h('b', { text: 'Committed every month: ' }), money(f.billsMonthlyCents) + ' in listed bills' + (subs.length ? ' and ' + money(f.subscriptionsMonthlyCents) + ' in subscriptions (' + subs.map(x => x.name + ' ' + money(x.monthlyCents)).join(', ') + ')' : '') + '.'),
      f.unconfirmedSubscriptions ? h('p', { class: 'hint', text: plural(f.unconfirmedSubscriptions, 'subscription') + ' found in your bank history but not confirmed yet, so ' + (f.unconfirmedSubscriptions === 1 ? 'it is' : 'they are') + ' not planned as a bill.' }) : null,
      s.unusual.length ? h('p', { class: 'hint', text: 'Large one-offs (' + s.unusual.map(u => u.desc + ' ' + money(u.amountCents)).join(', ') + ') are included above but kept out of your everyday estimate.' }) : null);
    const breakdown = h('div', { id: 'spend-breakdown', class: 'plan-disclosure-body' }, kinds, list, fixed,
      h('p', { class: 'hint', text: 'A look back at what you logged or imported. Nothing here is estimated, and card payments are not counted twice.' }));
    return h('section', { class: 'card spend', 'aria-labelledby': 'spend-h' }, title,
      h('p', { class: 'card-sub', text: s.coverage.note }),
      h('p', { class: 'sp-total' }, h('b', { text: money(s.totalCents) }), ' spent in the last 30 days',
        h('span', { class: 'i-sub', text: ' · Month to date ' + money(s.monthTotalCents) })),
      breakdown);
  }

  App.screens.plan = function () {
    const st = App.state, T = App.today(), plan = st.plan;
    if (!plan) return h('section', { class: 'card' }, h('h1', { id: 'title', tabindex: '-1', text: 'Nothing here yet' }), button('Start', { onclick: () => App.go('welcome', { reset: true }) }));
    const fp = E.firstPlan(plan, T);
    if (!fp.ok) return h('section', { class: 'card' }, h('h1', { id: 'title', tabindex: '-1', text: 'We need your balance first' }), h('p', { text: fp.error }), button('Enter it', { onclick: () => App.go('basics', { reset: true }) }));
    st.done = true; App.save();
    const returning = !!st.home;
    const persona = st.persona ? E.demoPersona(st.persona) : null;


    const intro = h('section', { class: 'card narrow-lg intro' },
      h('p', { class: 'eyebrow', text: persona ? 'Sample student: ' + persona.name + ' (made-up data)' : (returning ? 'Your plan' : 'Your first plan') }),
      h('h1', { id: 'title', tabindex: '-1', text: plan.meta.name ? plan.meta.name + ', here is your plan' : (returning ? 'My plan' : 'Here is your first plan') }));

    const t = fp.trust;
    const need = (!t.showAllowance && t.missing && t.missing[0])
      ? h('section', { class: 'card hero-plan warn' },
        h('div', { class: 'hp-top' }, badge(t.badge, 'warn')),
        h('h2', { class: 'hp-need', text: 'We are not showing a daily spending amount yet' }),
        h('p', { text: t.summary }),
        h('div', { class: 'need-q' }, h('p', null, h('b', { text: t.missing[0].question })), h('p', { class: 'hint', text: t.missing[0].why }), button('Answer this', { onclick: () => App.go('needs') })))
      : null;

    const cta = returning || need ? null : h('section', { class: 'card narrow-lg cta-today' },
      h('div', null, h('h2', { class: 'card-title', text: 'Your daily view is ready' }),
        h('p', { class: 'card-sub', text: 'Today shows what you can spend, lets you check a purchase before you make it, and keeps your bills and paychecks in sight.' })),
      h('div', { class: 'row-actions' }, button('Open my Today screen', { big: true, after: 'arrow', onclick: () => { st.home = true; App.go('today', { reset: true }); } })));

    const next = returning ? null : h('p', { class: 'next-note', text: 'This is your starting plan. Today is the daily view, Semester is the term picture, and Goals is where you save for something specific.' });

    return h('div', { class: 'stack plan' },
      intro, need, cta,
      h('div', { class: 'row-actions' }, button('Add a repeated expense', { kind: 'primary', onclick: () => show('bills') })),
      incomeBillsCard(fp),
      spendCard(plan, T),
      settingsCard(fp, plan, T),
      next);
  };

  const plural = (n, w) => n + ' ' + w + (n === 1 ? '' : 's');
})();

;
/* ===== ui/08-today.js ===== */
/* ---- Stage 3: the Today screen ----
   First-time path: Can I spend right now? What’s coming up? What should I do next?
   Every number comes from E.todayView(plan, today). The UI never does money arithmetic.
   Nothing changes a budget, bill, income or reserve unless the student presses a button that says so. */
(function () {
  'use strict';
  const E = CCE, D = E.D;
  const { h, icon, button, badge, money, dollarsText, readMoney, dayLabel, longDay, moneyBox, selectBox, errorBox, levelKind } = App;
  const LOG_CATS = ['Groceries', 'Dining out', 'Transportation', 'Entertainment', 'Shopping', 'Personal', 'Health', 'School supplies', 'Travel', 'Fees', 'Other'];
  const NATURE_KIND = { confirmed: 'good', scheduled: 'blue', expected: 'amber', uncertain: 'soft' };
  const plural = (n, w) => n + ' ' + w + (n === 1 ? '' : 's');
  const when = n => n === 0 ? 'today' : n === 1 ? 'tomorrow' : n === -1 ? 'yesterday' : n > 0 ? 'in ' + n + ' days' : (-n) + ' days ago';
  const signed = c => (c < 0 ? '\u2212' : '+') + money(Math.abs(c));
  let CUR = null, uid = 0;
  const nid = p => 'tv' + (++uid) + '-' + p;

  function TV() {
    const st = App.state;
    if (!st.tv) st.tv = { check: { amountText: '', desc: '', category: '', result: null, detailsOpen: false }, log: { amountText: '', cat: 'Dining out', date: '', desc: '' }, edit: null, open: null, openForm: null, confirmDel: null, showAllUp: false, showMore: false, checkInOpen: false, checkInText: '', msg: {}, dup: null, ideasOpen: false, logOpen: false, recentOpen: false, shortfallPreview: false };
    return st.tv;
  }
  const msgNode = where => { const m = TV().msg[where]; return m ? h('p', { class: 'tv-msg ' + m.kind, id: where + '-msg', tabindex: '-1', role: m.kind === 'bad' ? 'alert' : 'status', text: m.msg }) : null; };

  function commit(res, where, msg, o) {
    o = o || {}; const tv = TV();
    if (!res || !res.ok) { tv.msg = {}; tv.msg[where] = { msg: (res && res.error) || 'That did not work. Nothing was changed.', kind: 'bad' }; App.focusId = where + '-msg'; App.render(); return false; }
    App.setPlan(res.plan); tv.msg = {}; if (msg) tv.msg[where] = { msg, kind: o.kind || 'good' };
    if (!o.keepCheck) tv.check.result = null;
    tv.open = null; tv.openForm = null; tv.dup = null; tv.edit = null; tv.confirmDel = null; tv.checkInOpen = false;
    App.focusId = o.focus || (msg ? where + '-msg' : where); App.render(); return true;
  }
  const go = (screen, open) => { const st = App.state; if (open) st.openOptional = open; if (screen === 'import') st.path = 'csv'; App.go(screen); };

  function runOp(op, recId) {
    const T = App.today(), plan = App.state.plan, where = 'rec';
    switch (op.type) {
    case 'goto': return go(op.screen, op.open);
    case 'resolve': return commit(E.resolveOccurrence(plan, { type: op.kind, id: op.id, nominal: op.nominal, status: op.status, amountCents: op.amountCents }, T), where, op.status === 'paid' ? 'Marked as received. The plan has been updated.' : 'Okay. It stays on your list as not arrived yet.');
    case 'match': return commit(E.confirmDepositMatch(plan, { incomeId: op.incomeId, nominal: op.nominal, txId: op.txId, decision: op.decision }), where, op.decision === 'same' ? 'Linked. That paycheck is now counted once, as the real deposit.' : 'Okay. The deposit and the scheduled paycheck stay separate.');
    case 'dismiss': return commit(E.dismissRecommendation(plan, recId, T), where, '', { focus: 'title' });
    default: return null;
    }
  }

  /* ---------- intro ---------- */
  function intro(v, plan) {
    const st = App.state, persona = st.persona ? E.demoPersona(st.persona) : null, name = plan.meta.name;
    const sc = persona && E.demoScenarioDays(persona.id);
    const eye = persona
      ? ('Sample student: ' + persona.name + ' (made-up data)' + (sc && st.demoViewDay != null ? '; fixed sample date ' + sc.viewLabel : ''))
      : longDay(v.today);
    return h('section', { class: 'today-head' },
      h('div', null,
        h('p', { class: 'eyebrow', text: eye }),
        h('h1', { id: 'title', tabindex: '-1', text: (name ? name + ', here is today' : 'Here is today') }),
        persona ? h('p', { class: 'sub', text: longDay(v.today) + '. ' + persona.tagline }) : null));
  }

  /* ---------- 1. spending answer ---------- */
  // The positive summary is the room for all flexible spending. The one-purchase limit stays on the checker.
  function positiveRoom(v) {
    const p = v.pace, split = v.roomSplit;
    const short = !!(split && split.safeToSpendCents === 0) || !p.recommendSpend;
    return !!(p.shown && !short && p.safe && !p.over && split && split.safeToSpendCents > 0);
  }
  function spendingAnswer(v, plan) {
    const p = v.pace, split = v.roomSplit, health = v.planHealth, cushion = plan.account.cushionCents;
    if (!p.shown) {
      return h('section', { class: 'card hero-plan hero-today warn spend-answer', 'aria-labelledby': 'hero-h' },
        h('div', { class: 'hp-top' }, badge(p.badge, 'warn'), h('span', { class: 'hp-label', id: 'hero-h', text: 'Your daily spending amount' })),
        h('div', { class: 'hp-num' }, h('span', { class: 'pace-num hp-need', text: 'Not shown yet' })),
        h('p', { class: 'hp-sub', text: p.hidden || 'Campus Compass is missing something it needs to give you an honest number.' }),
        p.question ? h('div', { class: 'need-q' }, h('b', { text: p.question.question }), h('p', { class: 'hint', text: p.question.why }), button('Answer this', { kind: 'ghost', onclick: () => go('needs') })) : null);
    }

    const short = !!(split && split.safeToSpendCents === 0) || !p.recommendSpend;
    const over = p.over;

    // The engine already decided this amount is safe. The figure is that room; how sure it is comes from the same badge.
    if (positiveRoom(v)) {
      const lim = v.purchaseLimit && v.purchaseLimit.ok ? v.purchaseLimit : null;
      const planned = lim && lim.plannedSpendingCents > 0 ? h('p', { class: 'hp-sub', id: 'spend-planned', text: 'Includes ' + money(lim.plannedSpendingCents) + ' you\'ve already planned to spend.' }) : null;
      return h('section', { class: 'card hero-plan hero-today spend-answer', 'aria-labelledby': 'hero-h' },
        h('div', { class: 'hp-top' }, h('span', { class: 'hp-label', id: 'hero-h', text: 'Flexible spending room through ' + dayLabel(p.endDay) })),
        h('div', { class: 'hp-num' }, h('span', { class: 'pace-num', text: money(split.safeToSpendCents) }), h('span', { class: 'per', id: 'hero-confidence', text: ' ' + String(p.badge || '').toLowerCase() })),
        planned);
    }

    if (!short && p.safe && over) {
      return h('section', { class: 'card hero-plan hero-today amber spend-answer', 'aria-labelledby': 'hero-h' },
        h('div', { class: 'hp-top' }, badge('Over pace', 'amber'), h('span', { class: 'hp-label', id: 'hero-h', text: 'Over today\'s pace by' })),
        h('div', { class: 'hp-num' }, h('span', { class: 'pace-num', text: money(Math.abs(p.remainingTodayCents)) }), h('span', { class: 'per', text: ' over' })),
        h('p', { class: 'hp-sub', text: 'You have spent ' + money(p.spentTodayCents) + ' today against a pace of ' + money(p.allowanceCents) + '.' }),
        h('div', { class: 'row-actions' }, button('Can I afford this?', { kind: 'primary small', onclick: () => { App.focusId = 'check-amt'; } })));
    }

    // $0 safe to spend under the current plan
    let reason, action;
    if (!p.safe) {
      reason = 'Your listed bills and essentials already use up your ' + money(cushion) + ' cushion' + (p.shortfall.firstDay ? ' around ' + dayLabel(p.shortfall.firstDay) : '') + '.';
      action = button('See the semester', { kind: 'primary small', onclick: () => App.go('semester', { reset: true }) });
    } else if (p.budgetsBreakCushion || (health && health.ok && !health.okCushion)) {
      reason = 'Spending your approved budgets in full would take you below your ' + money(cushion) + ' cushion.';
      action = button('Review budgets', { kind: 'primary small', onclick: () => { App.state.budgetEdits = null; App.go('budgets'); } });
    } else if (split && split.gapCents > 0) {
      reason = 'About ' + money(split.gapCents) + ' of after-term need is still uncovered, so this plan is not labeled safe to spend yet.';
      action = button('Review in My plan', { kind: 'primary small', onclick: () => App.go('plan') });
    } else {
      reason = 'Your current plan leaves no room for extra spending.';
      action = button('Review budgets', { kind: 'primary small', onclick: () => { App.state.budgetEdits = null; App.go('budgets'); } });
    }

    return h('section', { class: 'card hero-plan hero-today amber spend-answer', 'aria-labelledby': 'hero-h' },
      h('div', { class: 'hp-top' }, h('span', { class: 'hp-label', id: 'hero-h', text: 'Safe to spend under your current plan' })),
      h('div', { class: 'hp-num' }, h('span', { class: 'pace-num', text: money(0) })),
      h('p', { class: 'hp-sub', id: 'spend-reason', text: reason }),
      h('div', { class: 'row-actions' }, action));
  }

  /* ---------- spending details (collapsed) ---------- */
  function bar(spent, allow, label) {
    const over = spent > allow, pct = allow <= 0 ? (spent > 0 ? 100 : 0) : Math.min(100, Math.round(100 * spent / allow));
    return h('div', { class: 'pbar' + (over ? ' over' : ''), role: 'img', 'aria-label': label }, h('span', { class: 'pfill', style: 'width:' + pct + '%' }));
  }
  function spendingDetails(v, plan) {
    const p = v.pace, g = v.progress;
    const row = (title, x, endText) => {
      const left = x.remainingCents, over = left < 0, txt = 'Spent ' + money(x.spentCents) + ' of ' + money(x.allowanceCents) + (endText ? ', ' + endText : '');
      return h('div', { class: 'prow' }, h('div', { class: 'prow-h' }, h('b', { text: title }), h('span', { class: 'prow-v ' + (over ? 'neg' : ''), text: over ? money(-left) + ' over pace' : money(left) + ' remaining at this pace' })), bar(x.spentCents, x.allowanceCents, title + ': ' + txt), h('p', { class: 'prow-s', text: txt }));
    };
    const tomorrowDiffers = p.tomorrowCents != null && p.tomorrowCents !== p.allowanceCents;
    const paceLine = p.shown ? (p.spentTodayCents > 0
      ? 'You have spent ' + money(p.spentTodayCents) + ' of today\'s ' + money(p.allowanceCents) + ' pace.'
      : 'The daily pace is ' + money(p.allowanceCents) + ' if you follow it.') : '';
    const grocery = v.scenario && v.scenario.ideas && v.scenario.ideas.find(i => i.id === 'trim-Groceries');
    const improvement = grocery ? h('details', { class: 'sure', id: 'spend-calc' },
      h('summary', { text: 'What could improve it' }),
      h('ul', { class: 'ideas' }, h('li', null,
        h('b', { text: grocery.title }),
        h('span', { class: 'idea-gain', text: money(grocery.paceBeforeCents) + ' to ' + money(grocery.paceAfterCents) + ' a day' }),
        h('p', { class: 'hint', text: grocery.detail })))) : null;
    const body = h('div', { class: 'spend-details-body' },
      h('p', { class: 'card-sub', id: 'spend-assume', text: 'These amounts depend on following the forecast’s spending assumptions.' }),
      paceLine ? h('p', { id: 'spend-pace', text: paceLine }) : null,
      tomorrowDiffers ? h('p', { class: 'hint', text: 'Tomorrow’s pace is ' + money(p.tomorrowCents) + ' if you follow it.' }) : null,
      h('div', { class: 'prows' }, row('Today', g.today), row('This week', g.week, 'through ' + dayLabel(g.week.endDay)), row('This month', g.month, 'through ' + dayLabel(g.month.endDay))),
      improvement);
    return h('details', { class: 'card sure spend-details', id: 'spend-details' },
      h('summary', { id: 'prog-h' }, h('span', { class: 'card-title', text: 'Extra cash after spending' })),
      body);
  }

  /* ---------- shortfall: one warning, and a preview only when the forecast supports it ---------- */
  const amount = c => money(c).replace(/^-/, '\u2212');
  function shortfallNotice(plan, T) {
    const n = E.todayShortfall(plan, T);
    if (!n || !n.ok || !n.show) return null;
    const tv = TV();
    let lead = 'The balance could reach ' + amount(n.lowCents) + ' on ' + dayLabel(n.lowDay);
    if (n.rent) lead = money(n.rent.amountCents) + ' rent is due ' + dayLabel(n.rent.day) + ', and the balance could reach ' + amount(n.lowCents) + ' on ' + dayLabel(n.lowDay);
    if (n.payday) lead += n.payday.daysBefore === 1 ? ', one day before payday' : ', ' + plural(n.payday.daysBefore, 'day') + ' before payday';
    lead += '.';
    const rec = n.recommendation && n.recommendation.supported ? n.recommendation : null;
    const shift = App.state.persona === 'maya' && plan.incomes.find(i => i.name === 'Extra campus shift');
    const shiftDay = shift && shift.schedule && D.parse(shift.schedule.anchor);
    const shiftNote = shiftDay != null && shiftDay > n.lowDay
      ? h('p', { class: 'hint', text: shift.name + ' adds ' + amount(shift.amountCents) + ' on ' + dayLabel(shiftDay) + ', after this low. It helps later but does not prevent the shortfall.' })
      : null;
    const between = rec && rec.between && rec.between.available ? rec.between : null;
    const whole = c => c % 100 === 0 ? money(c, { cents: false }) : money(c);
    const through = rec && rec.between && rec.between.termEndDay != null
      ? 'This protects your ' + whole(n.cushionCents) + ' cushion through ' + dayLabel(rec.between.termEndDay) + '.'
      : 'This protects your ' + whole(n.cushionCents) + ' cushion.';
    const still = !between ? ''
      : between.afterCents === 0
        ? (between.endedBy === 'aid' ? ' That covers the cash shortfall before your next aid refund.' : ' That covers the cash shortfall between semesters.')
        : ' You\'d still be ' + money(between.afterCents) + ' short ' + (between.endedBy === 'aid' ? 'before your next aid refund.' : 'between semesters.');
    const preview = rec && tv.shortfallPreview ? h('div', { class: 'note shortfall-preview', id: 'shortfall-preview', tabindex: '-1', role: 'region', 'aria-label': 'Preview of the suggested change' },
      h('p', { class: 'preview-line', id: 'shortfall-term' },
        h('span', { text: 'Lowest balance this semester' }),
        h('b', { text: amount(n.lowCents) + ' \u2192 ' + amount(rec.afterMinCents) })),
      between ? h('p', { class: 'preview-line', id: 'shortfall-bridge' },
        h('span', { text: 'Cash shortfall between semesters' }),
        h('b', { text: money(between.beforeCents) + ' \u2192 ' + money(between.afterCents) })) : null,
      h('p', { id: 'shortfall-support', text: 'Spending about ' + E.fmt(rec.aboutWeeklyCents, { cents: false }) + ' less per week. ' + through + still }),
      h('p', { class: 'hint', text: 'This is a preview. Your plan has not changed.' }),
      h('div', { class: 'row-actions' }, button('Review reserve', { kind: 'ghost small', id: 'shortfall-review-reserve', onclick: reviewReserve }))) : null;
    return h('section', { class: 'card amber-card shortfall-notice', id: 'shortfall-notice', 'aria-labelledby': 'shortfall-h' },
      h('h2', { class: 'card-title', id: 'shortfall-h', text: 'You could run short' }),
      h('p', { id: 'shortfall-why', text: lead }),
      shiftNote,
      rec ? h('div', { class: 'row-actions' }, button(tv.shortfallPreview ? 'Hide preview' : 'Preview this change', { kind: 'primary small', id: 'shortfall-preview-btn', onclick: () => { tv.shortfallPreview = !tv.shortfallPreview; App.focusId = tv.shortfallPreview ? 'shortfall-preview' : 'shortfall-preview-btn'; App.render(); } })) : null,
      preview);
  }

  function reviewReserve() {
    go('optional', 'reserve');
  }

  /* ---------- after-term alert ---------- */
  function afterTermAlert(v) {
    const a = v.status && v.status.afterTerm; if (!a || !(a.gapCents > 0)) return null;
    const dates = a.bridgeRangeLabel ? 'Covers ' + a.bridgeRangeLabel + (a.aidLabel ? ' (' + a.aidLabel + ')' : '') + '.' : (a.untilDay ? 'Through ' + dayLabel(a.untilDay) + '.' : '');
    return h('section', { class: 'card after-alert amber-card', 'aria-labelledby': 'after-h', id: 'after-term' },
      h('h2', { class: 'card-title', id: 'after-h', text: 'After the semester' }),
      h('p', { class: 'after-lead', id: 'after-lead' }, h('b', { text: money(a.gapCents) + ' still to set aside' })),
      dates ? h('p', { class: 'hint', id: 'after-dates', text: dates }) : null,
      h('div', { class: 'row-actions' }, button('Review reserve', { kind: 'ghost small', onclick: reviewReserve })));
  }

  /* ---------- one actionable warning not already covered by the spending answer or after-term ---------- */
  function actionNote(v) {
    const r = v.recommendation && v.recommendation.top; if (!r) return null;
    const id = r.id || '';
    if (id.startsWith('goal_')) return null;
    if (/budget|cushion|shortfall|break/i.test(id)) return null;
    if (/reserve|winter|bridge|after.?term/i.test(id)) return null;
    if ((r.actions || []).some(a => a.op && (a.op.type === 'reserve' || a.op.type === 'reserveFixed'))) return null;
    const ic = { bad: 'alert', amber: 'alert', blue: 'info', good: 'check' }[r.tone] || 'star';
    const warningStyle = App.state.persona === 'jordan' && (r.tone === 'amber' || r.tone === 'bad');
    return h('section', { class: 'card rec tone-' + r.tone + (warningStyle ? ' amber-card' : ''), 'aria-labelledby': 'rec-h', id: 'rec' },
      h('div', { class: 'st-top' }, h('span', { class: 'rec-ico' }, icon(ic, 20)), h('div', null, h('p', { class: 'eyebrow', text: r.priority >= 90 ? 'Needs your attention' : 'Worth knowing' }), h('h2', { class: 'card-title', id: 'rec-h', text: r.title }))),
      h('p', { text: r.body }),
      r.evidence.length ? h('ul', { class: 'evidence' }, r.evidence.map(e => h('li', { text: e }))) : null,
      msgNode('rec'),
      (r.actions.length || r.dismissible) ? h('div', { class: 'row-actions' }, r.actions.map(a => button(a.label, { kind: a.kind === 'primary' ? 'primary small' : 'ghost small', onclick: () => runOp(a.op, r.id) })), r.dismissible ? button('Hide for today', { kind: 'ghost small', onclick: () => runOp({ type: 'dismiss' }, r.id) }) : null) : null,
      r.actions.length ? h('p', { class: 'hint', text: 'Nothing happens until you press a button.' }) : null);
  }

  /* ---------- one goal reminder ---------- */
  function goalReminder(v) {
    const goals = v.goals && v.goals.goals ? v.goals.goals.filter(g => g.goalStatus === 'active' && !g.onTrack) : [];
    if (!goals.length) return null;
    const g = goals[0];
    const progress = bar(g.confirmedCents, g.targetCents, g.name + ': ' + money(g.confirmedCents) + ' of ' + money(g.targetCents) + ' saved');
    progress.classList.add('goal-bar');
    return h('section', { class: 'card goal-remind', 'aria-labelledby': 'gt-h', id: 'goal-remind' },
      h('h2', { class: 'card-title', id: 'gt-h', text: g.name }),
      h('p', { id: 'goal-progress', text: money(g.confirmedCents) + ' of ' + money(g.targetCents) + ' saved' + (g.dueDay != null ? ' \u00b7 Due ' + dayLabel(g.dueDay) : '') }),
      progress,
      h('div', { class: 'row-actions' }, button('View goal', { kind: 'ghost small', onclick: () => App.go('goals', { reset: true }) })));
  }

  /* ---------- 2. Can I afford this? ---------- */
  function dupPrompt(where) {
    const tv = TV(); if (!tv.dup || tv.dup.where !== where) return null;
    const d = tv.dup;
    return h('div', { class: 'note amber dup', id: where + '-dup', tabindex: '-1', role: 'alert' }, icon('alert'),
      h('div', { class: 'dup-body' }, h('b', { text: 'This looks like a purchase you already have.' }),
        h('ul', { class: 'dup-list' }, d.duplicates.slice(0, 3).map(x => h('li', { text: dayLabel(D.parse(x.date)) + ', ' + x.desc + ', ' + money(-x.amountCents) + (x.source === 'manual' ? ' (you typed this)' : ' (from your bank file)') }))),
        h('p', { class: 'small', text: 'Logging it again would count it twice. If it really is a second purchase, log it anyway.' }),
        h('div', { class: 'row-actions' }, button('It is new, log it anyway', { kind: 'primary small', onclick: () => attemptLog(Object.assign({}, d.o, { force: true }), where) }), button('Do not log it', { kind: 'ghost small', onclick: () => { tv.dup = null; App.focusId = null; App.render(); } }))));
  }
  function attemptLog(o, where) {
    const T = App.today(), tv = TV(), plan = App.state.plan, r = E.logPurchase(plan, o, T);
    if (r.needsConfirm) { tv.dup = { where, o, duplicates: r.duplicates }; tv.msg = {}; App.focusId = where + '-dup'; return App.render(); }
    if (!r.ok) return commit(r, where);
    const before = CUR, after = E.todayView(r.plan, T), cat = o.category || 'Other';
    let msg = 'Logged ' + money(o.amountCents) + ' for ' + cat + '. It is recorded spending, not an estimate, and your approved budgets did not change.';
    if (E.catKind(cat) === 'essential') { if (before && before.pace.shown && after.ok && after.pace.shown) msg += ' ' + cat + ' is an everyday essential, so money was already set aside for it. It lowers your pace only by what goes beyond that: your daily pace goes from ' + money(before.pace.allowanceCents) + ' to ' + money(after.pace.allowanceCents) + '.'; }
    else if (before && before.pace.shown && after.ok && after.pace.shown) msg += ' Left today: ' + money(before.pace.remainingTodayCents) + ' to ' + money(after.pace.remainingTodayCents) + '.';
    if (where === 'log') { tv.log.amountText = ''; tv.log.desc = ''; tv.recentOpen = true; tv.logOpen = true; }
    if (where === 'check') { tv.check.amountText = ''; tv.check.desc = ''; tv.check.category = ''; }
    commit(r, where, msg);
  }

  function resultNode(r, v) {
    const tv = TV(), T = v.today;
    if (r.needsInfo || r.verdict === 'needs_info' || r.classification === 'needs_info') {
      return h('div', { class: 'cr tone-grey', id: 'check-result', tabindex: '-1', role: 'region', 'aria-label': 'Answer' },
        h('div', { class: 'cr-top' }, badge('Needs more information', 'amber')),
        h('p', { class: 'cr-head' }, h('b', { text: r.headline })), h('p', { class: 'cr-sum', text: r.summary }), button('Answer this', { kind: 'primary small', onclick: () => go('needs') }));
    }
    const CLASS = { affordable: ['Affordable', 'good'], needs_changes: ['Possible with changes', 'amber'], unaffordable: ['Unaffordable', 'warn'] };
    const VERDICT = { yes: ['Yes', 'good'], yes_but: ['Yes, but', 'amber'], only_if: ['Only if', 'amber'], not_now: ['Not right now', 'warn'] };
    const classBadge = CLASS[r.classification] || CLASS.unaffordable;
    const verdictBadge = VERDICT[r.verdict] || null;
    const sel = selectBox({ label: 'Counts as', value: r.category, options: LOG_CATS.concat(LOG_CATS.indexOf(r.category) < 0 ? [r.category] : []).map(c => ({ value: c, label: c })), hint: r.categoryPicked ? '' : 'Guessed from what you typed. Change it if it is wrong.' });
    sel.input.addEventListener('change', () => { tv.check.category = sel.input.value; runCheck(null, true); });
    const alts = (r.alternatives || []).filter(a => a.available);
    const GOAL_KINDS = { pause_goals: 1, adjust_savings: 1, later_deadline: 1, priority: 1 };
    const goalLine = g => {
      const c = g.contributionCents;
      if (c && typeof c === 'object') return g.name + ': ' + money(c.before) + ' → ' + money(c.after) + ' per transfer' + (g.onTrack && g.onTrack.before && !g.onTrack.after ? ', would fall off track' : '');
      return g.name + (g.changed ? ' would change' : '');
    };
    const altAction = a => {
      if (a.kind === 'delay') return null;
      if (a.kind === 'reduce_discretionary') return button('Review budgets', { kind: 'ghost small', onclick: () => { App.state.budgetEdits = null; App.go('budgets'); } });
      if (GOAL_KINDS[a.kind]) return button('Open Goals', { kind: 'ghost small', onclick: () => App.go('goals', { reset: true }) });
      return button('Open My plan', { kind: 'ghost small', onclick: () => App.go('plan') });
    };
    const topAlt = alts[0] || null;
    let nextAction = null;
    if (r.classification === 'affordable') {
      nextAction = button('Log this purchase', { kind: 'primary small', onclick: () => attemptLog({ amountCents: r.amountCents, category: r.category, desc: r.desc, date: D.fmt(T) }, 'check') });
    } else if (topAlt && topAlt.kind === 'reduce_discretionary') {
      nextAction = button('Review budgets', { kind: 'primary small', onclick: () => { App.state.budgetEdits = null; App.go('budgets'); } });
    } else if (topAlt && GOAL_KINDS[topAlt.kind]) {
      nextAction = button('Open Goals', { kind: 'primary small', onclick: () => App.go('goals', { reset: true }) });
    } else if (r.verdict === 'not_now' || r.classification === 'unaffordable') {
      nextAction = button('Log it anyway', { kind: 'ghost small', onclick: () => attemptLog({ amountCents: r.amountCents, category: r.category, desc: r.desc, date: D.fmt(T) }, 'check') });
    } else {
      nextAction = button('Open My plan', { kind: 'primary small', onclick: () => App.go('plan') });
    }
    const showAdvice = r.advice && r.advice.length && !(alts.length && r.classification === 'needs_changes');
    const details = h('details', { class: 'sure' },
      h('summary', { text: 'See details' }),
      h('ul', { class: 'cr-lines' }, r.lines.filter(l => l.text).map(l => h('li', { class: 'tone-' + l.tone }, h('span', { class: 'dot', 'aria-hidden': 'true' }), h('div', null, h('b', { text: l.title + ': ' }), l.text)))),
      alts.length && r.classification !== 'affordable' ? h('div', { class: 'cr-alts' }, h('h3', { text: 'Realistic alternatives' }), alts.map(a => h('article', { class: 'cr-alt' }, h('p', { text: a.text }), a.goals && a.goals.some(g => g.changed) ? h('ul', { class: 'hint-list' }, a.goals.filter(g => g.changed).map(g => h('li', { text: goalLine(g) }))) : null, altAction(a)))) : null);
    return h('div', { class: 'cr tone-' + r.tone, id: 'check-result', tabindex: '-1', role: 'region', 'aria-label': 'Answer for ' + money(r.amountCents) },
      h('div', { class: 'cr-top' }, badge(classBadge[0], classBadge[1]), verdictBadge ? badge(verdictBadge[0], verdictBadge[1]) : null, h('b', { class: 'cr-amt', text: money(r.amountCents) + (r.desc ? ' for ' + r.desc : '') })),
      h('p', { class: 'cr-head' }, h('b', { text: r.headline })),
      h('p', { class: 'cr-sum', text: r.summary || r.headline }),
      showAdvice ? h('div', { class: 'cr-advice' }, h('h3', { text: 'What would help' }), h('ul', null, r.advice.map(a => h('li', { text: a.text })))) : null,
      sel.node,
      h('p', { class: 'hint', text: 'Nothing has been recorded. Your plan changes only if you log it or accept a change.' }),
      h('div', { class: 'row-actions' }, nextAction, button('Clear', { kind: 'ghost small', onclick: () => { tv.check.result = null; tv.check.amountText = ''; tv.check.desc = ''; tv.check.category = ''; App.focusId = 'check-amt'; App.render(); } })),
      dupPrompt('check'), msgNode('check'), details);
  }

  function runCheck(err, keepFocus) {
    const tv = TV(), c = tv.check, T = App.today(), cents = readMoney(c.amountText);
    if (cents == null || cents <= 0) { c.result = null; if (err) err.show('Enter an amount above $0, like 75 or 75.00.'); App.focusId = 'check-amt'; return err ? null : App.render(); }
    const r = E.purchaseCheck(App.state.plan, { today: T, amountCents: cents, desc: c.desc, category: c.category });
    if (!r.ok) { c.result = null; if (err) err.show(r.error); return; }
    c.result = r; c.detailsOpen = false; tv.msg = {}; App.focusId = keepFocus ? 'check-result' : 'check-result'; App.render();
  }

  function checkerCard(v) {
    const tv = TV(), c = tv.check, err = errorBox();
    const walkthrough = App.state.persona === 'maya' && E.demoWalkthrough(App.state.plan);
    const amt = moneyBox({ label: 'Purchase amount', hint: 'For example 75 or 12.50' }); amt.input.id = 'check-amt'; amt.node.querySelector('label').setAttribute('for', 'check-amt'); amt.input.value = c.amountText; amt.input.addEventListener('input', () => { c.amountText = amt.input.value; });
    const dId = nid('d'), desc = h('input', { id: dId, type: 'text', maxlength: 80, autocomplete: 'off', value: c.desc, placeholder: 'concert tickets' }); desc.addEventListener('input', () => { c.desc = desc.value; });
    const tryAmt = walkthrough ? walkthrough.purchase.amountCents : 0;
    const tryMoney = tryAmt % 100 === 0 ? money(tryAmt, { cents: false }) : money(tryAmt);
    const form = h('form', { class: 'check-form', novalidate: '', onsubmit: ev => { ev.preventDefault(); err.clear(); runCheck(err); } },
      v.purchaseLimit && v.purchaseLimit.ok ? h('p', { class: 'check-limit', id: 'check-limit', text: 'Up to ' + money(v.purchaseLimit.maxCents) + ' for one purchase today. Your monthly category budget may lower that limit.' }) : null,
      amt.node, h('div', { class: 'field' }, h('label', { for: dId, text: 'What are you buying? (optional)' }), desc), err.node,
      h('button', { type: 'submit', class: 'btn primary big' }, h('span', { text: 'Check purchase' })),
      h('p', { class: 'hint', id: 'check-log-note', text: 'You choose whether to log it.' }));
    return h('section', { class: 'card checker', 'aria-labelledby': 'chk-h' },
      h('h2', { class: 'card-title', id: 'chk-h', text: 'Can I afford this?' }),
      form,
      walkthrough ? h('p', { class: 'hint maya-purchase-hint', text: 'Try ' + tryMoney + ' for a ' + walkthrough.purchase.desc.toLowerCase() + '.' }) : null,
      c.result ? resultNode(c.result, v) : null);
  }

  /* ---------- 4. Everyday actions ---------- */
  function purchaseRow(r, v, plan) {
    const tv = TV(), T = v.today;
    if (tv.edit && tv.edit.id === r.id) {
      const f = tv.edit, er = errorBox(), amt = moneyBox({ label: 'Amount' }); amt.input.value = f.amountText; amt.input.disabled = !r.manual; amt.input.addEventListener('input', () => { f.amountText = amt.input.value; });
      const cat = selectBox({ label: 'Category', value: f.cat, options: LOG_CATS.concat(LOG_CATS.indexOf(f.cat) < 0 ? [f.cat] : []).map(c => ({ value: c, label: c })) }); cat.input.addEventListener('change', () => { f.cat = cat.input.value; });
      const did = nid('ed'), dt = h('input', { id: did, type: 'date', max: D.fmt(T), value: f.date, disabled: !r.manual }); dt.addEventListener('input', () => { f.date = dt.value; });
      const tid = nid('ex'), tx = h('input', { id: tid, type: 'text', maxlength: 80, value: f.desc, disabled: !r.manual }); tx.addEventListener('input', () => { f.desc = tx.value; });
      return h('li', { class: 'pr editing' }, h('form', { class: 'ev-form', novalidate: '', onsubmit: ev => { ev.preventDefault(); const patch = { category: f.cat }; if (r.manual) { const c = readMoney(f.amountText); if (c == null || c <= 0) return er.show('Enter an amount above $0.'); if (!f.date) return er.show('Pick a date.'); Object.assign(patch, { amountCents: c, date: f.date, desc: f.desc }); } commit(E.editPurchase(plan, r.id, patch, T), 'log', 'Saved. Your spending and forecasts are updated.'); } },
        amt.node, cat.node, h('div', { class: 'field' }, h('label', { for: did, text: 'Date' }), dt), h('div', { class: 'field' }, h('label', { for: tid, text: 'Description' }), tx),
        r.manual ? null : h('p', { class: 'hint', text: 'This row came from your bank file, so only its category can be changed.' }), er.node,
        h('div', { class: 'row-actions' }, h('button', { type: 'submit', class: 'btn primary small' }, h('span', { text: 'Save changes' })), button('Cancel', { kind: 'ghost small', onclick: () => { tv.edit = null; App.render(); } }))));
    }
    const confirming = tv.confirmDel === r.id;
    return h('li', { class: 'pr' },
      h('div', { class: 'pr-main' }, h('b', { text: r.desc || r.category }), h('span', { class: 'pr-sub', text: dayLabel(D.parse(r.date)) + ', ' + r.category }), h('span', { class: 'badge ' + (r.manual ? 'blue' : 'soft'), text: r.manual ? 'You logged this' : 'From bank file' })),
      h('b', { class: 'pr-amt ' + (r.flow === 'refund' ? 'pos' : ''), text: (r.flow === 'refund' ? '+' : '') + money(r.amountCents) }),
      confirming ? h('div', { class: 'row-actions' }, h('span', { class: 'small', text: 'Delete this purchase?' }), button('Yes, delete', { kind: 'danger small', onclick: () => commit(E.removePurchase(plan, r.id), 'log', 'Deleted. Your spending and forecasts are updated.') }), button('Keep it', { kind: 'ghost small', onclick: () => { tv.confirmDel = null; App.render(); } }))
        : h('div', { class: 'row-actions' }, button('Edit', { kind: 'ghost small', aria: 'Edit ' + (r.desc || r.category), onclick: () => { tv.edit = { id: r.id, amountText: dollarsText(r.amountCents), cat: r.category, date: r.date, desc: r.desc || '' }; tv.confirmDel = null; App.focusId = null; App.render(); } }), r.manual ? button('Delete', { kind: 'ghost small', aria: 'Delete ' + (r.desc || r.category), onclick: () => { tv.confirmDel = r.id; tv.edit = null; App.render(); } }) : null));
  }

  function logForm(v, plan) {
    const tv = TV(), l = tv.log, T = v.today, err = errorBox();
    if (!l.date) l.date = D.fmt(T);
    const amt = moneyBox({ label: 'Amount spent' }); amt.input.id = 'log-amt'; amt.node.querySelector('label').setAttribute('for', 'log-amt'); amt.input.value = l.amountText; amt.input.addEventListener('input', () => { l.amountText = amt.input.value; });
    const cat = selectBox({ label: 'Category', value: l.cat, options: LOG_CATS.map(c => ({ value: c, label: c })) }); cat.input.addEventListener('change', () => { l.cat = cat.input.value; });
    const did = nid('ld'), dt = h('input', { id: did, type: 'date', max: D.fmt(T), value: l.date }); dt.addEventListener('input', () => { l.date = dt.value; });
    const tid = nid('lx'), tx = h('input', { id: tid, type: 'text', maxlength: 80, autocomplete: 'off', value: l.desc, placeholder: 'optional, like "Kroger"' }); tx.addEventListener('input', () => { l.desc = tx.value; });
    return h('form', { class: 'log-form', id: 'log-form', novalidate: '', onsubmit: ev => { ev.preventDefault(); err.clear(); const c = readMoney(l.amountText); if (c == null || c <= 0) return err.show('Enter an amount above $0.'); if (!l.date) return err.show('Pick a date.'); attemptLog({ amountCents: c, category: l.cat, desc: l.desc, date: l.date }, 'log'); } },
      amt.node, cat.node, h('div', { class: 'field' }, h('label', { for: did, text: 'Date' }), dt), h('div', { class: 'field' }, h('label', { for: tid, text: 'Description' }), tx), err.node,
      h('button', { type: 'submit', class: 'btn primary' }, icon('check'), h('span', { text: 'Log purchase' })));
  }

  function checkInForm(v, plan) {
    const tv = TV(), T = v.today, err = errorBox();
    const amt = moneyBox({ label: 'What does your bank show right now?', hint: 'Your checking account balance. Your bank\'s number replaces our estimate.' }); amt.input.id = 'ci-amt'; amt.node.querySelector('label').setAttribute('for', 'ci-amt'); amt.input.value = tv.checkInText; amt.input.addEventListener('input', () => { tv.checkInText = amt.input.value; });
    return h('form', { class: 'ci-form', novalidate: '', onsubmit: ev => { ev.preventDefault(); err.clear(); const cents = readMoney(tv.checkInText); if (cents == null) return err.show('Enter your balance as a number, like 412.60.'); const r = E.checkIn(plan, { today: T, balanceCents: cents }); if (!r.ok) return err.show(r.error); tv.checkInText = ''; commit(r, 'checkin', 'Balance updated to ' + money(cents) + '. ' + r.insight + ' Nothing else in your plan changed.'); } },
      amt.node, err.node, h('div', { class: 'row-actions' }, h('button', { type: 'submit', class: 'btn primary small' }, icon('check'), h('span', { text: 'Save my balance' })), button('Cancel', { kind: 'ghost small', onclick: () => { tv.checkInOpen = false; tv.checkInText = ''; App.render(); } })));
  }
  function openCheckIn() { const tv = TV(); tv.checkInOpen = true; App.focusId = 'ci-amt'; App.render(); }
  function checkInCard(v, plan) {
    const tv = TV(), c = v.checkIn;
    const head = c.level === 'overdue' ? 'Your balance is out of date' : 'Time for a quick balance check-in';
    const lead = 'You last verified ' + money(c.balanceCents) + ' on ' + dayLabel(c.asOfDay) + ' (' + plural(c.staleDays, 'day') + ' ago).' + (c.level === 'overdue' ? ' The numbers on this screen are marked provisional until you check in.' : '');
    return h('section', { class: 'card checkin due checkin-top', 'aria-labelledby': 'ci-h' },
      h('div', { class: 'st-top' }, badge(c.level === 'overdue' ? 'Out of date' : 'Due', c.level === 'overdue' ? 'warn' : 'amber'), h('h2', { class: 'card-title', id: 'ci-h', text: head })),
      h('p', { text: lead }), msgNode('checkin'),
      tv.checkInOpen ? checkInForm(v, plan) : h('div', { class: 'row-actions' }, button('Check in now', { kind: 'primary small', onclick: openCheckIn })));
  }

  function quickActions(v, plan, inlineCheckIn) {
    const tv = TV(), c = v.checkIn, recent = v.recent, shown = tv.showMore ? recent : recent.slice(0, 4), dupes = v.duplicates;
    const recentOpen = !!(tv.edit || tv.confirmDel || tv.recentOpen);
    return h('section', { class: 'card everyday quick-actions', 'aria-labelledby': 'log-h' },
      h('h2', { class: 'card-title', id: 'log-h', text: 'Quick actions' }),
      h('div', { class: 'row-actions' },
        button(tv.logOpen ? 'Hide purchase form' : 'Log a purchase', { kind: 'primary small', onclick: () => { tv.logOpen = !tv.logOpen; App.focusId = tv.logOpen ? 'log-amt' : 'log-h'; App.render(); } }),
        button('Change bank balance', { kind: 'ghost small', onclick: () => { if (tv.checkInOpen) { tv.checkInOpen = false; tv.checkInText = ''; App.render(); } else openCheckIn(); } }),
        button('Add bank file', { kind: 'ghost small', onclick: () => go('import') })),
      tv.logOpen ? logForm(v, plan) : null,
      dupPrompt('log'), msgNode('log'), msgNode('checkin'),
      dupes.length ? h('div', { class: 'note blue dupes', role: 'group', 'aria-label': 'Possible repeats' }, icon('info'), h('div', null, h('b', { text: 'Is this the same purchase?' }), dupes.slice(0, 2).map(d => h('div', { class: 'dupe' }, h('p', { class: 'small', text: 'You logged "' + d.manual.desc + '" (' + money(-d.manual.amountCents) + ', ' + dayLabel(D.parse(d.manual.date)) + ') and your bank file has "' + d.bank.desc + '" (' + dayLabel(D.parse(d.bank.date)) + ').' }), h('div', { class: 'row-actions' }, button('Same purchase', { kind: 'primary small', onclick: () => commit(E.decideDuplicate(plan, d.manualId, d.importId, true), 'log', 'Linked. It is counted once, as the bank row.') }), button('Two purchases', { kind: 'ghost small', onclick: () => commit(E.decideDuplicate(plan, d.manualId, d.importId, false), 'log', 'Okay. They stay as two purchases.') })))))) : null,
      c.due && !inlineCheckIn ? null : h('p', { class: 'balance-line', id: 'balance-line', text: 'Last verified balance: ' + money(c.balanceCents) + ' on ' + dayLabel(c.asOfDay) + '.' }),
      (!c.due || inlineCheckIn) && tv.checkInOpen ? checkInForm(v, plan) : null,
      recent.length ? h('details', { class: 'sure', id: 'recent-tx', open: recentOpen ? '' : null }, h('summary', { text: 'Recent transactions (' + recent.length + ')' }), h('ul', { class: 'prs' }, shown.map(r => purchaseRow(r, v, plan))), recent.length > 4 ? button(tv.showMore ? 'Show fewer' : 'Show more', { kind: 'ghost small', onclick: () => { tv.recentOpen = true; tv.showMore = !tv.showMore; App.render(); } }) : null) : null);
  }

  /* ---------- screen ---------- */
  App.screens.today = function () {
    const st = App.state, T = App.today(), plan = st.plan;
    if (!plan) return h('section', { class: 'card' }, h('h1', { id: 'title', tabindex: '-1', text: 'Nothing here yet' }), button('Start', { onclick: () => App.go('welcome', { reset: true }) }));
    const v = E.todayView(plan, T);
    if (!v.ok) return h('section', { class: 'card' }, h('h1', { id: 'title', tabindex: '-1', text: 'We need your balance first' }), h('p', { text: 'Today is built from your checking balance.' }), button('Enter it', { onclick: () => App.go('basics', { reset: true }) }));
    CUR = v; st.home = true; App.save();
    TV();
    const due = v.checkIn.due, jordanDemo = st.persona === 'jordan';
    const thin = v.thinData ? h('section', { class: 'card thin', 'aria-labelledby': 'thin-h' }, h('h2', { class: 'card-title', id: 'thin-h', text: 'These numbers are provisional' }),
      h('p', { text: 'They rest on very little history, so they are careful starting points, not measurements. Every real purchase you log or import makes them more accurate.' }),
      v.progress.estimated.thinCategories.length ? h('p', { class: 'hint', text: 'Rough estimates for: ' + v.progress.estimated.thinCategories.join(', ') + '.' }) : null,
      h('div', { class: 'row-actions' }, button('Add bank history', { kind: 'primary small', onclick: () => go('import') }))) : null;
    return h('div', { class: 'stack today mode-' + v.mode },
      intro(v, plan),
      due && !jordanDemo ? checkInCard(v, plan) : null,
      spendingAnswer(v, plan),
      jordanDemo ? null : shortfallNotice(plan, T),
      checkerCard(v),
      quickActions(v, plan, jordanDemo),
      jordanDemo ? null : afterTermAlert(v),
      goalReminder(v),
      jordanDemo ? null : actionNote(v),
      thin,
      spendingDetails(v, plan),
      jordanDemo ? actionNote(v) : null);
  };
})();

;
/* ===== ui/09-semester.js ===== */
/* ---- Stage 4: the Semester screen ----
   Every number on this screen comes from E.semesterView(plan, today), E.stressRun, E.stressTable and E.semesterRecommendations:
   the same snapshot (forecast + capacity) that powers Today. The UI never does money arithmetic of its own.
   Stress tests run on a COPY of the plan. A recommendation, a one-time expense or the planning period changes the saved plan only
   when the student presses the button that says so (and every such change can be undone from the message that follows). */
(function () {
  'use strict';
  const E = CCE, D = E.D;
  const { h, icon, button, badge, money, readMoney, dayLabel, moneyBox, errorBox } = App;
  const NS = 'http://www.w3.org/2000/svg';
  const m0 = c => money(c, { cents: false });
  const signed = c => Math.round(Math.abs(c) / 100) === 0 ? '$0' : (c < 0 ? '\u2212' : '+') + money(Math.abs(c), { cents: false });
  const plural = (n, w) => n + ' ' + w + (n === 1 ? '' : 's');
  const NATURE_KIND = { confirmed: 'good', scheduled: 'blue', expected: 'amber', uncertain: 'soft' };
  const STATUS_KIND = { on_track: 'good', tight: 'amber', depends_on_income: 'amber', over_budget: 'amber', short_bills: 'warn', needs_info: 'amber' };
  const STATUS_WORD = { on_track: 'On track', tight: 'On track, little slack', depends_on_income: 'Depends on income', over_budget: 'Spending above plan', short_bills: 'Short', needs_info: 'Needs info' };
  const COLORS = { cautious: '#1f5c4a', expected: '#0f766e', commit: '#6b7280', in: '#15803d', aid: '#1d4ed8', rent: '#991b1b', out: '#4b5563', lump: '#6d28d9' };
  let uid = 0; const nid = p => 'sv' + (++uid) + '-' + p;

  /* ---------- screen-local state (never saved) ---------- */
  function SV() {
    const st = App.state;
    if (!st.sv) st.sv = { stress: {}, msg: {}, confirm: null, undo: null, exp: { name: '', amountText: '', date: '', cat: 'Other', essential: false }, unit: 'months', open: {}, extendChart: false, compareExpected: false, chartRange: '30' };
    if (st.sv.compareExpected == null) st.sv.compareExpected = false;
    if (st.sv.chartRange !== 'full') st.sv.chartRange = '30';
    return st.sv;
  }
  let memo = { key: '', v: null, recs: null, table: null };
  function data(plan, T) {
    const k = E.hash32(JSON.stringify(plan)) + '|' + T;
    if (memo.key !== k) memo = { key: k, v: E.semesterView(plan, T), recs: null, table: null };
    return memo;
  }
  const msgNode = where => {
    const sv = SV(), m = sv.msg[where]; if (!m) return null;
    return h('div', { class: 'tv-msg ' + m.kind, id: where + '-msg', tabindex: '-1', role: m.kind === 'bad' ? 'alert' : 'status' },
      h('span', { text: m.msg }),
      sv.undo && sv.undo.where === where && m.kind !== 'bad' ? button('Undo this change', { kind: 'ghost small', onclick: () => { const u = sv.undo; sv.undo = null; App.setPlan(u.plan); sv.msg = {}; sv.msg[where] = { msg: 'Undone. Your plan is back to how it was.', kind: 'good' }; App.focusId = where + '-msg'; App.render(); } }) : null);
  };
  function commit(res, where, msg, o) {
    o = o || {}; const sv = SV();
    if (!res || !res.ok) { sv.msg = {}; sv.msg[where] = { msg: (res && res.error) || 'That did not work. Nothing was changed.', kind: 'bad' }; App.focusId = where + '-msg'; App.render(); return false; }
    sv.undo = o.undo ? { plan: App.state.plan, where } : null;
    App.setPlan(res.plan); sv.msg = {}; if (msg) sv.msg[where] = { msg, kind: o.kind || 'good' }; sv.confirm = null; App.focusId = where + '-msg'; App.render(); return true;
  }
  const go = (screen, open) => { const st = App.state; if (open) st.openOptional = open; if (screen === 'import') st.path = 'csv'; App.go(screen); };

  /* ---------- SVG helpers ---------- */
  function sv_(tag, attrs) {
    const e = document.createElementNS(NS, tag);
    if (attrs) for (const k of Object.keys(attrs)) if (attrs[k] != null) e.setAttribute(k, String(attrs[k]));
    for (let i = 2; i < arguments.length; i++) { const c = arguments[i]; if (c == null) continue; e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); }
    return e;
  }
  function niceTicks(lo, hi, n) {
    const span = Math.max(1, hi - lo), raw = span / n, pow = Math.pow(10, Math.floor(Math.log10(raw))), f = raw / pow, step = (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * pow, out = [];
    for (let v = Math.floor(lo / step) * step; v <= hi + 1e-6; v += step) out.push(Math.round(v));
    return out;
  }
  const axisMoney = c => (c < 0 ? '\u2212$' : '$') + Math.round(Math.abs(c) / 100).toLocaleString('en-US');
  const bucket = () => (window.innerWidth < 400 ? 'xs' : window.innerWidth < 640 ? 'sm' : window.innerWidth < 1000 ? 'md' : 'lg');   // chart drawing size follows the screen so its text stays readable
  const CHART = { xs: [280, 220], sm: [360, 230], md: [640, 240], lg: [900, 250] }, STRESS_CHART = { xs: [280, 240], sm: [360, 250], md: [640, 260], lg: [900, 300] };

  // Whether story labels fit above the plot without covering each other. A second row may
  // catch a short tail; labels for nearby days go in the list under the chart instead.
  function markerLayout(marks, start, end, W) {
    const narrow = W < 500, ml = narrow ? 46 : 58, mr = 14, plotW = W - ml - mr, span = Math.max(1, end - start);
    const X = day => ml + (day - start) / span * plotW, charW = 7.2, gap = 10;
    const placed = [];
    let fit = true;
    for (const m of marks.slice().sort((a, b) => a.day - b.day)) {
      const w = m.label.length * charW, x = X(m.day);
      let row = -1, x0 = 0;
      for (let r = 0; r < 2 && row < 0; r++) {
        x0 = Math.min(ml + plotW - w - 2, Math.max(ml + 2, x - w / 2));
        if (x0 < ml + 2 || w > plotW - 8) break;
        const x1 = x0 + w;
        const sameRow = placed.some(p => p.row === r && x0 < p.x1 + gap && x1 > p.x0 - gap);
        const stacked = placed.some(p => Math.min(x1, p.x1) - Math.max(x0, p.x0) > 28);
        if (!sameRow && !stacked) row = r;
      }
      if (row < 0) { fit = false; break; }
      placed.push({ m, row, x0, x1: x0 + w, x });
    }
    return { fit: fit && placed.length === marks.length, placed };
  }

  // One chart for the balance timeline and the stress test. Plain SVG, no library.
  // Balance mode: the line leads; cushion and $0 are lighter guides; story marks stay smaller than the line.
  function chart(o) {
    const balance = o.balance !== false, W = o.W, H = o.H, narrow = W < 500;
    const ml = narrow ? 46 : 58, mr = 14, mb = 26;
    const story = balance && o.story && o.story.length ? o.story : null;
    const storyLay = story && !o.storyExternal ? markerLayout(story, o.startDay, o.afterEnd || o.endDay, W) : null;
    const storyText = !!(storyLay && storyLay.fit);
    const band = storyText ? (storyLay.placed.some(p => p.row === 1) ? 46 : 20) : 0;
    const mt = (balance ? 8 : 14) + band;
    const laneH = (!balance && o.events) ? 40 : 0, plotH = H - mt - mb - laneH, plotW = W - ml - mr;
    const all = []; for (const l of o.lines.concat(o.after || [])) for (const p of l.pts) all.push(p[1]);
    let lo = Math.min(0, ...all), hi = Math.max(o.cushion || 0, ...all); const pad = (hi - lo) * 0.08 || 1000; lo -= lo < 0 ? pad : 0; hi += pad;
    // Balance charts ask for more y-ticks so the axis stays readable after long guide labels moved to HTML.
    const ticks = niceTicks(lo, hi, balance ? (narrow ? 5 : 6) : (narrow ? 4 : 5)); lo = Math.min(lo, ticks[0]); hi = Math.max(hi, ticks[ticks.length - 1]);
    const d0 = o.startDay, d1 = o.afterEnd || o.endDay, X = d => ml + (d - d0) / Math.max(1, d1 - d0) * plotW, Y = c => mt + (hi - c) / (hi - lo) * plotH;
    const taken = [], addBox = (x, y, text, anchor, size) => { const w = String(text).length * (narrow ? 6.6 : 7.4) * (size || 12) / 12, x0 = anchor === 'end' ? x - w : anchor === 'middle' ? x - w / 2 : x; taken.push([x0, y - (size || 12), x0 + w, y + 3]); };
    const svg = sv_('svg', { viewBox: '0 0 ' + W + ' ' + H, class: 'chart' + (balance ? ' chart-balance' : ''), role: 'img', 'aria-labelledby': o.id + '-t ' + o.id + '-d', focusable: 'false' });
    svg.appendChild(sv_('title', { id: o.id + '-t' }, o.title)); svg.appendChild(sv_('desc', { id: o.id + '-d' }, o.desc));
    const g = sv_('g', { 'aria-hidden': 'true' }); svg.appendChild(g);
    if (!balance && o.cushion != null) {
      g.appendChild(sv_('rect', { x: ml, y: Y(o.cushion), width: plotW, height: Math.max(0, Y(Math.max(0, lo)) - Y(o.cushion)), fill: '#fef3c7' }));
      if (lo < 0) g.appendChild(sv_('rect', { x: ml, y: Y(0), width: plotW, height: Y(lo) - Y(0), fill: '#fee2e2' }));
    }
    if (o.afterFrom != null) { g.appendChild(sv_('rect', { x: X(o.afterFrom), y: mt, width: X(d1) - X(o.afterFrom), height: plotH, fill: '#eef2f7' })); g.appendChild(sv_('line', { x1: X(o.afterFrom), x2: X(o.afterFrom), y1: mt, y2: mt + plotH, stroke: '#6b7280', 'stroke-width': 1.5 })); }
    for (const t of ticks) {
      const zero = t === 0;
      g.appendChild(sv_('line', { x1: ml, x2: ml + plotW, y1: Y(t), y2: Y(t), stroke: zero && !balance ? '#d1d5db' : '#f3f4f6', 'stroke-width': 1 }));
      if (!(balance && zero)) {
        g.appendChild(sv_('text', { x: ml - 6, y: Y(t) + 4, 'text-anchor': 'end', class: zero ? 'c-zero' : null }, axisMoney(t)));
        addBox(ml - 6, Y(t) + 4, axisMoney(t), 'end');
      } else {
        g.appendChild(sv_('text', { x: ml - 6, y: Y(t) + 4, 'text-anchor': 'end', class: 'c-zero' }, axisMoney(0)));
        addBox(ml - 6, Y(t) + 4, axisMoney(0), 'end');
      }
    }
    if (balance) {
      g.appendChild(sv_('line', { x1: ml, x2: ml + plotW, y1: Y(0), y2: Y(0), stroke: '#9ca3af', 'stroke-width': 1.25, 'stroke-dasharray': '5 4' }));
    }
    if (o.cushion != null) {
      g.appendChild(sv_('line', { x1: ml, x2: ml + plotW, y1: Y(o.cushion), y2: Y(o.cushion), stroke: '#b45309', 'stroke-width': 1.25, 'stroke-dasharray': '5 4' }));
      if (!balance) {
        const cushionText = narrow ? axisMoney(o.cushion) + ' cushion' : 'Your ' + axisMoney(o.cushion) + ' cushion';
        g.appendChild(sv_('text', { x: ml + 6, y: Y(o.cushion) - 5, 'text-anchor': 'start', class: 'c-cush' }, cushionText)); addBox(ml + 6, Y(o.cushion) - 5, cushionText, 'start');
      }
    }
    // Restrained below-$0 highlight under the projected (first) line only — not a full-width red band.
    if (balance && o.lines[0] && o.lines[0].pts) {
      const pts = o.lines[0].pts, y0 = Y(0);
      let i = 0;
      while (i < pts.length) {
        while (i < pts.length && pts[i][1] >= 0) i++;
        if (i >= pts.length) break;
        const start = Math.max(0, i - (i > 0 && pts[i - 1][1] >= 0 ? 1 : 0));
        let j = i; while (j < pts.length && pts[j][1] < 0) j++;
        const end = Math.min(pts.length - 1, j);
        const slice = pts.slice(start, end + 1);
        if (slice.length >= 2) {
          const top = slice.map((p, k) => (k ? 'L' : 'M') + X(p[0]).toFixed(1) + ' ' + Y(Math.min(0, p[1])).toFixed(1)).join('');
          const back = 'L' + X(slice[slice.length - 1][0]).toFixed(1) + ' ' + y0.toFixed(1) + ' L' + X(slice[0][0]).toFixed(1) + ' ' + y0.toFixed(1) + ' Z';
          g.appendChild(sv_('path', { d: top + ' ' + back, fill: '#fecaca', opacity: '0.45', class: 'c-neg-fill' }));
        }
        i = j;
      }
    }
    const xt = [d0, o.endDay]; if (o.afterEnd) xt.push(o.afterEnd);
    for (let d = D.monthStart(d0); d <= d1; d = D.addMonths(d, 1, 1)) if (d > d0 + 6 && d < d1 - 6) xt.push(d);
    const placed = [];
    for (const d of Array.from(new Set(xt))) {
      const x = X(d), label = d === d0 ? 'Today, ' + D.label(d) : D.label(d), wd = label.length * 6.6, anchor = d === d0 ? 'start' : d === d1 ? 'end' : 'middle';
      const lx = Math.min(W - 6, Math.max(ml + 2, anchor === 'start' ? Math.max(ml + 2, x) : x)), a = anchor === 'start' ? lx : anchor === 'end' ? lx - wd : lx - wd / 2, b = a + wd;
      g.appendChild(sv_('line', { x1: x, x2: x, y1: mt + plotH, y2: mt + plotH + 4, stroke: '#9ca3af' }));
      if (placed.some(q => a < q[1] + 10 && b > q[0] - 10)) continue;
      placed.push([a, b]); g.appendChild(sv_('text', { x: lx, y: H - mb + 17, 'text-anchor': anchor }, label));
    }
    if (o.afterFrom != null) { g.appendChild(sv_('text', { x: X(o.afterFrom) + 6, y: mt + 13, class: 'c-after' }, 'After the term')); addBox(X(o.afterFrom) + 6, mt + 13, 'After the term', 'start'); }
    const path = pts => pts.map((p, i) => (i ? 'L' : 'M') + X(p[0]).toFixed(1) + ' ' + Y(p[1]).toFixed(1)).join('');
    for (const l of o.lines.concat(o.after || [])) g.appendChild(sv_('path', { d: path(l.pts), fill: 'none', stroke: l.color, 'stroke-width': l.width || 2.5, 'stroke-dasharray': l.dash || null, 'stroke-linejoin': 'round', 'stroke-linecap': 'round', opacity: l.opacity || 1 }));
    const placeMark = (mark) => {
      if (!mark) return;
      const x = X(mark.day), y = Y(mark.cents), txt = mark.label || '', sz = 12, charW = 7.0, w = txt.length * charW * sz / 12;
      const stroke = mark.tone === 'ok' ? COLORS.cautious : (mark.tone === 'warn' ? '#c2410c' : '#b91c1c');
      g.appendChild(sv_('circle', { cx: x, cy: y, r: 5, fill: '#fff', stroke, 'stroke-width': 2.4 }));
      taken.push([x - 8, y - 8, x + 8, y + 8]);
      // Answer copy lives above the plot; markers stay unlabeled unless a short in-plot label is supplied.
      if (mark.external || !txt) return;
      const preferAbove = mark.cents <= 0 || Math.abs(Y(0) - y) < 18;
      const dys = preferAbove ? [-10, -24, -38, -52, 18, 32, 46] : [18, 32, 46, -10, -24, -38, -52];
      const spots = []; for (const dy of dys) for (const side of (mark.preferSide === 'left' ? [-1, 1, 0] : [1, -1, 0])) spots.push({ side, dy });
      const place = sp => { const yy = y + sp.dy; let x0, anchor, tx; if (sp.side > 0) { x0 = x + 8; anchor = 'start'; tx = x0; } else if (sp.side < 0) { x0 = x - 8 - w; anchor = 'end'; tx = x - 8; } else { x0 = Math.min(W - 4 - w, Math.max(ml + 2, x - w / 2)); anchor = 'start'; tx = x0; } return { box: [x0, yy - sz, x0 + w, yy + 3], x: tx, y: yy, anchor }; };
      const free = b => b[0] >= ml + 2 && b[2] <= W - 4 && b[1] >= mt && b[3] <= mt + plotH && !taken.some(t => b[0] < t[2] + 4 && b[2] > t[0] - 4 && b[1] < t[3] + 3 && b[3] > t[1] - 3);
      const pl = place(spots.find(q => free(place(q).box)) || spots[0]);
      taken.push(pl.box);
      g.appendChild(sv_('text', { x: pl.x, y: pl.y, 'text-anchor': pl.anchor, class: mark.tone === 'ok' ? 'c-ok' : 'c-low', 'font-size': String(sz) }, txt));
    };
    if (story) {
      if (storyText) {
        for (const p of storyLay.placed) {
          g.appendChild(sv_('text', { x: p.x0, y: 14 + p.row * 22, 'text-anchor': 'start', class: 'c-mark' }, p.m.label));
          taken.push([p.x0, 2 + p.row * 22, p.x1, 18 + p.row * 22]);
        }
      }
      for (const m of story) {
        const x = X(m.day), y = Y(m.cents);
        const col = m.role === 'pay' ? '#166534' : m.role === 'rent' ? '#991b1b' : (m.cents < 0 ? '#9a3412' : '#1f5c4a');
        if (m.role === 'rent') g.appendChild(sv_('rect', { x: x - 3.5, y: y - 3.5, width: 7, height: 7, fill: '#fff', stroke: col, 'stroke-width': 1.6 }));
        else if (m.role === 'pay') g.appendChild(sv_('path', { d: 'M' + x + ' ' + (y - 5) + 'L' + (x + 4.5) + ' ' + (y + 3.5) + 'L' + (x - 4.5) + ' ' + (y + 3.5) + 'Z', fill: '#fff', stroke: col, 'stroke-width': 1.6 }));
        else g.appendChild(sv_('circle', { cx: x, cy: y, r: 4.5, fill: '#fff', stroke: col, 'stroke-width': 2 }));
        taken.push([x - 8, y - 8, x + 8, y + 8]);
      }
    }
    const guideAt = (text, yLine, cls, avoidY) => {
      const w = text.length * 6.4, right = ml + plotW - 4;
      const spots = [{ x: right, anchor: 'end', y: yLine - 6 }, { x: right, anchor: 'end', y: yLine + 14 }, { x: ml + 8, anchor: 'start', y: yLine - 6 }];
      for (const s of spots) {
        if (text === '$0' && s.x < ml + 40) continue;   // the axis already names $0
        const x0 = s.anchor === 'end' ? s.x - w : s.x;
        const box = [x0, s.y - 11, x0 + w, s.y + 3];
        if (box[0] < ml + 2 || box[2] > ml + plotW + 2 || box[1] < mt || box[3] > mt + plotH) continue;
        if (avoidY != null && box[1] < avoidY + 2 && box[3] > avoidY - 2) continue;
        if (taken.some(t => box[0] < t[2] + 3 && box[2] > t[0] - 3 && box[1] < t[3] + 2 && box[3] > t[1] - 2)) continue;
        g.appendChild(sv_('text', { x: s.x, y: s.y, 'text-anchor': s.anchor, class: cls }, text));
        taken.push(box);
        return true;
      }
      return false;
    };
    const guideMiss = [];
    if (balance && o.cushionLabel && !guideAt(o.cushionLabel, Y(o.cushion), 'c-cush', Y(0))) guideMiss.push('cushion');
    if (balance && !guideAt('$0', Y(0), 'c-zero', o.cushion != null ? Y(o.cushion) : null)) guideMiss.push('zero');
    if (guideMiss.length) svg.setAttribute('data-guides', guideMiss.join(' '));
    if (o.marks && o.marks.length) o.marks.forEach(placeMark);
    else if (o.mark) placeMark(o.mark);
    if (!balance && o.events) {
      const y0 = mt + plotH + 12;
      g.appendChild(sv_('text', { x: ml - 6, y: y0 + 12, 'text-anchor': 'end', class: 'c-lane' }, 'In'));
      g.appendChild(sv_('text', { x: ml - 6, y: y0 + 28, 'text-anchor': 'end', class: 'c-lane' }, 'Out'));
      for (const e of o.events) {
        if (e.day < d0 || e.day > o.endDay) continue;
        const x = X(e.day), money_ = e.money === 'in', cy = y0 + (money_ ? 8 : 24), r = 5;
        let shape, col;
        if (money_) { if (e.kind === 'aid') { shape = 'diamond'; col = COLORS.aid; } else { shape = 'up'; col = COLORS.in; } }
        else if (e.kind === 'rent') { shape = 'square'; col = COLORS.rent; } else if (e.kind === 'tuition' || e.kind === 'books' || e.kind === 'oneTime') { shape = 'diamond'; col = COLORS.lump; } else { shape = 'down'; col = COLORS.out; }
        const el = shape === 'diamond' ? sv_('path', { d: 'M' + x + ' ' + (cy - r - 1) + 'L' + (x + r + 1) + ' ' + cy + 'L' + x + ' ' + (cy + r + 1) + 'L' + (x - r - 1) + ' ' + cy + 'Z', fill: col })
          : shape === 'up' ? sv_('path', { d: 'M' + x + ' ' + (cy - r) + 'L' + (x + r) + ' ' + (cy + r - 1) + 'L' + (x - r) + ' ' + (cy + r - 1) + 'Z', fill: col })
          : shape === 'down' ? sv_('path', { d: 'M' + (x - r) + ' ' + (cy - r + 1) + 'L' + (x + r) + ' ' + (cy - r + 1) + 'L' + x + ' ' + (cy + r) + 'Z', fill: col })
          : sv_('rect', { x: x - r + 1, y: cy - r + 1, width: 2 * r - 2, height: 2 * r - 2, fill: col });
        el.appendChild(sv_('title', {}, e.name + ', ' + D.label(e.day) + ', ' + (money_ ? '+' : '\u2212') + money(Math.abs(e.amountCents), { cents: false })));
        g.appendChild(el);
      }
    }
    return svg;
  }
  const legendItem = (shape, color, text) => h('li', null, shapeIcon(shape, color), h('span', { text }));
  function shapeIcon(shape, color) {
    const s = sv_('svg', { viewBox: '0 0 14 14', width: 14, height: 14, 'aria-hidden': 'true', class: 'lg-ico' });
    const d = { up: 'M7 2L12 12H2Z', down: 'M2 3H12L7 12Z', diamond: 'M7 1L13 7L7 13L1 7Z', square: 'M2.5 2.5H11.5V11.5H2.5Z', line: 'M1 7H13', dash: 'M1 7H5M9 7H13', dot: 'M1 7H3M6 7H8M11 7H13' }[shape];
    s.appendChild(sv_('path', { d, fill: shape === 'line' || shape === 'dash' || shape === 'dot' ? 'none' : color, stroke: shape === 'line' || shape === 'dash' || shape === 'dot' ? color : 'none', 'stroke-width': 2.5 }));
    return s;
  }

  /* ---------- small building blocks ---------- */
  const card = (id, title, sub, ...kids) => h('section', { class: 'card sv-card', 'aria-labelledby': id }, h('h2', { class: 'card-title', id, tabindex: '-1', text: title }), sub ? h('p', { class: 'card-sub', text: sub }) : null, kids);
  const tone = c => c < 0 ? 'neg' : '';
  const amount = c => money(c).replace(/^-/, '−');
  const dollars = c => c % 100 === 0 ? money(c, { cents: false }) : money(c);
  const range = (start, end) => dayLabel(start) + ' to ' + dayLabel(end);

  function disclosure(id, title, body, cls) {
    const open = SV().open;
    return h('details', { id, class: 'sure ' + (cls || ''), open: !!open[id], ontoggle: e => { open[id] = e.target.open; } },
      h('summary', { text: title }), body);
  }

  function forecastHeadline(v) {
    const low = v.forecasts.cautious.planned, C = v.cushion.cents;
    if (v.standing.status === 'needs_info') return v.standing.headline;
    if (low.minCents < 0) return 'You could run ' + dollars(Math.abs(low.minCents)) + ' short on ' + dayLabel(low.minDay);
    if (low.minCents < C) return 'You could dip below your ' + dollars(C) + ' cushion';
    return 'Your projected low of ' + dollars(low.minCents) + ' on ' + dayLabel(low.minDay) + ' stays above your ' + dollars(C) + ' cushion through ' + dayLabel(v.endDay) + '.';
  }

  function outlook(v, plan, T, memoObj) {
    const ctx = v.ctx, low = v.forecasts.cautious.planned, s = v.standing, C = v.cushion.cents;
    const missing = s.status === 'needs_info', short = !missing && low.minCents < 0, below = !missing && low.minCents < C;
    const picked = below ? topRecommendation(memoObj, plan, T) : { list: [], main: null };
    const why = missing ? s.detail : below ? causeLine(v, low.minDay) : '';
    const help = picked.main ? helpSentence(picked.main, C) : '';
    const termBits = [ctx.periodName || 'Your semester', ctx.startDay != null ? dayLabel(ctx.startDay) + '\u2013' + dayLabel(v.endDay) : 'Through ' + dayLabel(v.endDay)];
    if (v.provisionalDates) termBits.push('Estimated dates');
    const options = ctx.options;
    const pick = options.length > 1 ? h('div', { class: 'period-pick' }, h('span', { class: 'pp-l', id: 'pp-l', text: 'Plan through' }),
      h('div', { class: 'chips', role: 'group', 'aria-labelledby': 'pp-l' }, options.map(o => h('button', {
        type: 'button', class: 'chip' + (o.selected ? ' on' : ''), 'aria-pressed': String(o.selected), text: o.name,
        onclick: () => { if (!o.selected) commit(E.setPlanningPeriod(plan, T, o.id), 'period', 'Now planning through ' + o.name + ' (' + dayLabel(D.parse(o.end)) + ').', { undo: true }); }
      })))) : null;
    const tone = short ? 'short' : below ? 'amber' : missing ? s.tone : '';
    return h('section', { class: 'card sem-hero' + (tone ? ' ' + tone : ''), 'aria-labelledby': 'title' },
      h('p', { class: 'sem-term', id: 'sem-term', text: termBits.join(' \u00b7 ') }),
      h('h1', { id: 'title', class: 'sh-title', tabindex: '-1', text: forecastHeadline(v) }),
      why ? h('p', { class: 'sem-why', id: 'sem-why', text: why }) : null,
      help ? h('p', { class: 'sem-help', id: 'sem-help' }, h('span', { class: 'sem-k', text: 'What would help: ' }), h('span', { text: help })) : null,
      suggestionList(plan, T, picked.list),
      ctx.note ? h('p', { class: 'hint', text: ctx.note }) : null,
      h('div', { class: 'sem-controls' }, pick, v.provisionalDates ? button('Confirm my semester dates', { kind: 'ghost small', onclick: () => go('optional', 'dates') }) : null),
      msgNode('period'),
      msgNode('rec'));
  }

  function forecastsDiffer(v) {
    return v.chart.cautious.some((p, i) => p[1] !== v.chart.expected[i][1]);
  }

  function forecastDetails(v) {
    const f = v.forecasts;
    const cells = m => [h('td', { text: amount(m.minCents) + ' on ' + dayLabel(m.minDay) }), h('td', { text: amount(m.endCents) })];
    const compare = forecastsDiffer(v) ? disclosure('forecast-compare', 'Compare cautious and expected forecasts',
      h('table', { class: 'cmp' },
        h('caption', { class: 'sr-only', text: 'Cautious and expected forecasts' }),
        h('thead', null, h('tr', null, h('th', { scope: 'col', text: 'Forecast' }), h('th', { scope: 'col', text: 'Lowest balance' }), h('th', { scope: 'col', text: 'Term end' }))),
        h('tbody', null,
          h('tr', null, h('th', { scope: 'row', text: 'Cautious' }), cells(f.cautious.planned)),
          h('tr', null, h('th', { scope: 'row', text: 'Expected' }), cells(f.expected.planned))))) : null;
    return compare;
  }

  function compareWhy(v) {
    if (v.variable && v.variable.is) {
      return 'The gap comes from variable pay' + (v.variable.names.length ? ' (' + v.variable.names.join(', ') + ')' : '') + ': the cautious line uses the low recent amount, while the comparison uses the scheduled amount.';
    }
    const late = (v.assumptions || []).find(a => /late|aid|scholarship/i.test(a.text || ''));
    if (late) return late.text;
    return 'The comparison uses scheduled income amounts and dates. The cautious line plans for lower or later income where that applies.';
  }

  function slicePts(pts, fromDay, toDay) {
    return pts.filter(p => p[0] >= fromDay && p[0] <= toDay);
  }

  function windowLow(pts) {
    if (!pts.length) return null;
    let best = pts[0];
    for (const p of pts) if (p[1] < best[1]) best = p;
    return { day: best[0], cents: best[1] };
  }

  function recTitle(rec) {
    return rec.title.replace(/on discretionary spending$/, 'on flexible purchases');
  }

  function topRecommendation(memoObj, plan, T) {
    if (!memoObj.recs) memoObj.recs = E.semesterRecommendations(plan, T);
    const r = memoObj.recs;
    if (!r.ok) return { recs: r, list: [], main: null };
    const list = r.items.concat(r.together ? [r.together] : []).filter(rec => rec.after.cautiousMinCents > rec.before.cautiousMinCents);
    const main = list.find(rec => rec.fullFix && rec.apply) || list.reduce((best, rec) =>
      !best || rec.after.cautiousMinCents > best.after.cautiousMinCents ? rec : best, null);
    return { recs: r, list, main };
  }

  // A cause only when the forecast names the bill or the draw that creates the low.
  function causeLine(v, lowDay) {
    const rent = v.income.rentGaps.find(r => r.lowestDay === lowDay);
    const pressure = v.pressure.find(p => p.day === lowDay) || v.pressure.find(p => p.isLowest);
    if (rent && rent.nextPay) return 'Your ' + dollars(rent.amountCents) + ' rent is due ' + dayLabel(rent.day) + ', and payday is ' + dayLabel(rent.nextPay.day) + '.';
    if (rent) return 'Your ' + dollars(rent.amountCents) + ' rent is due ' + dayLabel(rent.day) + '.';
    if (pressure && pressure.drivers && pressure.drivers[0]) {
      const d = pressure.drivers[0];
      return d.name + ' (' + dollars(d.amountCents) + ') is due ' + dayLabel(d.day) + (pressure.nextIncome ? ', and the next income is on ' + dayLabel(pressure.nextIncome.day) + '.' : '.');
    }
    return (pressure && pressure.why) || '';
  }

  function helpSentence(rec, C) {
    const weekly = rec.title.match(/^Spend about \$[\d,]+ less per week/);
    const lead = weekly ? weekly[0] + '.' : recTitle(rec).replace(/\.$/, '') + '.';
    const rise = ' Your lowest projected balance would rise to ' + money(rec.after.cautiousMinCents);
    return lead + rise + (rec.fullFix ? ', above your ' + dollars(C) + ' cushion.' : ', but it would still fall below your ' + dollars(C) + ' cushion.');
  }

  function storyMarks(v, pts, viewStart, viewEnd) {
    const low = windowLow(pts);
    if (!low || low.day < viewStart || low.day > viewEnd) return [];
    const at = day => { const p = pts.find(x => x[0] === day); return p ? p[1] : null; };
    const gaps = (v.income && v.income.rentGaps) || [];
    const rent = gaps.find(r => r.lowestDay === low.day) || gaps.find(r => r.day <= low.day && r.day >= viewStart && r.nextPay && r.nextPay.day >= low.day);
    const marks = [];
    const add = (day, cents, role, name) => {
      if (day < viewStart || day > viewEnd || cents == null) return;
      const hit = marks.find(m => m.day === day);
      if (hit) { if (hit.label.indexOf(name) < 0) hit.label += ', ' + name; return; }
      marks.push({ day, cents, role, label: dayLabel(day) + ' \u00b7 ' + name });
    };
    if (rent) add(rent.day, at(rent.day), 'rent', 'Rent due');
    add(low.day, low.cents, 'low', 'Lowest balance');
    if (rent && rent.nextPay) add(rent.nextPay.day, at(rent.nextPay.day), 'pay', 'Payday');
    return marks.sort((a, b) => a.day - b.day);
  }

  function timelineCard(v) {
    const ch = v.chart, [W, H] = CHART[bucket()], series = v.after.series, sv = SV(), differs = forecastsDiffer(v);
    const comparing = differs && sv.compareExpected;
    const daysLeft = ch.endDay - ch.startDay + 1;
    const showRangeSwitch = daysLeft > 30;
    const rangeMode = showRangeSwitch ? sv.chartRange : 'full';
    const viewEnd = rangeMode === '30' ? Math.min(ch.startDay + 29, ch.endDay) : ch.endDay;
    const viewStart = ch.startDay;
    const canExtend = !!(series && series.cautious && series.cautious.length);
    const afterOn = canExtend && sv.extendChart && rangeMode === 'full';
    const cautiousView = slicePts(ch.cautious, viewStart, viewEnd);
    const expectedView = slicePts(ch.expected, viewStart, viewEnd);
    const lines = [{ pts: cautiousView, color: COLORS.cautious, width: 3 }];
    if (comparing) lines.push({ pts: expectedView, color: COLORS.expected, width: 2, dash: '6 5', opacity: 0.95 });
    const after = afterOn ? [{ pts: ch.cautious.slice(-1).concat(series.cautious), color: COLORS.cautious, width: 3 }] : [];
    const chartEnd = afterOn ? series.cautious[series.cautious.length - 1][0] : viewEnd;
    const C = ch.cushionCents;
    const assumption = v.discretionaryBasis === 'approved' ? 'This forecast assumes you spend your approved budgets in full.' : '';
    const reviewBudgets = () => { App.state.budgetEdits = null; App.go('budgets'); };
    const cautLine = afterOn ? ch.cautious.slice(-1).concat(series.cautious) : cautiousView;
    const expLine = comparing ? (afterOn && series.expected ? ch.expected.slice(-1).concat(series.expected) : expectedView) : null;
    const shown = cautLine.length ? cautLine[cautLine.length - 1] : null;
    const expShown = expLine && expLine.length ? expLine[expLine.length - 1] : null;
    const story = storyMarks(v, cautLine, viewStart, shown ? shown[0] : viewEnd);
    const storyExternal = story.length > 0 && !markerLayout(story, viewStart, shown ? shown[0] : viewEnd, W).fit;
    const mode = comparing && afterOn ? 'Cautious forecast, with scheduled income and after the term'
      : comparing ? 'Cautious forecast and scheduled income'
      : afterOn ? 'Cautious forecast, including after the term'
      : 'Cautious forecast';
    const rangeSwitch = showRangeSwitch ? h('div', { class: 'chips sem-range', role: 'group', 'aria-label': 'Forecast range' },
      [['30', 'Next 30 days'], ['full', 'Full forecast']].map(([id, label]) => h('button', {
        type: 'button', id: 'chart-range-' + id, class: 'chip' + (rangeMode === id ? ' on' : ''),
        'aria-pressed': String(rangeMode === id), text: label,
        onclick: () => { if (sv.chartRange !== id) { sv.chartRange = id; App.focusId = 'chart-range-' + id; App.render(); } }
      }))) : null;
    const cushionLabel = dollars(C) + ' cushion';
    const svg = chart({ id: 'tl', W, H, balance: true, startDay: viewStart, endDay: viewEnd, afterFrom: afterOn ? ch.endDay : null, afterEnd: afterOn ? chartEnd : null,
      cushion: C, cushionLabel, lines, after, story, storyExternal,
      title: 'Projected checking balance, ' + range(viewStart, chartEnd),
      desc: forecastHeadline(v) + (story.length ? ' Marked ' + story.map(m => m.label).join(', ') + '.' : '') + ' Dashed guides: ' + cushionLabel + ' and $0. Open the balance table for daily figures.' });
    const guideMiss = (svg.getAttribute('data-guides') || '').split(' ').filter(Boolean);
    const key = guideMiss.length ? h('ul', { class: 'sem-chart-key', 'aria-label': 'Chart guide' },
      guideMiss.includes('cushion') ? h('li', null, h('span', { class: 'sem-key-swatch cush', 'aria-hidden': 'true' }), h('span', { text: cushionLabel })) : null,
      guideMiss.includes('zero') ? h('li', null, h('span', { class: 'sem-key-swatch zero', 'aria-hidden': 'true' }), h('span', { text: '$0' })) : null) : null;
    const markList = storyExternal ? h('ul', { class: 'sem-mark-list', id: 'sem-marks' }, story.map(m =>
      h('li', null, h('span', { class: 'mk ' + m.role + (m.role === 'low' && m.cents < 0 ? ' neg' : ''), 'aria-hidden': 'true' }), h('span', { text: m.label })))) : null;
    const compare = differs ? h('div', { class: 'sem-compare' },
      h('label', { class: 'sem-chart-toggle', for: 'compare-expected' },
        h('input', { type: 'checkbox', id: 'compare-expected', checked: comparing, onchange: e => { sv.compareExpected = e.target.checked; App.focusId = e.target.id; App.render(); } }),
        h('span', { text: 'Compare if income arrives as scheduled' })),
      comparing ? h('p', { class: 'hint sem-compare-why', text: compareWhy(v) }) : null) : null;
    const extend = canExtend ? h('label', { class: 'sem-chart-toggle', for: 'extend-balance-chart' },
      h('input', { type: 'checkbox', id: 'extend-balance-chart', checked: !!sv.extendChart, onchange: e => { sv.extendChart = e.target.checked; App.focusId = e.target.id; App.render(); } }),
      h('span', { text: 'Include the cautious forecast after the term' })) : null;
    const options = (compare || extend) ? disclosure('forecast-options', 'Forecast options',
      h('div', { class: 'sem-forecast-options' }, compare, extend,
        afterOn ? null : (sv.extendChart && rangeMode === '30' ? h('p', { class: 'hint', text: 'Switch to Full forecast to see the after-term stretch on the chart.' }) : null))) : null;
    const tablePts = afterOn ? ch.cautious.concat(series.cautious) : ch.cautious;
    const balanceRows = tablePts.map(([day, cents], i) =>
      h('tr', null, h('th', { scope: 'row', text: dayLabel(day) }), h('td', { class: tone(cents), text: amount(cents) }),
        comparing ? h('td', { text: (i < ch.expected.length ? amount(ch.expected[i][1]) : '—') }) : null));
    const table = disclosure('balance-table', 'Show daily balance table',
      h('table', { class: 'cmp small' },
        h('caption', { class: 'sr-only', text: 'Projected daily balances, ' + range(ch.startDay, afterOn ? chartEnd : ch.endDay) }),
        h('thead', null, h('tr', null, h('th', { scope: 'col', text: 'Date' }), h('th', { scope: 'col', text: comparing || afterOn ? 'Cautious' : 'Projected balance' }), comparing ? h('th', { scope: 'col', text: 'If income arrives as scheduled' }) : null)),
        h('tbody', null, balanceRows)));
    return card('tl-h', 'Projected checking balance', null,
      h('div', { class: 'sem-chart-panel' },
        h('div', { class: 'sem-chart-head' },
          h('div', { class: 'sem-chart-head-text' },
            h('p', { class: 'sem-chart-range', id: 'tl-range', text: range(viewStart, shown ? shown[0] : viewEnd) + ' · ' + mode })),
          rangeSwitch),
        options,
        assumption ? h('p', { class: 'sem-chart-basis', text: assumption }) : null,
        h('div', { class: 'chart-wrap' }, svg),
        markList,
        key,
        h('div', { class: 'sem-chart-foot' },
          shown ? h('p', { class: 'sem-ending' }, 'Projected balance on ' + dayLabel(shown[0]) + ' · ', h('b', { class: tone(shown[1]), text: amount(shown[1]) }), expShown && expShown[1] !== shown[1] ? ' cautious, ' + amount(expShown[1]) + ' if income arrives as scheduled.' : '.' ) : null,
          button('Review budgets', { kind: 'ghost small', id: 'tl-review-budgets', onclick: reviewBudgets }))),
      eventList(v), table);
  }

  function eventList(v) {
    const rows = v.events.map(e => h('li', { class: 'evl ' + e.nature },
      h('span', { class: 'evl-d', text: e.dayLabel }),
      h('span', { class: 'evl-n' }, h('b', { text: e.name }), h('span', { class: 'evl-k', text: e.kindLabel + (e.note ? '. ' + e.note : '') })),
      h('span', { class: 'evl-a ' + (e.money === 'in' ? 'pos' : ''), text: signed(e.amountCents) }),
      h('span', { class: 'evl-b' }, badge(e.natureLabel, NATURE_KIND[e.nature])),
      h('span', { class: 'evl-bal', text: e.balanceAfterCents == null ? '' : 'Balance ' + amount(e.balanceAfterCents) })));
    for (const e of v.rests.uncounted) rows.push(h('li', { class: 'evl uncertain' },
      h('span', { class: 'evl-d', text: dayLabel(e.day) }), h('span', { class: 'evl-n' }, h('b', { text: e.name }), h('span', { class: 'evl-k', text: e.text })),
      h('span', { class: 'evl-a', text: signed(e.income ? e.amountCents : -e.amountCents) }), h('span', { class: 'evl-b' }, badge('Not counted', 'soft'))));
    return disclosure('timeline-events', 'See all forecast events',
      rows.length ? h('ol', { class: 'evls' }, rows) : h('p', { class: 'hint', text: 'No forecast events are listed for this term.' }));
  }

  /* ---------- 5. stress tests ---------- */
  function stressCard(v, plan, T, memoObj) {
    const sv = SV(), menu = E.stressMenu(plan, T), picks = Object.keys(sv.stress).map(id => ({ id, param: sv.stress[id] }));
    const chosen = menu.filter(m => sv.stress[m.id] !== undefined);
    const controls = h('div', { class: 'st-controls', role: 'group', 'aria-label': 'Choose stress tests' },
      menu.map(m => {
        const on = sv.stress[m.id] !== undefined, ok = m.applies.ok;
        const sid = 'stress-amount-' + m.id;
        return h('div', { class: 'st-item' + (on ? ' on' : '') + (ok ? '' : ' off') },
          h('button', { type: 'button', class: 'chip' + (on ? ' on' : ''), id: 'st-' + m.id, 'aria-pressed': on ? 'true' : 'false', disabled: !ok, 'aria-describedby': ok ? null : 'st-why-' + m.id, text: m.label,
            onclick: () => { if (on) delete sv.stress[m.id]; else sv.stress[m.id] = m.dflt; App.focusId = 'st-' + m.id; App.render(); } }),
          on ? h('span', { class: 'st-pick' }, h('label', { for: sid, class: 'sr-only', text: 'How much: ' + m.label }),
            h('select', { id: sid, onchange: e => { sv.stress[m.id] = Number(e.target.value); App.focusId = sid; App.render(); } }, m.options.map(o => h('option', { value: o, selected: o === sv.stress[m.id], text: m.optionLabel(o) })))) : null,
          ok ? null : h('span', { class: 'st-why', id: 'st-why-' + m.id, text: m.applies.reason }));
      }));
    let result;
    if (!picks.length) result = h('p', { class: 'hint st-empty', text: 'Pick one or more tests to see what would happen to your forecast. They run on a copy, so nothing about your real plan changes.' });
    else {
      const r = E.stressRun(plan, T, picks);
      if (!r.ok) result = h('p', { class: 'error', role: 'alert', text: r.error });
      else if (r.empty) result = h('p', { class: 'hint', text: r.skipped.map(s => s.reason).join(' ') });
      else {
        const b = r.before, a = r.after, C = v.cushion.cents;
        const row = (label, before, after, delta, fmtf, goodUp) => h('tr', null, h('th', { scope: 'row', text: label }), h('td', { text: fmtf(before) }), h('td', null, h('b', { text: fmtf(after) })), h('td', { class: delta === 0 ? 'zero' : ((delta > 0) === goodUp ? 'pos' : 'neg'), text: delta === 0 ? 'no change' : (delta > 0 ? '+' : '\u2212') + fmtf(Math.abs(delta)).replace('-', '') }));
        const W = STRESS_CHART[bucket()][0], H = STRESS_CHART[bucket()][1];
        const svg = chart({ id: 'st-c', balance: false, W, H, startDay: v.chart.startDay, endDay: v.chart.endDay, cushion: C, lines: [{ pts: r.series.baselineCautious, color: '#9ca3af', width: 2, dash: '2 4' }, { pts: r.series.expected, color: COLORS.expected, dash: '7 5' }, { pts: r.series.cautious, color: COLORS.cautious, width: 3 }],
          mark: { day: a.cautious.minDay, cents: a.cautious.minCents, label: 'Lowest: ' + axisMoney(a.cautious.minCents) + ', ' + dayLabel(a.cautious.minDay) }, title: 'Stress test result', desc: 'With the stress test, the cautious lowest balance is ' + money(a.cautious.minCents) + ' on ' + dayLabel(a.cautious.minDay) + ' instead of ' + money(b.cautious.minCents) + '.' });
        result = h('div', { class: 'st-result', id: 'st-result', role: 'region', 'aria-live': 'polite', 'aria-label': 'Stress test result' },
          h('div', { class: 'st-assume' }, h('b', { text: 'What if: ' }), r.assumptions.join(' ')),
          h('div', { class: 'st-status' }, badge(STATUS_WORD[b.standing.status], STATUS_KIND[b.standing.status]), h('span', { 'aria-hidden': 'true', text: ' \u2192 ' }), h('span', { class: 'sr-only', text: 'becomes' }), badge(STATUS_WORD[a.standing.status], STATUS_KIND[a.standing.status]), r.standingChanged ? h('span', { class: 'st-changed', text: ' The picture changes.' }) : null),
          h('table', { class: 'cmp st-table' }, h('caption', { class: 'sr-only', text: 'Before and after the stress test' }), h('thead', null, h('tr', null, h('th', { scope: 'col', text: '' }), h('th', { scope: 'col', text: 'Now' }), h('th', { scope: 'col', text: 'With the stress test' }), h('th', { scope: 'col', text: 'Change' }))),
            h('tbody', null,
              row('Lowest balance (cautious)', b.cautious.minCents, a.cautious.minCents, r.delta.minCents, money, true),
              row('Balance on ' + dayLabel(v.endDay) + ' (cautious)', b.cautious.endCents, a.cautious.endCents, r.delta.endCents, money, true),
              row('Lowest balance (expected)', b.expected.minCents, a.expected.minCents, r.delta.expectedMinCents, money, true),
              row('Room through ' + dayLabel(v.endDay), b.roomCents, a.roomCents, r.delta.roomCents, money, true),
              row('Needed between terms', b.needBetweenCents, a.needBetweenCents, r.delta.needBetweenCents, money, false))),
          h('div', { class: 'chart-wrap st-chart' }, svg),
          h('ul', { class: 'legend' }, legendItem('dot', '#9ca3af', 'Your plan now (cautious)'), legendItem('line', COLORS.cautious, 'With the stress test: cautious'), legendItem('dash', COLORS.expected, 'With the stress test: expected')),
          h('ul', { class: 'sure-list' }, r.sentences.map(s => h('li', { text: s }))),
          r.skipped.length ? h('p', { class: 'hint', text: 'Skipped: ' + r.skipped.map(s => s.reason).join(' ') }) : null,
          h('p', { class: 'safe-note' }, icon('lock', 14), h('span', { text: ' This was a what-if on a copy. Your saved plan, approved budgets and Today numbers did not change.' })));
      }
    }
    // each test alone, side by side (memoised with the view, so it is computed once per plan)
    if (!memoObj.table) memoObj.table = E.stressTable(plan, T);
    const t = memoObj.table;
    const compare = t.ok ? disclosure('stress-compare', 'Compare every test, one at a time',
      h('table', { class: 'cmp small' }, h('caption', { class: 'sr-only', text: 'Each stress test alone' }),
        h('thead', null, h('tr', null, ['Test', 'Lowest balance (cautious)', 'Change', 'Result'].map(x => h('th', { scope: 'col', text: x })))),
        h('tbody', null,
          h('tr', { class: 'base' }, h('th', { scope: 'row', text: 'Your plan today' }), h('td', null, h('b', { class: tone(t.baseline.minCents), text: money(t.baseline.minCents) })), h('td', { text: '' }), h('td', null, badge(STATUS_WORD[t.baseline.status], STATUS_KIND[t.baseline.status]))),
          t.rows.map(x => x.applies
            ? h('tr', null, h('th', { scope: 'row', text: x.label + ' (' + x.paramLabel + ')' }), h('td', null, h('b', { class: tone(x.minCents), text: money(x.minCents) })), h('td', { class: x.deltaMinCents < 0 ? 'neg' : x.deltaMinCents > 0 ? 'pos' : 'zero', text: x.deltaMinCents === 0 ? (x.deltaNeedCents ? 'needs ' + signed(x.deltaNeedCents) + ' after' : 'none') : signed(x.deltaMinCents) }), h('td', null, badge(STATUS_WORD[x.status], STATUS_KIND[x.status])))
            : h('tr', { class: 'na' }, h('th', { scope: 'row', text: x.label }), h('td', { colspan: 3, text: x.reason }))))), 'compare') : null;
    const mayaStress = App.state.persona === 'maya' && E.demoWalkthrough(App.state.plan)
      ? h('p', { class: 'hint', id: 'maya-stress-hint', text: 'On Maya’s starting plan, try an unexpected expense of $500. The cautious low falls below her $100 cushion. The test uses a copy and does not change her saved plan.' })
      : null;
    return card('stress-tools', 'What if something changes?', null, h('div', { class: 'sem-disclosure-body' },
      h('p', { class: 'hint', text: 'Pick one or more changes to test against a copy of your plan.' }), mayaStress, controls, result, compare));
  }

  function suggestionList(plan, T, list) {
    if (!list.length) return null;
    const sv = SV();
    const explain = rec => 'Your projected low would rise to ' + amount(rec.after.cautiousMinCents) + '.';
    const one = rec => {
      const confirming = sv.confirm === rec.id;
      return h('li', { class: 'rec-item ' + (rec.fullFix ? 'fix' : 'part') },
        h('b', { text: recTitle(rec) }), h('p', { text: explain(rec) }),
        rec.steps.length ? h('ul', { class: 'sure-list' }, rec.steps.map(s => h('li', { text: s }))) : null,
        rec.note ? h('p', { class: 'hint', text: rec.note }) : null,
        confirming ? h('div', { class: 'confirm-box', role: 'group', 'aria-label': 'Confirm change' },
          h('p', { text: 'Apply these changes to your saved plan?' }),
          h('div', { class: 'row-actions' }, h('button', { type: 'button', id: 'confirm-semester-change', class: 'btn primary small',
            onclick: () => commit(E.applyRecommendation(plan, T, rec.apply), 'rec', 'Done. Your plan and forecast have been updated.', { undo: true }),
            text: 'Yes, make this change' }),
          button('Not now', { kind: 'ghost small', onclick: () => { sv.confirm = null; App.focusId = 'review-' + rec.id; App.render(); } })))
          : rec.apply ? h('button', { type: 'button', class: 'btn ghost small', id: 'review-' + rec.id, text: rec.actionLabel,
            onclick: () => { sv.open['suggested-changes'] = true; sv.confirm = rec.id; App.focusId = 'confirm-semester-change'; App.render(); } })
          : rec.goto ? button(rec.actionLabel, { kind: 'ghost small', onclick: () => go(rec.goto.screen, rec.goto.open) }) : null);
    };
    return h('details', { id: 'suggested-changes', class: 'sure sem-suggest', open: !!sv.open['suggested-changes'],
      ontoggle: e => { sv.open['suggested-changes'] = e.target.open; } },
      h('summary', { class: 'btn primary', text: 'See suggested changes' }),
      h('ul', { class: 'recs' }, list.map(one)));
  }

  function afterCard(v) {
    const a = v.after;
    if (!a.ok) return null;
    const c = a.coverage, sv = SV(), dates = a.dates || v.dates;
    const bridge = a.bridge;
    const delayedAid = a.needExpectedCents !== a.needCents && dates.aidScheduledDay != null && dates.aidCautiousDay != null;
    const delayExpense = delayedAid ? v.expenses.find(e => e.day > dates.aidScheduledDay && e.day <= dates.aidCautiousDay) : null;
    const aidComparison = delayedAid ? h('p', { class: 'hint aid-timing-comparison', id: 'aid-timing-comparison',
      text: 'If aid arrives as scheduled on ' + dayLabel(dates.aidScheduledDay) + ', the between-term need is ' + amount(a.needExpectedCents) +
        '. In the cautious view it is counted on ' + dayLabel(dates.aidCautiousDay) + ', so the need is ' + amount(a.needCents) + ' through ' + dayLabel(bridge.endDay) + '.' +
        (delayExpense ? ' ' + delayExpense.name + ' (' + amount(delayExpense.amountCents) + ') is due ' + dayLabel(delayExpense.day) + ' while waiting.' : '') })
      : null;
    const gap = c.belowZeroCents > 0;
    const termEnd = dayLabel(a.semesterEndDay);
    const calcLine = (label, cents, neg) => h('div', null, h('dt', { text: label }), h('dd', { class: neg ? 'neg' : '', text: amount(cents) }));
    const calc = h('dl', { class: 'sem-calc' },
      calcLine('Needed by ' + termEnd + ' \u00b7', a.needCents, false),
      calcLine('Projected balance on ' + termEnd + ' \u00b7', c.endBalanceIfBudgetsFollowedCents, c.endBalanceIfBudgetsFollowedCents < 0),
      calcLine('Projected shortfall \u00b7', c.belowZeroCents, gap));
    const items = a.items.length ? h('ul', { class: 'bt-items' }, a.items.slice().sort((x, y) => x.day - y.day).map(i => h('li', null,
      h('time', { datetime: D.fmt(i.day), text: dayLabel(i.day) + ' ' }), h('b', { text: i.name }), h('span', { text: ' ' + amount(i.amountCents) })))) : null;
    const offers = a.offers.map(o => {
      const apply = () => {
        const res = o.op.type === 'reserve' ? E.setReserve(App.state.plan, { bridge: true }) : E.setReserve(App.state.plan, { fixedCents: o.op.fixedCents });
        const note = o.partial ? ' Still to earmark toward your reserve target ' + amount(o.uncoveredCents) + '.' : '';
        sv.reserveConfirm = null;
        commit(res, 'after', 'Done. ' + amount(o.coversCents) + ' is now earmarked in your plan.' + note, { undo: true });
      };
      return h('div', { class: 'offer' },
        h('p', { text: 'Proposed earmark ' + amount(o.coversCents) }),
        o.partial ? h('p', { class: 'amber-text', text: 'Still to earmark toward your reserve target ' + amount(o.uncoveredCents) }) : null,
        sv.reserveConfirm === o.id ? h('div', { class: 'confirm-box', role: 'group', 'aria-label': 'Confirm reserve amount' },
          h('p', { text: 'Earmark ' + amount(o.coversCents) + ' in your saved plan?' }),
          h('div', { class: 'row-actions' }, h('button', { type: 'button', id: 'confirm-reserve', class: 'btn primary small', text: 'Confirm reserve', onclick: apply }),
            button('Not now', { kind: 'ghost small', onclick: () => { sv.reserveConfirm = null; App.focusId = 'reserve-' + o.id; App.render(); } })))
          : h('button', { type: 'button', id: 'reserve-' + o.id, class: 'btn ghost small', text: o.label, onclick: () => {
            sv.open['after-term-details'] = true; sv.reserveConfirm = o.id; App.focusId = 'confirm-reserve'; App.render();
          } }));
    });
    const clearReserve = a.reserveEnabled ? (sv.reserveConfirm === 'clear'
      ? h('div', { class: 'confirm-box', role: 'group', 'aria-label': 'Confirm reserve removal' },
        h('p', { text: 'Remove the earmark from your saved plan?' }),
        h('div', { class: 'row-actions' }, h('button', { type: 'button', id: 'confirm-reserve', class: 'btn primary small', text: 'Confirm removal', onclick: () => {
          sv.reserveConfirm = null;
          commit(E.setReserve(App.state.plan, { bridge: false, fixedCents: 0 }), 'after', 'Reserve earmark removed from your plan.', { undo: true });
        } }), button('Not now', { kind: 'ghost small', onclick: () => { sv.reserveConfirm = null; App.focusId = 'reserve-clear'; App.render(); } })))
      : h('button', { type: 'button', id: 'reserve-clear', class: 'btn ghost small', text: 'Remove reserve earmark', onclick: () => {
        sv.open['after-term-details'] = true; sv.reserveConfirm = 'clear'; App.focusId = 'confirm-reserve'; App.render();
      } })) : null;
    const info = disclosure('after-term-details', 'See how it\'s calculated', h('div', { class: 'sem-disclosure-body' },
      calc,
      aidComparison,
      delayedAid ? h('p', { text: 'Still uncovered ' + amount(c.uncoveredCents) + '. After using ' + amount(c.aboveCushionCents) + ' above your ' + amount(v.cushion.cents) + ' cushion.' }) : null,
      delayedAid ? h('p', { class: 'hint', text: 'With approved budgets spent in full, the cautious balance reaches ' + amount(c.lowestAfterCents) + ' on ' + dayLabel(c.lowestAfterDay) + '.' }) : null,
      dates.aidLabel ? h('p', { text: dates.aidLabel + '.' }) : h('p', { class: 'hint', text: 'No refund is scheduled in this forecast window.' }),
      bridge ? h('p', { text: 'Everyday essentials ' + amount(bridge.essentialsCents) + (bridge.incomeCents ? ' · Forecast income ' + amount(bridge.incomeCents) : '') }) : null,
      items,
      a.appliedReserveCents > 0 ? h('p', null, 'Earmarked in your plan ', h('b', { text: amount(a.appliedReserveCents) })) : null,
      h('p', { class: 'hint', text: 'Earmarking sets money aside in your plan only. The projected shortfall is based on your forecast balance, and the earmark does not add to that balance.' }),
      offers.length ? h('div', { class: 'offers' }, offers) : null, clearReserve));
    info.firstElementChild.id = 'after-term-summary';
    const when = bridge
      ? dayLabel(bridge.startDay) + '\u2013' + dayLabel(bridge.endDay) + (gap ? '. Your balance could fall below $0 on ' + dayLabel(c.lowestAfterDay) + '.' : '.')
      : '';
    const aidDelayed = dates.aidScheduledDay != null && dates.aidCautiousDay != null && dates.aidScheduledDay !== dates.aidCautiousDay;
    const aidNote = aidDelayed ? h('p', { class: 'sem-bridge-when', id: 'aid-delay-note', text: 'Aid is scheduled for ' + dayLabel(dates.aidScheduledDay) + '. This forecast plans for it to arrive ' + dayLabel(dates.aidCautiousDay) + '.' }) : null;
    const node = card('af-h', 'Between semesters', null,
      gap ? h('p', { class: 'sem-bridge-lead' }, h('b', { text: amount(c.belowZeroCents) }), ' projected shortfall') : h('p', { class: 'sem-bridge-lead', text: 'Forecast costs are covered' }),
      h('div', { class: 'sem-bridge-notes' },
        when ? h('p', { class: 'sem-bridge-when', text: when }) : h('p', { class: 'hint', text: 'No separate forecast window is available.' }),
        aidNote),
      h('div', { class: 'row-actions' }, button('Review reserve', { kind: 'primary small', onclick: () => {
        sv.open['after-term-details'] = true;
        App.focusId = 'after-term-summary';
        App.render();
      } })),
      info, msgNode('after'));
    if (gap) node.classList.add('short');
    return node;
  }

  /* ---------- planned one-time expenses ---------- */
  function expensesCard(v, plan, T) {
    const sv = SV(), x = sv.exp, err = errorBox();
    if (!x.date) x.date = D.fmt(Math.min(v.endDay, T + 14));
    const idN = nid('en'), idD = nid('ed'), idC = nid('ec'), idE = nid('ee');
    const amt = moneyBox({ label: 'Amount' }); amt.input.value = x.amountText; amt.input.addEventListener('input', () => { x.amountText = amt.input.value; });
    const nm = h('input', { id: idN, type: 'text', maxlength: 60, autocomplete: 'off', value: x.name, placeholder: 'Chemistry textbook' }); nm.addEventListener('input', () => { x.name = nm.value; });
    const dt = h('input', { id: idD, type: 'date', min: D.fmt(T + 1), value: x.date }); dt.addEventListener('input', () => { x.date = dt.value; });
    const cat = h('select', { id: idC }, E.PLANNED_CATEGORIES.map(c => h('option', { value: c.category, selected: c.category === x.cat, text: c.label })));
    const must = h('input', { id: idE, type: 'checkbox', checked: x.essential }); cat.addEventListener('change', () => { x.cat = cat.value; const c = E.PLANNED_CATEGORIES.find(k => k.category === x.cat); x.essential = !!(c && c.essential); must.checked = x.essential; }); must.addEventListener('change', () => { x.essential = must.checked; });
    const form = h('form', { class: 'exp-form', novalidate: '', onsubmit: ev => { ev.preventDefault(); err.clear(); const cents = readMoney(x.amountText); if (cents == null || cents <= 0) return err.show('Enter an amount above $0.');
        const res = E.addPlannedExpense(plan, { name: x.name, amountCents: cents, date: x.date, category: x.cat, essential: x.essential }); if (!res.ok) return err.show(res.error);
        sv.open['planned-expense'] = false; sv.exp = { name: '', amountText: '', date: '', cat: 'Other', essential: false }; commit(res, 'exp', 'Added. It now appears on your timeline and in every forecast.', { undo: true }); } },
      h('div', { class: 'field' }, h('label', { for: idN, text: 'What is it?' }), nm), amt.node, h('div', { class: 'field' }, h('label', { for: idD, text: 'Date it is due' }), dt), h('div', { class: 'field' }, h('label', { for: idC, text: 'Kind of expense' }), cat),
      h('div', { class: 'field check' }, must, h('label', { for: idE, text: 'I have to pay this (it is not optional)' })), err.node,
      h('button', { type: 'submit', class: 'btn primary small' }, icon('check'), h('span', { text: 'Add to my plan' })));
    const list = h('ul', { class: 'pe-list' }, v.expenses.map(e => h('li', null, h('span', null, h('b', { text: e.name }), h('span', { class: 'pe-sub', text: ' ' + dayLabel(e.day) + ', ' + (e.essential ? 'must pay' : 'optional') + (e.day > v.endDay ? ', after the term' : '') })), h('b', { text: m0(e.amountCents) }),
      button('Remove', { kind: 'ghost small', aria: 'Remove ' + e.name, onclick: () => commit(E.removePlannedExpense(plan, e.id), 'exp', 'Removed "' + e.name + '". Your forecast is updated.', { undo: true }) }))));
    return card('planned-expense', 'Add a planned expense', null, form, v.expenses.length ? list : null, msgNode('exp'));
  }

  /* ---------- the screen ---------- */
  App.screens.semester = function () {
    const st = App.state, plan = st.plan, T = App.today(); st.home = true;
    if (!plan) return h('section', { class: 'card' }, h('h1', { id: 'title', tabindex: '-1', text: 'Semester plan' }), h('p', { text: 'Start with the first screen to build your plan.' }));
    const mo = data(plan, T), v = mo.v;
    if (!v.ok) return h('section', { class: 'card' }, h('h1', { id: 'title', tabindex: '-1', text: 'Semester plan' }), h('p', { text: 'We need your checking balance before we can draw your semester.' }), h('div', { class: 'actions' }, button('Open Today', { onclick: () => App.go('today', { reset: true }) })));
    const tools = [expensesCard(v, plan, T), stressCard(v, plan, T, mo), st.persona === 'jordan' ? null : forecastDetails(v)];
    return h('div', { class: 'stack semester' },
      outlook(v, plan, T, mo), timelineCard(v), tools);
  };
  let lastBucket = bucket();
  window.addEventListener('resize', () => {
    const next = bucket();
    if (next !== lastBucket) {
      lastBucket = next;
      if (App.state && App.state.step === 'semester') App.render();
    }
  });
})();

;
/* ===== ui/10-goals.js ===== */
/* ---- Stage E: Goals, savings pockets, and explicit plan choices ----
   Every number on this screen comes from E.goalStatus, E.goalAllocation, E.goalAlternatives, E.savingsSummary
   and E.checkGoalPlan. The UI never does money arithmetic of its own. Nothing here changes a contribution,
   a budget, a savings balance or a goal unless the student presses the button that says so. */
(function () {
  'use strict';
  const E = CCE, D = E.D;
  const { h, icon, button, badge, money, dollarsText, readMoney, dayLabel, moneyBox, textBox, selectBox, errorBox } = App;
  const TYPE_LABEL = { emergency: 'Emergency fund', purchase: 'A purchase', trip: 'A trip', savings: 'General savings', other: 'Something else' };
  const FEASIBLE = { feasible: ['Fits your plan', 'good'], needs_changes: ['Needs a change', 'amber'], unreachable: ['Not reachable on time', 'warn'], paused: ['Paused', 'soft'], done: ['Completed', 'good'], on_track: ['On track', 'good'], reached: ['Target reached', 'good'], reached_unconfirmed: ['Confirm savings', 'amber'], no_deadline: ['No deadline', 'soft'] };
  const TYPE_OPTS = E.GOAL_TYPES.map(t => ({ value: t, label: TYPE_LABEL[t] || t }));
  let uid = 0; const nid = p => 'gv' + (++uid) + '-' + p;
  let memo = { key: '', status: null, alloc: null, alts: null };

  function GV() {
    const st = App.state;
    if (!st.gv) st.gv = { form: blankForm(), editId: null, showAdd: false, showAltsFor: null, pending: null, confirmDisc: false, savingsText: '', floorText: '', msg: {}, open: {} };
    return st.gv;
  }
  function blankForm(g) {
    g = g || {};
    return { name: g.name || '', targetText: g.targetCents != null ? dollarsText(g.targetCents) : '', savedText: g.savedCents != null ? dollarsText(g.savedCents) : '', dueDate: g.dueDate || '', type: g.type || 'purchase', priority: g.priority != null ? String(g.priority) : '' };
  }
  const msgNode = where => {
    const m = GV().msg[where];
    return m ? h('p', { class: 'tv-msg ' + m.kind, id: where + '-msg', tabindex: '-1', role: m.kind === 'bad' ? 'alert' : 'status', text: m.msg }) : null;
  };
  function commit(res, where, msg, o) {
    o = o || {}; const gv = GV();
    if (!res || !res.ok) { gv.msg = {}; gv.msg[where] = { msg: (res && res.error) || 'That did not work. Nothing was changed.', kind: 'bad' }; App.focusId = where + '-msg'; App.render(); return false; }
    App.setPlan(res.plan); gv.msg = {}; if (msg) gv.msg[where] = { msg, kind: o.kind || 'good' };
    gv.pending = null; gv.confirmDisc = false; gv.editId = o.keepEdit ? gv.editId : null;
    App.focusId = o.focus || (msg ? where + '-msg' : where); App.render(); return true;
  }
  function data(plan, T) {
    const k = E.hash32(JSON.stringify(plan)) + '|' + T;
    if (memo.key !== k) {
      const gv = GV();
      gv.pending = null; gv.confirmDisc = false;
      const status = E.goalStatus(plan, T), alloc = E.goalAllocation(plan, T);
      memo = { key: k, status, alloc, alts: alloc.ok ? E.goalAlternatives(plan, T, { allocation: alloc }) : { ok: false, goals: [] } };
    }
    return memo;
  }


  const compactMoney = cents => money(cents).replace(/\.00$/, '');
  function details(id, label, body, cls = 'sure') {
    const state = GV().open;
    return h('details', { id, class: cls, open: !!state[id], ontoggle: e => { state[id] = e.target.open; } },
      h('summary', { class: cls === 'card sure' ? 'card-title' : null, text: label }), body);
  }
  function control(id, label, kind, onclick, aria) {
    return h('button', { id, type: 'button', class: 'btn ' + kind, text: label, onclick, 'aria-label': aria });
  }

  function savingsDetails(where) {
    const plan = App.state.plan, T = App.today(), gv = GV(), err = errorBox();
    const sav = E.savingsSummary(plan), C = plan.account.cushionCents;
    const amt = moneyBox({ label: 'Savings-account balance', hint: 'The amount in savings as of today. Leave this blank if you do not have a separate savings account.' });
    amt.input.id = where + '-sav-amt'; amt.node.querySelector('label').setAttribute('for', amt.input.id);
    amt.input.value = gv.savingsText; amt.input.addEventListener('input', () => { gv.savingsText = amt.input.value; });
    const pocket = (k, v) => h('li', { class: 'pocket' }, h('b', { text: k }), h('span', { class: 'pocket-value', text: v }));
    const form = h('form', { class: 'form', novalidate: '', onsubmit: ev => {
      ev.preventDefault(); err.clear();
      const cents = readMoney(gv.savingsText); if (cents == null) return err.show('Enter an amount of $0 or more, like 200 or 200.00.');
      commit(E.setSavingsBalance(plan, cents, T), where, 'Saved. Your savings balance is ' + money(cents) + ' as of ' + dayLabel(T) + '. Linked goal transfers after that date will be added on top.');
    } }, amt.node, err.node, h('button', { type: 'submit', class: 'btn primary small' }, h('span', { text: 'Update savings balance' })));
    return h('section', { id: 'savings-details', class: 'card', 'aria-labelledby': 'savings-h' },
      h('h2', { id: 'savings-h', class: 'card-title', text: 'Savings details' }),
      h('div', { class: 'goal-details-body' },
      h('ul', { class: 'items pockets' },
        pocket('Checking', money(plan.account.balanceCents)),
        pocket('Savings account', money(sav.savingsNowCents)),
        pocket('Set aside for goals', money(sav.allocatedCents)),
        pocket('Unallocated savings', money(sav.unallocatedCents)),
        pocket('Protected cushion', money(C))),
      sav.overAllocatedCents > 0 ? h('p', { class: 'hint', text: 'Goal savings add up to ' + money(sav.overAllocatedCents) + ' more than the savings balance on record. That does not invent money; it means a saved amount needs an update.' }) : null,
      msgNode(where), form));
  }

  function goalForm(plan, T, existing) {
    const gv = GV(), err = errorBox(), f = gv.form, editing = !!(existing && existing.id);
    const name = textBox({ label: 'Name', value: f.name, placeholder: 'Laptop', max: 60, hint: 'A short name you will recognize.' });
    name.input.id = 'goal-name'; name.node.querySelector('label').htmlFor = name.input.id;
    name.input.addEventListener('input', () => { f.name = name.input.value; });
    const target = moneyBox({ label: 'Target', hint: 'How much you want to have saved.' });
    target.input.value = f.targetText; target.input.addEventListener('input', () => { f.targetText = target.input.value; });
    const saved = moneyBox({ label: 'Already saved', hint: 'Confirmed savings for this goal right now. $0 is fine.' });
    saved.input.value = f.savedText; saved.input.addEventListener('input', () => { f.savedText = saved.input.value; });
    const dueId = nid('due'), due = h('input', { id: dueId, type: 'date', value: f.dueDate }); due.addEventListener('input', () => { f.dueDate = due.value; });
    const type = selectBox({ label: 'Kind of goal', value: f.type, options: TYPE_OPTS }); type.input.addEventListener('change', () => { f.type = type.input.value; });
    const pri = textBox({ label: 'Priority (1 is first)', value: f.priority, placeholder: String(plan.goals.length + 1), hint: 'Your ranking, not the deadline. 1 is funded first.' });
    pri.input.inputMode = 'numeric'; pri.input.addEventListener('input', () => { f.priority = pri.input.value; });
    const form = h('form', { class: 'form goal-form', novalidate: '', onsubmit: ev => {
      ev.preventDefault(); err.clear();
      const targetCents = readMoney(f.targetText); if (targetCents == null || targetCents <= 0) return err.show('Enter a target above $0.');
      const savedCents = f.savedText.trim() === '' ? 0 : readMoney(f.savedText); if (savedCents == null || savedCents < 0) return err.show('Enter how much is already saved as $0 or more.');
      const priority = f.priority.trim() === '' ? undefined : Math.round(Number(f.priority));
      if (f.priority.trim() && !(Number.isInteger(priority) && priority >= 1 && priority <= 99)) return err.show('Priority must be between 1 and 99.');
      if (editing) {
        const r = E.updateGoal(plan, existing.id, { name: f.name, type: f.type, targetCents, dueDate: f.dueDate, priority, savedCents }, T);
        if (commit(r, 'goals', 'Updated "' + (r.ok ? (r.plan.goals.find(g => g.id === existing.id) || {}).name : f.name) + '". Nothing was set aside until you accept a savings plan.', { keepEdit: false })) gv.form = blankForm();
      } else {
        const r = E.addGoal(plan, { name: f.name, type: f.type, targetCents, savedCents, dueDate: f.dueDate, priority }, T);
        if (r.ok) gv.showAdd = false;
        if (commit(r, 'goals', 'Goal added. Open its options to plan transfers.')) gv.form = blankForm();
      }
    } },
      name.node, target.node, saved.node, h('div', { class: 'field' }, h('label', { for: dueId, text: 'Deadline (optional)' }), due, h('p', { class: 'hint', text: 'I use this to check whether the plan can get you there on time.' })),
      type.node, pri.node, err.node,
      h('div', { class: 'row-actions' },
        h('button', { type: 'submit', class: 'btn primary small' }, h('span', { text: editing ? 'Save changes' : 'Add this goal' })),
        button(editing ? 'Cancel' : 'Not now', { kind: 'ghost small', onclick: () => { gv.editId = null; gv.showAdd = false; gv.form = blankForm(); App.focusId = editing ? 'edit-' + existing.id : 'add-goal'; App.render(); } })));
    return form;
  }

  function progressBar(have, need) {
    const pct = need > 0 ? Math.max(0, Math.min(100, Math.round(100 * have / need))) : (have > 0 ? 100 : 0);
    return h('div', { class: 'pbar', role: 'img', 'aria-label': money(have) + ' of ' + money(need) + ' saved' }, h('span', { class: 'pfill', style: 'width:' + pct + '%' }));
  }

  function goalCard(row, plan, T, mo) {
    const gv = GV(), id = row.goalId, g = plan.goals.find(x => x.id === id);
    const allocation = mo.alloc, ag = allocation.ok ? allocation.goals.find(x => x.goalId === id) : null;
    const status = row.goalStatus !== 'active' ? row.goalStatus
      : row.reached ? 'reached' : row.onTrack && allocation.ok && allocation.current.safe && ag?.status === 'feasible' ? 'on_track'
      : ag?.status || 'needs_changes';
    const badgePair = FEASIBLE[status] || FEASIBLE.needs_changes;
    const editing = gv.editId === id, expanded = gv.showAltsFor === id;
    const pack = mo.alts.ok && mo.alts.goals.find(x => x.goalId === id);
    const recommended = allocation.ok && allocation.recommended && allocation.safe && allocation.changes.find(c => c.goalId === id);
    const actions = row.goalStatus === 'active' ? [
      button('Pause', { kind: 'ghost small', aria: 'Pause ' + row.name, onclick: () => changeStatus('paused', 'Paused') }),
      button('Mark complete', { kind: 'ghost small', aria: 'Mark ' + row.name + ' complete', onclick: () => changeStatus('done', 'Completed') })
    ] : [button(row.goalStatus === 'paused' ? 'Resume' : 'Reopen', { kind: 'ghost small', onclick: () => changeStatus('active', row.goalStatus === 'paused' ? 'Resumed' : 'Reopened') })];
    function changeStatus(value, label) {
      gv.showAltsFor = null;
      gv.open['manage-' + id] = true;
      commit(E.setGoalStatus(plan, id, value), 'goals', label + ' “' + row.name + '”.');
    }
    const limitedSavings = status === 'unreachable' && ag?.maxPossibleCents != null && ag.required;
    const floor = allocation.discretionary?.effectiveFloorWeeklyCents;
    const savingFor = row.type === 'trip' && /^bus\b/i.test(row.name) ? 'the bus ticket' : 'this goal';
    const reason = limitedSavings
      ? 'You still need ' + compactMoney(ag.needCents) + ' by ' + dayLabel(ag.dueDay) + '. ' +
        (ag.maxPossibleCents > 0 ? 'That’s ' + compactMoney(ag.requiredCents) + ' each time you set money aside. ' : '') +
        'Even if you pause your other goals and cut optional spending to ' + compactMoney(floor) + (floor > 0 ? ' a week' : '') +
        (ag.maxPossibleCents > 0 ? ', your plan can set aside only ' + compactMoney(ag.maxPossibleCents) + ' each time.' : ', your plan has no money left to put toward ' + savingFor + '.') +
        (ag.afterTerm ? ' The deadline is after the term ends, so the forecast checks the transfers only through ' + dayLabel(allocation.endDay) + '.' : '')
      : status === 'needs_changes' && allocation.ok && !allocation.current.safe && row.required
      ? 'Your current plan can’t fund this goal while protecting your ' + compactMoney(plan.account.cushionCents) + ' cushion.'
      : status === 'on_track' ? 'Your planned transfers support this goal' + (row.afterTerm ? ' through ' + dayLabel(allocation.endDay) : '') + '.'
      : status === 'feasible' ? 'You can schedule transfers while protecting your cushion.'
      : status === 'reached_unconfirmed' ? 'Update the saved amount after verifying those transfers.'
      : status === 'unreachable' || status === 'no_deadline' ? ag?.reason : '';
    const edit = control('edit-' + id, 'Edit goal', pack || recommended ? 'ghost small' : 'primary small', () => {
      gv.editId = id; gv.form = blankForm(g); gv.showAdd = false; gv.showAltsFor = null; gv.pending = null;
      App.focusId = 'goal-name'; App.render();
    }, 'Edit goal: ' + row.name);
    const toggle = pack || recommended ? h('button', {
      id: 'options-' + id, type: 'button', class: 'btn primary small', 'aria-expanded': String(expanded),
      'aria-controls': expanded ? 'alt-' + id : null, text: expanded ? 'Hide savings options' : 'Show savings options',
      onclick: () => {
        gv.showAltsFor = expanded ? null : id; gv.pending = null; gv.confirmDisc = false;
        App.focusId = expanded ? 'options-' + id : 'alt-' + id; App.render();
      }
    }) : null;
    return h('article', { class: 'card goal-card', 'aria-labelledby': 'g-' + id },
      h('header', { class: 'gc-head' }, h('h2', { id: 'g-' + id },
        row.name, row.dueDay != null ? h('span', { class: 'goal-due', text: ' · Due ' + dayLabel(row.dueDay) }) : null),
        badge(badgePair[0], badgePair[1])),
      progressBar(row.confirmedCents, row.targetCents),
      h('p', { class: 'goal-progress', text: compactMoney(row.confirmedCents) + ' saved of ' + compactMoney(row.targetCents) +
        (row.remainingCents != null ? ' · ' + compactMoney(row.remainingCents) + ' to go' : '') }),
      reason ? h('p', { class: 'hint', text: reason }) : null,
      row.currentContributionCents && row.goalStatus === 'active' ? h('p', { class: 'hint', text: 'Planned transfers ' + compactMoney(row.currentContributionCents) + ' each' }) : null,
      h('div', { class: 'row-actions' }, toggle, edit),
      editing ? goalForm(plan, T, g) : null,
      expanded ? optionsBlock(plan, T, id, pack, allocation, recommended) : null,
      details('manage-' + id, 'Manage goal', h('div', { class: 'row-actions' }, actions)));
  }

  function optionsBlock(plan, T, id, pack, allocation, recommended) {
    const gv = GV();
    const options = pack ? pack.options.slice() : [];
    if (recommended && !options.some(o => o.choice === allocation.choice)) options.unshift({
      kind: 'recommended', available: true, choice: allocation.choice, validation: allocation.validation,
      text: recommended.toCents > 0 ? 'Save ' + compactMoney(recommended.toCents) + ' per transfer.' : 'Stop the currently planned transfers for this goal.'
    });
    const workable = options.filter(o => o.available && o.choice && o.validation?.safe)
      .map(o => ({ option: o, preview: E.goalTransferPreview(plan, T, id, o.choice) }))
      .sort((a, b) => Number(b.preview?.meetsDeadline === true) - Number(a.preview?.meetsDeadline === true));
    const unavailable = options.filter(o => !workable.some(x => x.option === o));
    return h('div', { class: 'alts', id: 'alt-' + id, tabindex: '-1', 'aria-labelledby': 'options-heading-' + id, role: 'region' },
      h('h3', { id: 'options-heading-' + id, text: 'Savings options' }),
      workable.length ? workable.map(({ option, preview }) => optionCard(plan, T, id, option, preview, allocation))
        : h('p', { class: 'hint', text: 'The forecast found no workable option with these settings.' }),
      unavailable.length ? details('unavailable-' + id, 'Why other options don’t fit',
        h('ul', { class: 'sure-list' }, unavailable.map(o => h('li', { text: o.available ? o.text + ' This would leave your plan below its protected balance.' : o.text })))) : null);
  }

  function optionCard(plan, T, goalId, option, preview, allocation) {
    const gv = GV(), key = goalId + '-' + option.kind;
    const pending = gv.pending === key;
    const needsDisc = !!option.choice.discretionary;
    const summary = option.kind === 'reduce_discretionary'
      ? 'Spend ' + money(option.weeklyCents) + ' a week on flexible purchases instead of ' + money(allocation.discretionary.plannedWeeklyCents) +
        ', and save ' + compactMoney(option.amountCents) + ' per transfer.'
      : option.text;
    const deadline = preview && preview.dueDay != null
      ? preview.meetsDeadline === true ? 'Meets the ' + dayLabel(preview.dueDay) + ' deadline.'
        : preview.meetsDeadline === false ? 'Falls short of the ' + dayLabel(preview.dueDay) + ' deadline.'
        : 'The forecast checks transfers through ' + dayLabel(preview.endDay) + '.'
      : null;
    const others = option.choice.goals.filter(c => {
      if (c.id === goalId) return false;
      const goal = plan.goals.find(g => g.id === c.id);
      return goal && ((c.amountCents !== undefined && c.amountCents !== (goal.contribution?.amountCents || 0)) ||
        (c.priority !== undefined && c.priority !== goal.priority) || (c.dueDate !== undefined && c.dueDate !== goal.dueDate));
    });
    return h('article', { class: 'alt-card' },
      h('p', { class: 'goal-option-summary', text: summary }),
      deadline ? h('p', { text: deadline }) : null,
      preview?.transfers.length ? h('ul', { class: 'goal-transfer-list', 'aria-label': 'Planned transfers' },
        preview.transfers.map(t => h('li', null, h('b', { text: dayLabel(t.day) }), ' · ' + compactMoney(t.amountCents)))) : null,
      others.length ? h('ul', { class: 'sure-list', 'aria-label': 'Changes to other goals' }, others.map(c => h('li', {
        text: plan.goals.find(g => g.id === c.id).name +
          (c.amountCents !== undefined ? ' · ' + compactMoney(c.amountCents) + ' per transfer' : '') +
          (c.priority !== undefined ? ' · Priority ' + c.priority : '') +
          (c.dueDate ? ' · Due ' + dayLabel(D.parse(c.dueDate)) : '')
      }))) : null,
      pending ? h('div', { class: 'confirm-box', role: 'group', 'aria-label': 'Confirm savings plan' },
        h('p', { text: 'Apply these changes to your saved plan?' }),
        needsDisc ? h('label', { class: 'confirm' }, h('input', {
          id: 'confirm-spending-' + key, type: 'checkbox', checked: gv.confirmDisc,
          onchange: e => { gv.confirmDisc = e.target.checked; App.focusId = e.target.id; App.render(); }
        }), h('span', { text: 'I choose to lower my flexible spending to ' + money(option.choice.discretionary.weeklyCents) + ' per week.' })) : null,
        h('div', { class: 'row-actions' },
          h('button', { id: 'confirm-option-' + key, type: 'button', class: 'btn primary small', text: 'Yes, use this plan',
            disabled: needsDisc && !gv.confirmDisc, onclick: () => {
              const choice = E.clone(option.choice);
              if (needsDisc) choice.discretionary.confirmed = true;
              const result = E.applyGoalPlan(plan, choice, T);
              if (result.ok) gv.showAltsFor = null;
              commit(result, 'goals', 'Savings plan updated. Record each transfer after it happens to update confirmed savings.');
            } }),
          button('Keep my current plan', { kind: 'ghost small', onclick: () => {
            gv.pending = null; gv.confirmDisc = false; App.focusId = 'choose-' + key; App.render();
          } })))
        : h('div', { class: 'row-actions' }, control('choose-' + key, 'Use this plan', 'ghost small', () => {
          gv.pending = key; gv.confirmDisc = false;
          App.focusId = (needsDisc ? 'confirm-spending-' : 'confirm-option-') + key;
          App.render();
        })));
  }

  App.screens.goals = function () {
    const st = App.state, plan = st.plan, T = App.today();
    if (!plan) return h('section', { class: 'card' }, h('h1', { id: 'title', tabindex: '-1', text: 'Goals' }), h('p', { text: 'Start with the first screen to build your plan.' }), button('Start', { onclick: () => App.go('welcome', { reset: true }) }));
    st.home = true; App.save();
    const gv = GV(), mo = data(plan, T), persona = st.persona ? E.demoPersona(st.persona) : null;
    const rows = mo.status.ok ? mo.status.goals : [];
    const mayaGoal = persona && persona.id === 'maya' ? rows.find(r => r.name === 'Used laptop') : null;
    return h('div', { class: 'stack goals' },
      h('section', { class: 'today-head goals-head' },
        h('div', null, persona ? h('p', { class: 'eyebrow', text: 'Sample student: ' + persona.name + ' (made-up data)' }) : null,
          h('h1', { id: 'title', tabindex: '-1', text: 'Save for what matters' }),
          mayaGoal ? h('p', { class: 'sub maya-goal-hint' }, 'Maya has ' + money(mayaGoal.confirmedCents) + ' confirmed toward ' + money(mayaGoal.targetCents) + '. Open its options to preview transfers; confirmed savings changes only when you record them.') : null),
        control('add-goal', gv.showAdd ? 'Hide goal form' : 'Add a goal', 'primary', () => {
          gv.showAdd = !gv.showAdd; gv.editId = null; gv.form = blankForm();
          App.focusId = gv.showAdd ? 'goal-name' : 'add-goal'; App.render();
        })),
      msgNode('goals'),
      gv.showAdd ? h('section', { class: 'card', 'aria-label': 'Add a goal' }, goalForm(plan, T, null)) : null,
      h('section', { id: 'gl-h', class: 'goal-list', 'aria-label': 'Your goals' },
        rows.length ? rows.map(r => goalCard(r, plan, T, mo)) : h('p', { class: 'hint', text: 'Add a goal to set a savings target.' })),
      savingsDetails('goal-savings'));
  };
})();

;
/* ===== ui/11-about.js ===== */
/* ---- About, license and privacy (reachable from the footer on every screen) ---- */
(function () {
  'use strict';
  const { h, icon, button, card } = App;
  const MIT = [
    'Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:',
    'The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.',
    'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.'
  ];

  App.screens.about = function () {
    const st = App.state;
    const back = () => { if (st.hist.length) App.back(); else App.go(st.plan && st.done ? App.homeStep() : 'welcome', { reset: true }); };
    return h('div', { class: 'stack about' },
      h('section', { class: 'card narrow-lg' },
        h('p', { class: 'eyebrow', text: 'About' }),
        h('h1', { id: 'title', tabindex: '-1', text: 'About Campus Compass' }),
        h('p', { class: 'lede', text: 'A budgeting coach for University of Kentucky students whose money arrives in lumps (a financial aid refund once a term, a campus paycheck that changes with their hours, help from family) while rent, groceries and fees fall due on fixed dates.' }),
        h('p', { text: 'A bank app shows today\'s balance. Campus Compass shows how much of it is actually free to spend once everything due before your next money arrives is set aside, checks a purchase against your lowest balance in the weeks ahead, and keeps savings goals from quietly eating your rent money.' }),
        h('div', { class: 'actions' }, button('Back', { kind: 'ghost', icon: 'back', onclick: back }))),
      card('Educational use only', null, h('div', null,
        h('p', { text: 'Campus Compass is an educational budgeting tool. It is not financial, investment, tax or legal advice, and it never recommends investments or securities. Its numbers are estimates calculated by fixed rules from what you enter; they are not promises. Check balances and due dates with your bank, landlord and financial aid office before relying on them.' }),
        h('p', { class: 'hint', text: 'Made for the 2026 Kentucky PFM Challenge. Neither Globefin nor the University of Kentucky endorses its calculations or conclusions.' }))),
      card('Your privacy', null, h('ul', { class: 'promises' },
        h('li', null, icon('lock', 16), h('span', { text: 'Everything stays on this device. Campus Compass uses no outside services: the page makes no network requests, has no accounts, logins, analytics or tracking, and needs no API key.' })),
        h('li', null, icon('file', 16), h('span', { text: '"Save file" downloads your plan as a file only you hold. "Open file" loads one back. A file that is not a valid Campus Compass plan is refused and nothing changes.' })),
        h('li', null, icon('check', 16), h('span', { text: 'Your browser also keeps a copy for next time. "Start over" erases it from this device.' })))),
      card('License', null, h('div', { class: 'license' },
        h('p', null, h('b', { text: CC_LICENSE.line })),
        h('p', { class: 'small', text: 'MIT License' }),
        MIT.map(t => h('p', { class: 'small', text: t })))),
      card('Credits', null, h('div', null,
        h('p', { text: 'Written for this project by ' + CC_LICENSE.author + ' with the help of AI coding assistants, as the challenge expects. It contains no third-party libraries, frameworks, fonts, images or code copied from elsewhere. Icons are simple shapes drawn for this page.' }),
        h('p', { class: 'hint', text: 'Saved files carry a checksum computed with the FNV-1a hash, a public-domain method, only to detect a damaged file. The sample students and their bank files are made up.' }))));
  };
})();

;
/* ===== ui/99-main.js ===== */
/* ---- start-up ---- */
(function () {
  'use strict';
  function boot() {
    // Rule 5: warn before closing while the plan has changes that are not saved to a file.
    // Browsers only show that prompt after the visitor has interacted with the page, and log an error if asked earlier.
    let acted = false; const mark = () => { acted = true; };
    ['pointerdown', 'keydown', 'touchstart'].forEach(t => window.addEventListener(t, mark, { capture: true, passive: true }));
    window.addEventListener('beforeunload', ev => {
      const active = acted || !!(navigator.userActivation && navigator.userActivation.hasBeenActive);
      if (!active || !App.unsaved()) return undefined;
      ev.preventDefault(); ev.returnValue = 'You have changes that are not saved to a file.'; return ev.returnValue;
    });
    App.load(); App.render();
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
})();

</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

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 Morgan Powers. 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.