← Demos
Web Pages · Demos

Compare My Futures

Compare My Futures helps Kentucky students and young adults select and compare different future options, such as entering the workforce, continuing their education, or starting a business. Users can build and compare multiple 10-year financial projections to understand how each decision could affect their income, taxes, debt, savings, living costs, and personal net worth. The website also helps users identify when one path may financially overtake another and test different scenarios using the W

by Anthony Adduci Nov 18, 2026 15 views 119.5 KB
Sandbox · compare-my-futures · no access to your account
View source — the whole page is this one file
<!-- Copyright (c) 2026 Anthony Adduci. Released under the MIT License. -->
<!--
MIT License

Copyright (c) 2026 Anthony Adduci

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

<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Compare My Futures — Compare Your Financial Paths</title><style>
:root{font-family:Inter,ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;color:#17253a;background:#f5f7fb}*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button{cursor:pointer}header{background:#101f36;color:white;padding:28px max(24px,calc((100vw - 1120px)/2));}header .eyebrow{color:#a6c8f7;font-size:12px;letter-spacing:2px;font-weight:750}h1{font-size:clamp(28px,4vw,42px);margin:8px 0}header p{color:#c6d3e5;max-width:700px;line-height:1.6}.wrap{max-width:1120px;margin:auto;padding:26px 22px 70px}.steps{display:flex;gap:8px;margin:0 0 24px;flex-wrap:wrap}.step{border:1px solid #d9e1ec;background:white;padding:10px 15px;border-radius:10px;color:#5c6980}.step.active{background:#1d5cc5;color:white;border-color:#1d5cc5}.panel{background:white;border:1px solid #e1e7f0;border-radius:18px;padding:24px;margin-bottom:20px;box-shadow:0 5px 25px #1d37500a}h2{font-size:24px;margin:0 0 8px}h3{margin:6px 0 12px;font-size:17px}.muted{color:#637188;line-height:1.55}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:15px}.grid.two{grid-template-columns:repeat(2,minmax(0,1fr))}label{display:block;color:#45536a;font-size:13px;font-weight:650;margin-bottom:5px}input,select{width:100%;padding:11px 12px;border:1px solid #ccd7e5;border-radius:9px;background:#fff;color:#17253a}input:focus,select:focus{outline:2px solid #9bbcf1;border-color:#2864c2}.field{margin-bottom:13px}.hint{font-size:12px;color:#718097;margin-top:5px}.actions{display:flex;gap:10px;flex-wrap:wrap;margin:18px 0}.btn{border:1px solid #cdd8e8;background:white;color:#1c467d;padding:11px 16px;border-radius:10px;font-weight:750}.btn.primary{background:#1759c2;border-color:#1759c2;color:white}.btn.danger{color:#9a2732}.btn:disabled{opacity:.45;cursor:not-allowed}.path{border:1px solid #dce5f0;border-radius:14px;padding:18px;margin:12px 0;background:#fbfcff}.pathhead{display:flex;align-items:center;justify-content:space-between;gap:12px}.pill{background:#e9f1fe;color:#1d59a5;padding:5px 9px;border-radius:99px;font-size:12px;font-weight:750}.notice{border-left:4px solid #dfab45;background:#fff8e9;padding:12px 16px;border-radius:7px;color:#75551d;font-size:13px;line-height:1.5;margin:14px 0}.results-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px}.metric{background:#f7f9fd;border:1px solid #e0e8f4;border-radius:14px;padding:16px}.metric strong{display:block;font-size:24px;margin:8px 0}.metric small{color:#66768c}.chart{width:100%;overflow:auto}svg{max-width:100%;height:auto}.analysis{line-height:1.65;color:#344259}.analysis p{margin:7px 0 16px}.tablewrap{overflow:auto}table{border-collapse:collapse;width:100%;min-width:480px}th,td{text-align:right;padding:11px;border-bottom:1px solid #e3e9f2;font-size:14px}th:first-child,td:first-child{text-align:left}th{color:#637188;font-size:12px}.hide{display:none!important}.divider{height:1px;background:#e3e9f2;margin:20px 0}footer{max-width:1120px;margin:auto;padding:12px 22px 35px;color:#728096;font-size:12px;line-height:1.6}@media(max-width:720px){.grid,.grid.two{grid-template-columns:1fr}.panel{padding:18px}.wrap{padding:20px 13px}header{padding:24px 18px}}

/* Plain-language funding visuals: each bar is the unpaid-expense balance at that year's end. */
.cmf-money-guide{border:1px solid #dce6f0;background:#f8fbff;border-radius:12px;padding:13px;margin:12px 0}
.cmf-money-guide h4{margin:0 0 7px;font-size:1rem}.cmf-money-guide p{margin:5px 0;font-size:.92rem}
.cmf-legend{display:flex;flex-wrap:wrap;gap:8px 16px;font-size:.84rem;color:#42546b;margin:8px 0}
.cmf-key{display:inline-block;width:11px;height:11px;border-radius:3px;margin-right:5px;vertical-align:middle}
.cmf-timeline{display:grid;grid-template-columns:repeat(11,minmax(0,1fr));gap:4px;align-items:end;height:110px;border-bottom:1px solid #c9d5e5;padding-top:12px;margin-top:8px}
.cmf-year-col{height:100%;display:flex;flex-direction:column;justify-content:flex-end;align-items:center;gap:3px;min-width:0}
.cmf-year-bar{width:80%;min-height:0;border-radius:4px 4px 0 0;background:#c8863d}
.cmf-year-col.is-selected .cmf-year-bar{background:#346ca7}
.cmf-year-label{font-size:.67rem;color:#51647b;text-align:center}
.cmf-money-note{font-size:.86rem;color:#40546b;margin-top:10px}
@media(max-width:520px){.cmf-insight-metrics{grid-template-columns:1fr}.cmf-timeline{gap:2px}.cmf-year-label{font-size:.58rem}}
.cmf-story-steps{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin:14px 0}.cmf-story-step{display:flex;flex-direction:column;gap:6px;padding:13px;border:1px solid #d8e2ed;border-radius:12px;background:#fff}.cmf-story-step small{font-weight:650;color:#43536b}.cmf-story-step strong{font-size:1.45rem;color:#233953}.cmf-story-step span:last-child{font-size:.84rem;color:#506078}.cmf-step-num{display:grid;place-items:center;background:#e8eff8;color:#254e7c;border-radius:50%;width:25px;height:25px;font-weight:750}@media(max-width:680px){.cmf-story-steps{grid-template-columns:1fr}}
</style><style id="homepage-style">#cmfHome{min-height:100vh;background:linear-gradient(145deg,#101f36,#203f65);color:white;padding:6vh max(20px,calc((100vw - 1040px)/2));display:flex;align-items:center}#cmfHome .homeInner{width:100%}#cmfHome h1{font-size:clamp(36px,6vw,68px);line-height:1.1;margin:12px 0}#cmfHome p{max-width:750px;line-height:1.65;font-size:18px;color:#e3edf9}#cmfHome .homeCards{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:14px;margin:26px 0}#cmfHome .homeCard{background:#ffffff15;border:1px solid #ffffff38;border-radius:14px;padding:18px}#cmfHome .homeActions{display:flex;gap:12px;flex-wrap:wrap}#cmfHome button{border:0;border-radius:9px;padding:14px 22px;font-weight:700;background:#fff;color:#132744}#cmfHome button.secondary{background:transparent;color:#fff;border:1px solid #ffffff88}#cmfHome .fine{font-size:13px;color:#c9d7e9}#cmfApp{display:none}#cmfApp.active{display:block}#cmfHome.hidden{display:none}#qaBox textarea{width:100%;min-height:75px;padding:12px;border:1px solid #bdc8d9;border-radius:8px}#qaAnswer{margin-top:12px;white-space:pre-wrap;line-height:1.55}#qaBox .qaButtons{display:flex;flex-wrap:wrap;gap:8px;margin:10px 0}#qaBox .qaButtons button{font-size:12px;padding:8px 10px}</style><style>.cmf-details{margin-top:12px;border:1px solid #dbe4ef;border-radius:10px;padding:12px 15px}.cmf-details summary{cursor:pointer;font-weight:650;color:#16375a}.cmf-details[open] summary{margin-bottom:12px}.qaButtons{flex-wrap:wrap}#qaAnswer{white-space:pre-wrap;line-height:1.55}</style><style id="cmf-insight-style">.cmf-insight{border:1px solid #dbe5ef;border-radius:14px;padding:18px;margin:14px 0;background:#fff}.cmf-insight h3{margin:0 0 12px;font-size:1.08rem}.cmf-insight p{line-height:1.55;margin:10px 0}.cmf-insight-metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:12px 0}.cmf-insight-metrics>div{background:#f2f6fb;border-radius:10px;padding:12px;min-width:0}.cmf-insight-metrics small{display:block;color:#52647c;line-height:1.35;margin-bottom:7px}.cmf-insight-metrics strong{display:block;font-size:1.4rem;overflow-wrap:anywhere}.cmf-insight .cmf-details{margin-top:12px}.cmf-overview{background:#eef5fd;border-color:#c8dced}@media(max-width:560px){.cmf-insight-metrics{grid-template-columns:1fr}.cmf-insight{padding:14px}}</style></head><body><section id="cmfHome" aria-label="Welcome to Compare My Futures"><div class="homeInner"><div style="letter-spacing:2px;font-size:13px">EDUCATIONAL FINANCIAL PLANNING</div><h1>Compare My Futures</h1><p>Big decisions shape your future. Compare a career, additional education, or starting a business—and explore how income, debt, and living costs could affect your personal net worth over the next 10 years.</p><div class="homeCards"><div class="homeCard"><strong>1 · Set your starting point</strong><p style="font-size:14px">Enter your own finances. No personal numbers are prefilled.</p></div><div class="homeCard"><strong>2 · Build your futures</strong><p style="font-size:14px">Explore jobs, school, or business in any U.S. city.</p></div><div class="homeCard"><strong>3 · Understand the results</strong><p style="font-size:14px">Compare outcomes and ask the offline results assistant questions.</p></div></div><div class="homeActions"><button onclick="cmfStart(false)">Start a new comparison</button><button id="cmfResume" class="secondary" onclick="cmfStart(true)" style="display:none">Continue saved comparison</button></div><p class="fine">Educational estimates, not financial, tax, or investment advice. Your financial entries stay in your browser unless you export them. No account or API key required. No external services are called. Download a backup to keep your work; browser storage can be cleared.</p></div></section><div id="cmfApp"><header><p style="background:#fff4d6;color:#6b4500;padding:9px;border-radius:8px;font-size:13px">Tax estimates are simplified educational scenarios. States without verified tax rules use a clearly labeled 5% effective state-income-tax planning placeholder, not actual tax law. Local taxes, credits and individual circumstances may change results. Verify assumptions before decisions.</p><div class="eyebrow">KENTUCKY LAUNCH. NATIONWIDE FUTURES.</div><h1>Compare My Futures</h1><p>What would your financial future look like if you chose a different path? Compare jobs, further education, and business goals using the same starting finances.</p></header><main class="wrap"><nav class="steps"><button class="step active" id="tab0" onclick="go(0)">1 · Starting Point</button><button class="step" id="tab1" onclick="go(1)">2 · Your Futures</button><button class="step" id="tab2" onclick="go(2)">3 · Compare Results</button></nav><section id="page0"><div class="panel"><h2>Your Starting Point</h2><p class="muted">Every future starts from where you are today. No finance background needed—best estimates are fine. Your entries stay on this device.</p><div class="grid"><div class="field"><label>State</label><select id="state"><option value="" selected disabled>Select a state</option><option value="AL">AL</option><option value="AK">AK</option><option value="AZ">AZ</option><option value="AR">AR</option><option value="CA">CA</option><option value="CO">CO</option><option value="CT">CT</option><option value="DE">DE</option><option value="FL">FL</option><option value="GA">GA</option><option value="HI">HI</option><option value="ID">ID</option><option value="IL">IL</option><option value="IN">IN</option><option value="IA">IA</option><option value="KS">KS</option><option value="KY">KY</option><option value="LA">LA</option><option value="ME">ME</option><option value="MD">MD</option><option value="MA">MA</option><option value="MI">MI</option><option value="MN">MN</option><option value="MS">MS</option><option value="MO">MO</option><option value="MT">MT</option><option value="NE">NE</option><option value="NV">NV</option><option value="NH">NH</option><option value="NJ">NJ</option><option value="NM">NM</option><option value="NY">NY</option><option value="NC">NC</option><option value="ND">ND</option><option value="OH">OH</option><option value="OK">OK</option><option value="OR">OR</option><option value="PA">PA</option><option value="RI">RI</option><option value="SC">SC</option><option value="SD">SD</option><option value="TN">TN</option><option value="TX">TX</option><option value="UT">UT</option><option value="VT">VT</option><option value="VA">VA</option><option value="WA">WA</option><option value="WV">WV</option><option value="WI">WI</option><option value="WY">WY</option><option value="DC">DC</option></select><div class="hint">Select any state. Recognizes approximately 200 cities for entry suggestions; unverified states use a clearly labeled 5% state-income-tax placeholder rather than actual tax rules. City recognition is not tax or housing coverage.</div></div><div class="field"><label>Current city</label><select id="city" aria-label="Current city"></select><div class="hint">Choose your state first, then a city. Use “Other city” if it is not listed.</div><input id="cityOther" class="hide" placeholder="Enter city name" aria-label="Other current city"></div><div class="field"><label>Tax filing status</label><select id="filing"><option value="single">Single</option><option value="mfj">Married filing jointly</option><option value="mfs">Married filing separately</option><option value="hoh">Head of household</option></select><div class="hint">How you file your federal income taxes. If you are unmarried and file on your own, choose Single. We use this to estimate taxes.</div></div><div class="field"><label>Current annual income ($)</label><input id="currentIncome" type="number" min="0" value=""><div class="hint">Your yearly pay before taxes or other deductions. An estimate is fine.</div></div><div class="field"><label>Cash / savings ($)</label><input id="cash" type="number" min="0" value=""><div class="hint">Money in checking, savings, and emergency-fund accounts.</div></div><div class="field"><label>Investments ($)</label><input id="investments" type="number" min="0" value=""><div class="hint">Stocks, ETFs, mutual funds, or brokerage accounts. Do not count retirement accounts twice.</div></div><div class="field"><label>Retirement accounts ($)</label><input id="retirement" type="number" min="0" value=""><div class="hint">Money already saved in a 401(k), 403(b), IRA, or Roth IRA.</div></div><div class="field"><label>Existing debt ($)</label><input id="debt" type="number" min="0" value=""><div class="hint">The total amount you still owe on loans and credit cards. This is a liability, not a monthly bill. <strong>If you have no debt, enter $0.</strong></div><button type="button" class="btn" id="noDebtBtn" onclick="setNoDebt()" style="margin-top:8px;padding:8px 12px;font-size:12px">I have no debt — set debt fields to $0</button><div class="hint" id="noDebtStatus" role="status"></div></div><div class="field"><label>Average debt APR (%)</label><input id="debtApr" type="number" min="0" max="100" step=".1" value=""><div class="hint">APR means annual interest rate. If you have multiple debts, enter a rough average for now. If you have no debt, use 0%.</div></div><div class="field"><label>Required monthly debt payment ($)</label><input id="debtMin" type="number" min="0" value=""><div class="hint">The minimum total you must pay each month toward your existing debt. If you have no debt, enter $0.</div></div><div class="field" id="debtStrategyBox"><label>Extra debt repayment strategy</label><select id="debtStrategy"><option value=".25">Conservative · 25% of surplus</option><option value=".5" selected>Moderate · 50% of surplus</option><option value=".75">Aggressive · 75% of surplus</option><option value="custom">Custom</option></select><div class="hint">After living expenses and required debt payments, what share of your extra money should pay down debt faster?</div></div><div class="field" id="customDebtBox" style="display:none"><label>Custom extra debt share (%)</label><input id="customDebt" type="number" min="0" max="100" value="50"></div><div class="field"><label>New savings allocation</label><select id="allocation"><option value=".2">Mostly cash · 3.3% blended planning return</option><option value=".5" selected>Mix · 4.7% blended planning return</option><option value=".8">Mostly investments · 5.5% blended planning return</option></select><div class="hint">Where to put money left after expenses and debt payments. Returns are illustrative, not guaranteed.</div></div></div><div class="notice">Planning assumptions are not guaranteed returns. Tax calculations are illustrative, especially where state tax data are unverified; individual tax credits and comprehensive loan-specific repayment rules are excluded.</div><div class="actions"><button class="btn primary" onclick="go(1)">Build My Futures →</button></div>
<div class="notice"><strong>Continue a previous comparison?</strong> Open a previously downloaded comparison to restore your Starting Point and future paths. You will be asked before replacing anything.<div class="actions"><button type="button" class="btn" onclick="chooseImport('comparison')">Open a Saved Comparison</button><button type="button" class="btn" onclick="exportData()">Download My Comparison</button></div><span id="importStatus" role="status" class="hint"></span></div></div></section><section id="page1" class="hide"><div class="panel"><h2>Build Your Futures</h2><p class="muted">Add 2–5 futures. Compare multiple jobs, businesses, or education paths. Every path starts from the same financial position. Each input has a short explanation underneath—estimates are okay.</p><div class="actions"><button class="btn" onclick="addPath('job')">+ Job</button><button class="btn" onclick="addPath('school')">+ Education</button><button class="btn" onclick="addPath('business')">+ Business</button></div><div id="paths"></div><div id="taxCoverageNotice" class="notice hide" role="status"></div>
<div class="panel" style="background:#f7faff;margin-top:22px"><h3>Save Your Progress</h3><p class="muted">Keep your futures for later. Save an entire comparison, or download a single pathway from its card above.</p>
<div class="actions"><button type="button" class="btn" onclick="exportData()">Download My Comparison</button><button type="button" class="btn" onclick="chooseImport('comparison')">Open a Saved Comparison</button><button type="button" class="btn" onclick="chooseImport('pathway')">Add a Saved Pathway</button></div>
<p class="hint">Opening a full comparison replaces your current Starting Point and pathways after confirmation. Adding one pathway keeps everything you already entered. Files stay on your device.</p><div id="saveStatus" role="status" class="hint"></div><div id="autosaveStatus" role="status" class="hint">Automatic saving is ready. Your progress stays in this browser; download a copy for backup.</div></div><div class="actions"><button class="btn primary" onclick="go(2)">Compare My Futures →</button></div></div></section><section id="page2" class="hide"><div class="panel"><h2>Futures at a Glance</h2><p class="muted">Compare modeled personal net worth: cash + investments + retirement − debt − unfunded shortfalls. Business results are conditional goal scenarios, not forecasts.</p><div class="actions"><label style="align-self:center">Compare year</label><select id="horizon" style="width:130px" onchange="renderResults()"><option value="1">Year 1</option><option value="5" selected>Year 5</option><option value="10">Year 10</option></select><select id="scenario" style="width:180px" onchange="scenarioChanged()"><option value="base">Base scenario</option><option value="lower">Lower outcome</option><option value="higher">Higher outcome</option></select></div><p id="scenarioLabel" class="hint" role="status">Viewing: Base scenario</p><div id="cards" class="results-grid"></div><div class="notice">Educational-use only. Not personalized financial, tax, or investment advice. No specific securities are recommended. Kentucky, Illinois, limited Ohio/Michigan, and Tennessee earned-income state-only tax calculations are supported. City income taxes, other credits and complex situations are not modeled; location cost estimates may be broader regional benchmarks. Results depend on your inputs and assumptions.</div></div><div class="panel"><h2>How Your Futures Develop</h2><div class="chart" id="chart"></div><p class="hint">Business lines show a conditional goal trajectory, not an expected outcome.</p><h3 style="margin:18px 0 8px;font-size:1rem">Year-by-year comparison</h3><p class="hint">Exact modeled personal net worth behind the chart, Years 0–10.</p><div id="yearTable" class="tablewrap"></div></div><div class="panel"><h2>What Your Results Are Telling You</h2><div id="analysis" class="analysis"></div></div><div class="panel" id="bizPanel"><h2>Business Financial Deep Dive</h2><p class="muted">Explore the business outcomes required to meet your personal financial goals. These are mathematical requirements, not predictions.</p><details class="cmf-details"><summary>Explore revenue goals, reinvestment and business levers</summary><div id="bizAnalysis" class="analysis"></div></details></div><div class="panel" id="qaBox"><h2>Explore Your Futures · What-If Simulator</h2><p class="muted">Choose a question and the pathways to compare. No typing or exact wording needed. Calculations run offline and never change your saved pathways.</p><div class="cmf-insight" style="margin:12px 0"><label for="cmfMode">What would you like to explore?</label><select id="cmfMode" onchange="cmfConfigureExplorer()" style="width:100%;max-width:650px"><option value="ranking">Rank all pathways by net worth</option><option value="crossovers">Find crossovers between pathways</option><option value="leaders">See which pathway leads each year</option><option value="funding">Find funding gaps and missed payments</option><option value="debt">Compare loans and unpaid expenses</option><option value="cashflow">Compare income, taxes and living costs</option><option value="salaryTarget">What salary would it take to match another pathway?</option><option value="tuitionTarget">What tuition would it take to match another pathway?</option><option value="revenueTarget">What business revenue would it take to match another pathway?</option><option value="change">What happens if I change an assumption?</option></select><div id="cmfExplorerFields" class="actions" style="align-items:end;gap:12px;flex-wrap:wrap;margin-top:12px"><div id="cmfSubjectWrap"><label for="cmfSubject">Pathway to explore</label><select id="cmfSubject" style="min-width:170px"></select></div><div id="cmfReferenceWrap"><label for="cmfReference">Compare against</label><select id="cmfReference" style="min-width:170px"></select></div><div id="cmfYearWrap"><label for="cmfYear">Comparison year</label><select id="cmfYear"><option value="1">Year 1</option><option value="5">Year 5</option><option value="10" selected>Year 10</option></select></div><div id="cmfChangeWrap" style="display:none"><label for="cmfField">Change</label><select id="cmfField" onchange="cmfConfigureExplorer()"><option value="housing">Monthly housing</option><option value="other">Other monthly living costs</option><option value="health">Monthly healthcare</option><option value="salary">Annual salary</option><option value="tuition">Annual tuition</option><option value="startup">Startup investment</option><option value="margin">Business operating margin (percentage points)</option><option value="reinvest">Business reinvestment (percentage points)</option></select></div><div id="cmfAmountWrap" style="display:none"><label for="cmfAmount">Amount of change</label><input type="number" id="cmfAmount" value="300" min="1" step="any" style="width:125px"></div><div id="cmfDirectionWrap" style="display:none"><label for="cmfDirection">Direction</label><select id="cmfDirection"><option value="increase">Increase</option><option value="decrease">Decrease</option></select></div></div><div class="actions"><button class="btn primary" onclick="cmfRunExplorer()">Show my results</button></div></div><input type="hidden" id="cmfQuestion" value=""><div id="qaAnswer" role="status" aria-live="polite" class="notice" style="white-space:pre-line">Select an exploration above, then choose “Show my results.”</div></div><div class="panel"><details class="cmf-details"><summary><strong>How We Calculate Your Future · Data & Sources</strong></summary><p class="muted">Net worth = modeled personal cash + investments + retirement − outstanding debt − unfunded shortfalls. Annual pay is taxed using simplified federal/state rules, living costs grow with assumed inflation, and monthly surplus pays debt then builds savings. Business trajectories are conditional goals, never predicted company growth.</p><p class="muted"><strong>Verified inputs actually embedded:</strong> HUD FY2026 one-bedroom Fair Market Rents for Lexington-Fayette KY MSA and Chicago-Joliet-Naperville IL HMFA; USDA September 2026 Moderate-Cost Food Plan (national); BLS 2023–24 Consumer Expenditure Survey (South region or Chicago metro). BLS numbers are per consumer unit, not per individual: the conversion divides by mean people per unit and is a rough planning proxy. $250 per month for other essentials is an unsourced planning allowance. These are not precise city-specific averages. Healthcare includes premiums and out-of-pocket expenses once only.</p><p class="muted"><a href="https://www.huduser.gov/portal/datasets/fmr/fmr2026/FY2026_FMR_Schedule.pdf" target="_blank" rel="noopener">HUD FY2026</a> · <a href="https://www.fns.usda.gov/cnpp/usda-food-plans-cost-food-monthly-reports" target="_blank" rel="noopener">USDA Sep 2026</a> · <a href="https://www.bls.gov/regions/midwest/data/consumerexpenditures_selectedareas_table.htm" target="_blank" rel="noopener">BLS 2023–24</a>. Tax and return assumptions remain subject to validation. Only Lexington and Chicago have source-backed local cost observations; other cities use editable illustrative planning tiers, not measured city data.</p></div></details></div><div class="panel"><details class="cmf-details"><summary><strong>Assumptions & Confidence</strong></summary><p class="muted">Salary growth: 3% base, ±1 percentage point. Living-cost inflation: 2.3% base, lower outcome 3.3%, higher outcome 1.3%. Investment returns: 5.5% base, ±2 percentage points; cash 3.3%. For single Kentucky residents, the 2026 one-person Family Size Tax Credit is approximated using the full and partial statutory credit bands, with later-year thresholds escalated illustratively. Modified gross income is approximated using modeled earnings and self-employment adjustments; household income additions, other family sizes, and other credits are not modeled. Actual eligibility and taxes may differ. Taxes use simplified 2026 federal, Kentucky, Illinois, and limited Ohio state-only parameters; future years are projections, not published tax rates. Business taxes assume an active self-employed owner eligible for the QBI deduction. If business income is too high for the simplified calculation, results pause rather than guessing. Future-year tax brackets and deductions are illustrative projections; the $400 minimum QBI deduction is only modeled for 2026, not guessed for later years. Actual taxes may differ. Debt interest and payments use monthly timing; income and tax are estimated annually and spread evenly across months. New tuition and startup cash expenses are assumed due at the start of their year. Unfunded living or tuition expenses are hypothetical unpaid liabilities, not a financing source; the model does not verify whether those expenses could actually remain unpaid. Unpaid required loan payments stay in the loan balance and may continue accruing interest; missed payments are tracked separately. Shortfalls for ordinary expenses are tracked as unfunded liabilities without assumed interest; future positive monthly cash flow repays those shortfalls after required loan payments and before optional extra loan payments.</p><p class="muted">Lexington and Chicago cost estimates are embedded from HUD FY2026, USDA September 2026 and BLS 2023–24 observations, with labeled conversion assumptions and user overrides. Other locations receive editable illustrative starting scenarios, not verified local cost data. City-specific income taxes are not included for Ohio or Michigan (including Detroit), and are not automatically verified elsewhere. No business sale value is included. School loan repayment is modeled over 10 years after graduation; startup loans over 5 years. These are planning assumptions, not lender-specific schedules.</p></details><div class="actions"><button class="btn" onclick="go(1)">← Edit futures</button><button class="btn" onclick="exportData()">Download My Comparison</button><button class="btn" onclick="chooseImport('comparison')">Open a Saved Comparison</button><input id="importFile" type="file" accept=".json,application/json" style="position:absolute;left:-9999px;width:1px;height:1px" onchange="importSelectedFile(this)"></div></div></section></main><datalist id="city-suggestions"></datalist><footer>Compare My Futures · Kentucky PFM Challenge · Educational planning prototype · Submission candidate · All calculations run in your browser. No personal financial data is transmitted. © 2026 Anthony Adduci · Released under the MIT License. Based on original work by Anthony Adduci with AI-assisted development.</footer><script>
'use strict';const $=id=>document.getElementById(id);const money=n=>(n<0?'−':'')+'$'+Math.abs(n).toLocaleString('en-US',{maximumFractionDigits:0});const num=(id,def=0)=>{let n=Number($(id)?.value);return Number.isFinite(n)?n:def};const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));let paths=[],nextId=1,dirty=false;// V1.7: Federal rules maintained in one versioned, auditable configuration.
// Projection multiplier preserves the V1.6.16 baseline; it is not a published future tax schedule.
const FEDERAL_TAX_RULES=Object.freeze({
 taxYear:2026, projectionGrowth:0.023,
 brackets:Object.freeze({single:[12400,50400,105700,201775,256225,640600],mfj:[24800,100800,211400,403550,512450,768700],mfs:[12400,50400,105700,201775,256225,384350],hoh:[17700,67450,105700,201750,256200,640600]}),
 standardDeduction:Object.freeze({single:16100,mfj:32200,mfs:16100,hoh:24150}),
 rates:Object.freeze([.10,.12,.22,.24,.32,.35,.37]),
 socialSecurityWageBase:184500, employeeSSRate:.062,employeeMedicareRate:.0145,
 selfEmploymentBaseFactor:.9235,selfEmploymentSSRate:.124,selfEmploymentMedicareRate:.029,
 additionalMedicareRate:.009,
 additionalMedicareThreshold:Object.freeze({single:200000,mfj:250000,mfs:125000,hoh:200000}),
 qbi:Object.freeze({rate:.2,minimum2026:400,minimum2027:415,minimumIncome2026:1000,minimumIncome2027:1030,
  threshold2026:Object.freeze({single:201750,mfj:403500,mfs:201775,hoh:201750}),
  threshold2027:Object.freeze({single:208300,mfj:416600,mfs:208325,hoh:208300})})
});
const TAX=FEDERAL_TAX_RULES.brackets,STD=FEDERAL_TAX_RULES.standardDeduction,RATES=FEDERAL_TAX_RULES.rates;
function prog(amount,filing,y){let a=Math.max(0,amount),prev=0,t=0,b=TAX[filing].map(v=>(v*Math.pow(1+FEDERAL_TAX_RULES.projectionGrowth,y-1)));for(let i=0;i<7;i++){let hi=b[i]??Infinity,portion=Math.max(0,Math.min(a,hi)-prev);t+=portion*RATES[i];if(a<=hi)break;prev=hi}return t}
// V1.6.16 controlled tax candidate. 2026 parameters; later years are projections.
// V1.7 foundation: centrally maintained state tax policy table. Only reviewed states are enabled.
// The 2026 parameters below preserve the locked V1.6.16 calculations exactly.
// Annual projection index and simplified household assumptions remain unchanged.
const STATE_TAX_RULES=Object.freeze({
 KY:Object.freeze({name:'Kentucky',taxYear:2026,incomeBasis:'agi',standardDeduction2026:3360,rate2026:.035,familySizeCredit:'KY_SINGLE_2026',reviewStatus:'baseline-reviewed'}),
 IL:Object.freeze({name:'Illinois',taxYear:2026,incomeBasis:'gross',standardDeduction2026:2925,rate2026:.0495,familySizeCredit:null,reviewStatus:'baseline-reviewed'}),
 OH:Object.freeze({name:'Ohio',taxYear:2026,incomeBasis:'ohio_nonbusiness',reviewStatus:'OH_2026_STATE_ONLY_SINGLE_LOCKED_SCOPE',exemptions:[2400,2150,1900],threshold:26050,baseTax:332,rate:.0275}),
 MI:Object.freeze({name:'Michigan',taxYear:2026,incomeBasis:'agi',reviewStatus:'MI_2026_STATE_ONLY_SINGLE_LOCKED_SCOPE',personalExemption2026:5900,rate2026:.0425}),
 TN:Object.freeze({name:'Tennessee',taxYear:2026,incomeBasis:'none',reviewStatus:'TN_2026_EARNED_INCOME_STAGE1',rate2026:0}),
 IN:Object.freeze({name:'Indiana',taxYear:2026,incomeBasis:'agi',reviewStatus:'IN_2026_WAGES_PRELIMINARY_COUNTY_EXCLUDED',rate2026:.0295,personalExemption2026:1000}),
 PA:Object.freeze({name:'Pennsylvania',taxYear:2026,incomeBasis:'gross',reviewStatus:'PA_2026_WAGES_PRELIMINARY_LOCAL_EXCLUDED',rate2026:.0307})
});
const STATE_TAX_COVERAGE=Object.freeze(Object.keys(STATE_TAX_RULES));
function tax(gross,state,filing,y,business=false){
 if(!Object.prototype.hasOwnProperty.call(STATE_TAX_RULES,state) && !SUPPORTED_CITY_NAMES[state])throw new Error("UNSUPPORTED_STATE_TAX");
 if(!Object.prototype.hasOwnProperty.call(STD,filing))throw new Error("UNSUPPORTED_FILING_STATUS");
 if(!Number.isFinite(gross)||gross<0||!Number.isInteger(y)||y<1||y>10)throw new Error("INVALID_TAX_INPUT");
 const idx=Math.pow(1+FEDERAL_TAX_RULES.projectionGrowth,y-1),g=Math.max(0,gross);
 const ssCap=FEDERAL_TAX_RULES.socialSecurityWageBase*idx;
 const addThreshold=FEDERAL_TAX_RULES.additionalMedicareThreshold[filing];
 let payroll=0,halfSE=0;
 if(business){
  const seBase=g*FEDERAL_TAX_RULES.selfEmploymentBaseFactor;
  const regular=Math.min(seBase,ssCap)*FEDERAL_TAX_RULES.selfEmploymentSSRate+seBase*FEDERAL_TAX_RULES.selfEmploymentMedicareRate;
  payroll=regular+Math.max(0,seBase-addThreshold)*FEDERAL_TAX_RULES.additionalMedicareRate;
  halfSE=regular/2;
 }else{
  payroll=Math.min(g,ssCap)*FEDERAL_TAX_RULES.employeeSSRate+g*FEDERAL_TAX_RULES.employeeMedicareRate+Math.max(0,g-addThreshold)*FEDERAL_TAX_RULES.additionalMedicareRate;
 }
 const agi=g-halfSE;
 const taxableBeforeQBI=Math.max(0,agi-STD[filing]*idx);
 let qbi=0;
 if(business){
  const qualifyingIncome=Math.max(0,g-halfSE);
  const normalQBI=Math.min(FEDERAL_TAX_RULES.qbi.rate*qualifyingIncome,FEDERAL_TAX_RULES.qbi.rate*taxableBeforeQBI);
  // Use published 2026 and 2027 active-owner minimums; later-year minimums are omitted pending verified guidance.
  const minimum=y===1&&qualifyingIncome>=FEDERAL_TAX_RULES.qbi.minimumIncome2026?FEDERAL_TAX_RULES.qbi.minimum2026:y===2&&qualifyingIncome>=FEDERAL_TAX_RULES.qbi.minimumIncome2027?FEDERAL_TAX_RULES.qbi.minimum2027:0;
  const threshold=y===2?(FEDERAL_TAX_RULES.qbi.threshold2027[filing]):FEDERAL_TAX_RULES.qbi.threshold2026[filing]*idx;
  // High-income QBI wage/property/SSTB rules require inputs not yet collected.
  // Do not invent a high-income deduction: this requires wages, property and business-type information.
  if(taxableBeforeQBI>threshold)throw new Error('HIGH_INCOME_QBI_DETAILS');
  qbi=Math.max(normalQBI,minimum);
 }
 const federal=prog(Math.max(0,taxableBeforeQBI-qbi),filing,y);
 const rule=STATE_TAX_RULES[state] || null;
 if(state==='OH' && filing!=='single')throw new Error('OH_SINGLE_ONLY');
 if(state==='MI' && filing!=='single')throw new Error('MI_SINGLE_ONLY');
 if((state==='IN'||state==='PA') && business)throw new Error('STATE_BUSINESS_TAX_UNSUPPORTED');
 if((state==='IN'||state==='PA') && filing!=='single')throw new Error('STATE_SINGLE_ONLY');
 if(state==='OH' && business && g>250000)throw new Error('OH_COMPLEX_BUSINESS_INCOME');
 const stateIncome=rule ? (rule.incomeBasis==='agi'?agi:g) : agi;
 let stateTax;
 if(state==='OH'){
  // 2026 OH state-only estimate: single filer, resident, no dependents, modeled wages OR
  // qualifying sole-proprietor income; excludes municipal, school district, other adjustments.
  // Later years hold 2026 OH parameters fixed (scenario assumption, not enacted future law).
  // Only full-year OH residents with all wages or all qualifying sole-proprietor
  // income are modeled; mixed income, local taxes, school district, EITC,
  // other credits and adjustments require additional information.
  const ohioMAGI=agi; // Approximation; assumes no other OH additions or deductions.
  const exemption=ohioMAGI>=500000?0:ohioMAGI<=40000?2400:ohioMAGI<=80000?2150:1900;
  // For the modeled sole proprietor, the Ohio business-income deduction is
  // limited to qualifying business income INCLUDED in federal AGI. The
  // deductible half of SE tax has already reduced federal AGI above.
  const qualifyingBusinessAGI=business?Math.max(0,agi):0;
  const businessDeduction=business?Math.min(qualifyingBusinessAGI,250000):0;
  const taxableBusiness=business?Math.max(0,qualifyingBusinessAGI-businessDeduction):0;
  const ohioAdjusted=Math.max(0,ohioMAGI-businessDeduction);
  const nonBusinessBase=Math.max(0,ohioAdjusted-exemption-taxableBusiness);
  const unusedExemption=Math.max(0,exemption-(ohioAdjusted-taxableBusiness));
  const businessBase=Math.max(0,taxableBusiness-unusedExemption);
  stateTax=(nonBusinessBase<=26050?0:332+.0275*(nonBusinessBase-26050))+.03*businessBase;
  // R.C. 5747.022: one $20 exemption credit when OH MAGI less exemptions < $30,000.
  if(ohioMAGI-exemption<30000)stateTax=Math.max(0,stateTax-20);
 }else if(state==='TN'){
  // Tennessee imposes no individual income tax on earned wages or active proprietor earnings.
  // Federal income and employment taxes remain; entity-level franchise/excise taxes are outside scope.
  stateTax=0;
 }else if(state==='IN'){
  // Indiana 2026 state-level wages only. County income tax and dependent exemptions excluded.
  // 2026 parameters held constant for projections, not a forecast of enacted future law.
  stateTax=Math.max(0,agi-rule.personalExemption2026)*rule.rate2026;
 }else if(state==='PA'){
  // Pennsylvania 2026 state wages only; no federal-style standard deduction.
  // Local earned-income taxes and income-class deductions excluded.
  stateTax=g*rule.rate2026;
 }else if(state==='MI'){
  // Michigan full-year single resident, wages or uncomplicated active sole proprietor.
  // Federal AGI includes deductible half of SE tax; federal QBI deduction does not reduce MI AGI.
  // Hold 2026 personal exemption and rate constant in future projection years; NOT enacted rates.
  // Excludes city taxes, state EITC, homestead credit, retirement subtractions,
  // MI-specific IRC decoupling adjustments (depreciation, section 179, R&D, interest),
  // flow-through entity tax credits, other state adjustments and nonresident allocation.
  stateTax=Math.max(0,agi-rule.personalExemption2026)*rule.rate2026;
 }else if(!rule){
  // Transparent scenario-only placeholder, NOT a claim about this state's actual income-tax law.
  // Users should verify local and state taxes before relying on a comparison.
  stateTax=Math.max(0,agi)*0.05;
 }else stateTax=Math.max(0,stateIncome-rule.standardDeduction2026*idx)*rule.rate2026;
 // Kentucky's family-size credit fully offsets KY individual income tax at or below
 // the family-size-one poverty threshold. This is a conservative minimum-family-size
 // assumption for a single full-year KY resident with only modeled earnings.
 // Later-year thresholds are illustrative 2.3% escalations, not published figures.
 if(rule && rule.familySizeCredit==='KY_SINGLE_2026' && filing==='single'){
  // 2026 one-person Family Size Tax Credit. MGI is approximated by modeled AGI;
  // other household income and statutory MGI additions are not collected.
  const threshold=15960*idx;
  const ratio=agi/threshold;
  let creditPct=0;
  if(ratio<=1)creditPct=1;
  else if(ratio<=1.32){
    // KRS 141.066: >100–104% => 90%, ... >128–132% => 20%;
    // >132–133% => 10%. Boundary values follow the statutory intervals.
    const band=Math.ceil((ratio-1)/.04);
    creditPct=Math.max(.2,1-.1*band);
  }else if(ratio<1.33)creditPct=.1;
  stateTax*=1-creditPct;
 }
 return federal+stateTax+payroll;
}
function initial(){let d=$('debtStrategy').value;return {cash:num('cash'),invest:num('investments'),ret:num('retirement'),debt:num('debt'),apr:num('debtApr')/100,min:num('debtMin')*12,filing:$('filing').value,share:d==='custom'?num('customDebt')/100:Number(d),alloc:num('allocation'),state:$('state').value}}const SUPPORTED_CITY_NAMES={"AL":["Birmingham","Montgomery","Huntsville","Mobile","Tuscaloosa"],"AK":["Anchorage","Fairbanks","Juneau"],"AZ":["Phoenix","Tucson","Mesa","Scottsdale","Tempe","Chandler","Glendale"],"AR":["Little Rock","Fayetteville","Fort Smith","Bentonville"],"CA":["Los Angeles","San Diego","San Jose","San Francisco","Sacramento","Fresno","Oakland","Long Beach","Irvine","Bakersfield","Riverside","Stockton","Santa Barbara","Palo Alto"],"CO":["Denver","Colorado Springs","Aurora","Fort Collins","Boulder"],"CT":["Bridgeport","New Haven","Hartford","Stamford","Waterbury"],"DE":["Wilmington","Dover","Newark"],"FL":["Jacksonville","Miami","Tampa","Orlando","St. Petersburg","Tallahassee","Fort Lauderdale","Gainesville","West Palm Beach"],"GA":["Atlanta","Augusta","Columbus","Savannah"],"HI":["Honolulu","Hilo","Kailua"],"ID":["Boise","Meridian","Idaho Falls"],"IL":["Chicago","Aurora","Naperville","Rockford","Springfield"],"IN":["Indianapolis","Fort Wayne","Evansville"],"IA":["Des Moines","Cedar Rapids","Davenport"],"KS":["Wichita","Overland Park","Kansas City"],"KY":["Lexington","Louisville","Bowling Green","Owensboro","Frankfort","Richmond","Paducah","Florence"],"LA":["New Orleans","Baton Rouge","Shreveport"],"ME":["Portland","Lewiston","Bangor"],"MD":["Baltimore","Frederick","Rockville"],"MA":["Boston","Worcester","Springfield","Cambridge"],"MI":["Detroit","Grand Rapids","Ann Arbor","Lansing"],"MN":["Minneapolis","St. Paul","Rochester"],"MS":["Jackson","Gulfport","Hattiesburg"],"MO":["Kansas City","St. Louis","Springfield"],"MT":["Billings","Missoula","Bozeman"],"NE":["Omaha","Lincoln","Bellevue"],"NV":["Las Vegas","Henderson","Reno"],"NH":["Manchester","Nashua","Concord"],"NJ":["Newark","Jersey City","Paterson"],"NM":["Albuquerque","Santa Fe","Las Cruces"],"NY":["New York","Buffalo","Rochester","Yonkers","Syracuse"],"NC":["Charlotte","Raleigh","Greensboro","Durham"],"ND":["Fargo","Bismarck","Grand Forks"],"OH":["Columbus","Cleveland","Cincinnati","Toledo","Akron"],"OK":["Oklahoma City","Tulsa","Norman"],"OR":["Portland","Eugene","Salem"],"PA":["Philadelphia","Pittsburgh","Allentown","Erie"],"RI":["Providence","Warwick","Cranston"],"SC":["Charleston","Columbia","Greenville"],"SD":["Sioux Falls","Rapid City","Brookings"],"TN":["Nashville","Memphis","Knoxville","Chattanooga"],"TX":["Houston","San Antonio","Dallas","Austin","Fort Worth"],"UT":["Salt Lake City","West Valley City","Provo"],"VT":["Burlington","South Burlington","Montpelier"],"VA":["Virginia Beach","Norfolk","Richmond","Arlington"],"WA":["Seattle","Spokane","Tacoma","Bellevue"],"WV":["Charleston","Huntington","Morgantown"],"WI":["Milwaukee","Madison","Green Bay"],"WY":["Cheyenne","Casper","Laramie"],"DC":["Washington"]};
function cityRegistryStatus(city,state){const names=SUPPORTED_CITY_NAMES[state]||[];const found=names.find(n=>n.toLowerCase()===String(city||'').trim().toLowerCase());return found?`<strong>${esc(found)}, ${esc(state)}</strong> is in our 200-city recognition list. This does not mean housing and tax data have been verified yet.`:`<strong>${esc(city)}, ${esc(state)}</strong> is outside the initial city list. You can still enter it manually, but local estimates are unavailable.`;}
const COST_SOURCES={hud:'https://www.huduser.gov/portal/datasets/fmr/fmr2026/FY2026_FMR_Schedule.pdf',usda:'https://www.fns.usda.gov/cnpp/usda-food-plans-cost-food-monthly-reports',bls:'https://www.bls.gov/regions/midwest/data/consumerexpenditures_selectedareas_table.htm'};
// Embedded verified public observations, plus explicitly labeled single-adult planning conversions.
const COST_AREAS={
 'lexington|KY':{label:'Lexington-Fayette, KY metropolitan area',rent:1079,region:'South',transport:12532,health:5765,people:2.5},
 'chicago|IL':{label:'Chicago-Joliet-Naperville, IL HUD area',rent:1581,region:'Chicago metro',transport:12941,health:7114,people:2.4}
};
// Nationwide scenario starting points: explicitly illustrative tiers, NOT measured city rents.
// Verified metro observations remain limited to COST_AREAS above.
const COST_TIER_OVERRIDES=Object.freeze({
 'new york|NY':3,'san francisco|CA':3,'san jose|CA':3,'palo alto|CA':3,'boston|MA':3,'cambridge|MA':3,
 'seattle|WA':3,'bellevue|WA':3,'santa barbara|CA':3,'los angeles|CA':3,'san diego|CA':3,
 'miami|FL':2,'fort lauderdale|FL':2,'west palm beach|FL':2,'washington|DC':3,'arlington|VA':3,
 'denver|CO':2,'boulder|CO':3,'aurora|CO':2,'austin|TX':2,'dallas|TX':2,'portland|OR':2,
 'oakland|CA':3,'irvine|CA':3,'sacramento|CA':2,'long beach|CA':2,'riverside|CA':2,
 'nashville|TN':2,'charlotte|NC':2,'raleigh|NC':2,'tampa|FL':2,'orlando|FL':2,
 'jersey city|NJ':3,'newark|NJ':2,'stamford|CT':3,'honolulu|HI':3,
 'columbus|OH':1,'toledo|OH':0,'cleveland|OH':0,'cincinnati|OH':1,'akron|OH':0,
 'louisville|KY':1,'bowling green|KY':0,'frankfort|KY':0,'richmond|KY':0,
 'detroit|MI':0,'grand rapids|MI':1,'ann arbor|MI':2,'indianapolis|IN':1,
 'philadelphia|PA':2,'pittsburgh|PA':1,'minneapolis|MN':2,'madison|WI':1,
 'atlanta|GA':2,'houston|TX':1,'san antonio|TX':1,'phoenix|AZ':2,
 'las vegas|NV':2,'salt lake city|UT':2,'boise|ID':2
});
const COST_TIER_MONTHLY=Object.freeze([
 {name:'lower-cost scenario',housing:950,other:900,health:250},
 {name:'middle-cost scenario',housing:1200,other:1000,health:250},
 {name:'higher-cost scenario',housing:1700,other:1150,health:275},
 {name:'very-high-cost scenario',housing:2400,other:1350,health:300}
]);
function locationEstimate(p){
 const key=String(p.city||'').trim().toLowerCase()+'|'+p.state;
 const a=COST_AREAS[key];
 if(!a){
  const known=(SUPPORTED_CITY_NAMES[p.state]||[]).some(c=>c.toLowerCase()===String(p.city||'').trim().toLowerCase());
  const tier=Object.prototype.hasOwnProperty.call(COST_TIER_OVERRIDES,key)?COST_TIER_OVERRIDES[key]:1;
  const t=COST_TIER_MONTHLY[tier];
  return {area:{label:known?'Illustrative city-tier planning scenario':'National fallback planning scenario',estimated:true},housing:t.housing,other:t.other,health:t.health,estimated:true,tier:t.name,recognized:known};
 }
 let food=Math.round(((336.4+398.4)/2)*1.2);
 let transport=Math.round(a.transport/12/a.people),health=Math.round(a.health/12/a.people);
 let essentials=250;
 return {area:a,housing:a.rent,other:food+transport+essentials,health,food,transport,essentials,estimated:false};
}
function costDisclosure(p){
 const e=locationEstimate(p),custom=p.costCustom||{};
 if(e.estimated)return `<div class="notice"><strong>Illustrative planning scenario — NOT verified city data.</strong> ${esc(p.city)}, ${esc(p.state)}: ${esc(e.tier)}. Starting suggestions: housing ${money(e.housing)}/month, other living expenses ${money(e.other)}/month, healthcare ${money(e.health)}/month. ${e.recognized?'This city is recognized, but its actual local costs have not been verified.':'This city is not in the recognition list; national fallback assumptions apply.'} <strong>These are scenario assumptions, not observed local prices or averages.</strong> Edit all amounts to match your circumstances. ${Object.values(custom).some(Boolean)?'Your customized amounts are preserved.':''} State and local tax coverage is separate and may be incomplete.</div>`;
 return `<div class="notice"><strong>Source-backed estimates for ${esc(e.area.label)}</strong><br>HUD FY2026 1-bedroom Fair Market Rent: <strong>${money(e.housing)}/month</strong> (benchmark, not average rent). USDA Sep 2026 moderate-cost food plan: ${money(e.food)}/month (single-adult planning midpoint). BLS 2023–24 ${esc(e.area.region)} transportation: ${money(e.transport)}/month and healthcare: ${money(e.health)}/month (household averages divided by mean household size, not observed individual averages). Other necessities: ${money(e.essentials)}/month (unsourced allowance).<br><strong>Current inputs:</strong> housing ${money(p.housing)}, everyday expenses ${money(p.other)}, healthcare ${money(p.health)} per month. ${Object.values(custom).some(Boolean)?'Customized amounts are preserved.':''}<br><a href="${COST_SOURCES.hud}" target="_blank" rel="noopener">HUD</a> · <a href="${COST_SOURCES.usda}" target="_blank" rel="noopener">USDA</a> · <a href="${COST_SOURCES.bls}" target="_blank" rel="noopener">BLS</a>. All values are editable; avoid counting healthcare twice.</div>`;
}
function applyLocation(p,force=false){let e=locationEstimate(p);if(!e)return false;p.costCustom=p.costCustom||{};for(let k of ['housing','other','health'])if(force||!p.costCustom[k])p[k]=e[k];p.costArea=p.city+'|'+p.state;return true;}
function resetCost(id){let p=paths.find(p=>p.id===id);if(!p)return;

p.costCustom={};applyLocation(p,true);dirty=true;drawPaths();}
function pathDefaults(type){let id=nextId++;return {id,type,name:'',city:'',state:'',interest:7,salary:'',growth:3,housing:'',other:'',health:'',costCustom:{},employer:0,schoolYears:2,tuition:'',loanShare:75,loanApr:6.5,enrollIncome:'',revenue:'',margin:40,reinvest:20,goal:'',startup:'',startBorrow:50,bizApr:9,after5:0}}function addPath(type){if(paths.length>=5){alert('Compare up to five paths.');return}let p=pathDefaults(type);applyLocation(p,true);paths.push(p);drawPaths();dirty=true}const pathHelp={
 name:'Give this option a name you will recognize, such as “Chicago marketing job” or “Start a bakery”.',
 city:'The city where you expect to live for this future. Location helps us compare living costs and taxes.',
 interest:'How excited are you about this path personally? 1 means very little interest; 10 means extremely interested. This never changes the financial math.',
 housing:'Your expected monthly rent or mortgage housing cost in this city. Use your best estimate; $0 only if you truly expect no housing payment.',
 other:'Monthly food, transportation, utilities and everyday necessities. Healthcare is entered separately; do not count it twice.',
 salary:'For a job, your yearly pay before taxes. For education, your expected yearly pay after graduating. This is not take-home pay.',
 growth:'The percentage your salary might increase each year. For example, 3 means a 3% annual raise, not $3.',
 health:'Your monthly health insurance premiums PLUS expected out-of-pocket care. For a job include only the employee-paid portion of premiums; for school or business include your expected coverage cost. Do not include this under everyday expenses.',
 employer:'Money your employer adds to your retirement account each year, such as a 401(k) match. Do not include your own contributions.',
 schoolYears:'How many years you expect to study before starting your post-graduation job.',
 tuition:'Your yearly school cost after scholarships and grants, excluding housing and normal living costs (those are entered separately).',
 loanShare:'What percent of tuition you plan to cover using student loans. For example, 75 means borrowing three quarters of tuition.',
 loanApr:'Annual interest rate on new student loans. APR is the yearly borrowing cost expressed as a percentage.',
 enrollIncome:'How much you expect to earn per year from work while enrolled, before taxes. Enter $0 if you will not work.',
 revenue:'Total money customers pay your business in its first year, BEFORE subtracting expenses. Revenue is not personal take-home pay.',
 margin:'The percent of revenue left after normal business operating expenses, before personal taxes and reinvestment. Example: $100,000 revenue minus $60,000 expenses = 40% margin.',
 reinvest:'The share of operating profit you plan to put back into the business rather than take as owner cash. Reinvestment is not automatically tax-deductible.',
 goal:'How much annual pre-tax personal income you WANT the business to provide by Year 5, after business expenses and planned reinvestment. This is a target, not a prediction.',
 startup:'Money needed to launch or expand the business, such as equipment, deposits, or setup costs. The model accounts for the spending and any associated borrowing.',
 startBorrow:'Percent of startup spending financed with a loan rather than your existing funds. Example: 50 means half borrowed.',
 bizApr:'Annual interest rate on the business startup loan. Enter 0 if no startup money is borrowed.',
 after5:'What to assume AFTER reaching the Year-5 business goal: 0 means maintain the same purchasing-power revenue level, with inflation adjustments. A positive value assumes additional annual growth; it is not a forecast.'
};
function cityOptions(state,selected){const cities=SUPPORTED_CITY_NAMES[state]||[];return `<option value="" ${!selected?'selected':''} disabled>Select a city</option>`+cities.map(n=>`<option value="${esc(n)}" ${n===selected?'selected':''}>${esc(n)}</option>`).join('')+`<option value="__other__" ${selected==='__other__'?'selected':''}>Other city (not listed)</option>`}
function cityField(p){let listed=(SUPPORTED_CITY_NAMES[p.state]||[]).includes(p.city);return `<div class="field"><label>City</label><select data-id="${p.id}" data-key="city" aria-label="City">${cityOptions(p.state,p.city)}</select><input class="${listed?'hide':''}" data-id="${p.id}" data-other-city="true" value="${listed?'':esc(p.city)}" placeholder="Enter your city" aria-label="Other city name" style="margin-top:8px"><div class="hint">Choose a city in your state. Other cities can be entered manually, but local data may not be available.</div></div>`}
function field(p,k,label,extra=''){return `<div class="field"><label>${label}</label><input data-id="${p.id}" data-key="${k}" ${extra} value="${esc(p[k])}"><div class="hint">${pathHelp[k]||''}</div></div>`}
function selectState(p){return `<div class="field"><label>State</label><select data-id="${p.id}" data-key="state"><option value="" ${!p.state?'selected':''} disabled>Select a state</option><option value="AL" ${p.state==='AL'?'selected':''}>AL</option><option value="AK" ${p.state==='AK'?'selected':''}>AK</option><option value="AZ" ${p.state==='AZ'?'selected':''}>AZ</option><option value="AR" ${p.state==='AR'?'selected':''}>AR</option><option value="CA" ${p.state==='CA'?'selected':''}>CA</option><option value="CO" ${p.state==='CO'?'selected':''}>CO</option><option value="CT" ${p.state==='CT'?'selected':''}>CT</option><option value="DE" ${p.state==='DE'?'selected':''}>DE</option><option value="FL" ${p.state==='FL'?'selected':''}>FL</option><option value="GA" ${p.state==='GA'?'selected':''}>GA</option><option value="HI" ${p.state==='HI'?'selected':''}>HI</option><option value="ID" ${p.state==='ID'?'selected':''}>ID</option><option value="IL" ${p.state==='IL'?'selected':''}>IL</option><option value="IN" ${p.state==='IN'?'selected':''}>IN</option><option value="IA" ${p.state==='IA'?'selected':''}>IA</option><option value="KS" ${p.state==='KS'?'selected':''}>KS</option><option value="KY" ${p.state==='KY'?'selected':''}>KY</option><option value="LA" ${p.state==='LA'?'selected':''}>LA</option><option value="ME" ${p.state==='ME'?'selected':''}>ME</option><option value="MD" ${p.state==='MD'?'selected':''}>MD</option><option value="MA" ${p.state==='MA'?'selected':''}>MA</option><option value="MI" ${p.state==='MI'?'selected':''}>MI</option><option value="MN" ${p.state==='MN'?'selected':''}>MN</option><option value="MS" ${p.state==='MS'?'selected':''}>MS</option><option value="MO" ${p.state==='MO'?'selected':''}>MO</option><option value="MT" ${p.state==='MT'?'selected':''}>MT</option><option value="NE" ${p.state==='NE'?'selected':''}>NE</option><option value="NV" ${p.state==='NV'?'selected':''}>NV</option><option value="NH" ${p.state==='NH'?'selected':''}>NH</option><option value="NJ" ${p.state==='NJ'?'selected':''}>NJ</option><option value="NM" ${p.state==='NM'?'selected':''}>NM</option><option value="NY" ${p.state==='NY'?'selected':''}>NY</option><option value="NC" ${p.state==='NC'?'selected':''}>NC</option><option value="ND" ${p.state==='ND'?'selected':''}>ND</option><option value="OH" ${p.state==='OH'?'selected':''}>OH</option><option value="OK" ${p.state==='OK'?'selected':''}>OK</option><option value="OR" ${p.state==='OR'?'selected':''}>OR</option><option value="PA" ${p.state==='PA'?'selected':''}>PA</option><option value="RI" ${p.state==='RI'?'selected':''}>RI</option><option value="SC" ${p.state==='SC'?'selected':''}>SC</option><option value="SD" ${p.state==='SD'?'selected':''}>SD</option><option value="TN" ${p.state==='TN'?'selected':''}>TN</option><option value="TX" ${p.state==='TX'?'selected':''}>TX</option><option value="UT" ${p.state==='UT'?'selected':''}>UT</option><option value="VT" ${p.state==='VT'?'selected':''}>VT</option><option value="VA" ${p.state==='VA'?'selected':''}>VA</option><option value="WA" ${p.state==='WA'?'selected':''}>WA</option><option value="WV" ${p.state==='WV'?'selected':''}>WV</option><option value="WI" ${p.state==='WI'?'selected':''}>WI</option><option value="WY" ${p.state==='WY'?'selected':''}>WY</option><option value="DC" ${p.state==='DC'?'selected':''}>DC</option></select><div class="hint">Select any U.S. state. Unverified states use a clearly labeled illustrative 5% effective state-income-tax placeholder; this is not the actual state tax rate.</div></div>`}function drawPaths(){ $('paths').innerHTML=paths.map(p=>`<div class="path"><div class="pathhead"><h3>${esc(p.name)}</h3><span class="pill">${p.type==='job'?'💼 Job':p.type==='school'?'🎓 Education':'🚀 Business'}</span></div><div class="grid">${field(p,'name','Path name')}${selectState(p)}${cityField(p)}${field(p,'interest','Personal interest (1–10)','type="number" min="1" max="10"')}${field(p,'housing','Monthly housing ($)','type="number" min="0"')}${field(p,'other','Monthly everyday living expenses ($)','type="number" min="0"')}${field(p,'health','Monthly healthcare ($)','type="number" min="0"')}${p.type==='job'?`${field(p,'salary','Starting annual salary ($)','type="number" min="0"')}${field(p,'growth','Annual salary growth (%)','type="number" step=".1"')}${field(p,'employer','Annual employer retirement contribution ($)','type="number" min="0"')}`:p.type==='school'?`${field(p,'schoolYears','Years in school','type="number" min="1" max="10"')}${field(p,'tuition','Annual tuition after aid ($)','type="number" min="0"')}${field(p,'loanShare','Tuition financed with loans (%)','type="number" min="0" max="100"')}${field(p,'loanApr','New student loan APR (%)','type="number" min="0"')}${field(p,'enrollIncome','Annual earnings during school ($)','type="number" min="0"')}${field(p,'salary','Post-graduation starting salary ($)','type="number" min="0"')}${field(p,'growth','Post-graduation salary growth (%)','type="number" step=".1"')}`:`${field(p,'revenue','Year-1 revenue ($)','type="number" min="0"')}${field(p,'margin','Operating profit margin (%)','type="number" min="0" max="100"')}${field(p,'reinvest','Profit reinvested (%)','type="number" min="0" max="99"')}${field(p,'goal','Year-5 personal pre-tax income goal ($)','type="number" min="0"')}${field(p,'startup','Startup investment ($)','type="number" min="0"')}${field(p,'startBorrow','Startup funded with borrowing (%)','type="number" min="0" max="100"')}${field(p,'bizApr','Startup loan APR (%)','type="number" min="0"')}${field(p,'after5','Annual revenue growth after Year 5 (%) · 0 means maintain in real terms','type="number" step=".1"')}`}</div>${costDisclosure(p)}<button class="btn" type="button" onclick="resetCost(${p.id})" ${locationEstimate(p)?'':'disabled title="No verified location estimate yet"'}>${locationEstimate(p).estimated?'Use illustrative starting estimates':'Use source-backed estimates for this location'}</button>${p.type==='business'?'<p class="hint">Year-5 income is your goal, not a forecast. Profit margin is a reverse-calculation assumption, not a predicted future margin.</p>':''}<button class="btn" type="button" onclick="exportPath(${p.id})">Save This Pathway</button> <button class="btn danger" onclick="removePath(${p.id})">Remove path</button></div>`).join('');$('paths').querySelectorAll('[data-key]').forEach(el=>el.addEventListener(el.tagName==='SELECT'?'change':'input',()=>{let p=paths.find(x=>x.id===+el.dataset.id);const k=el.dataset.key;if(k==='state'){p.state=el.value;p.city=(SUPPORTED_CITY_NAMES[p.state]||[])[0]||'';applyLocation(p);drawPaths();}else if(k==='city'){p.city=el.value==='__other__'?'':el.value;applyLocation(p);drawPaths();}else{p[k]=el.type==='number'?Number(el.value):el.value;if(['housing','other','health'].includes(k)){p.costCustom=p.costCustom||{};p.costCustom[k]=true;}if(k==='name')el.closest('.path').querySelector('h3').textContent=p.name;}dirty=true}));$('paths').querySelectorAll('[data-other-city]').forEach(el=>el.addEventListener('input',()=>{let p=paths.find(x=>x.id===+el.dataset.id);p.city=el.value;dirty=true;}));updateTaxCoverageNotice()}function updateTaxCoverageNotice(){const states=[...new Set(paths.filter(p=>p.state&&!STATE_TAX_COVERAGE.includes(p.state)).map(p=>p.state))];const box=$('taxCoverageNotice');if(!box)return;box.classList.toggle('hide',!states.length);if(states.length)box.innerHTML='<strong>Tax coverage still being built for '+esc(states.join(', '))+'.</strong> You can enter and save these futures, but results use a clearly labeled illustrative 5% state-income-tax placeholder, not verified state tax rules. Do not treat these as accurate local tax estimates. For a comparison within documented scope, use Kentucky, Illinois, limited Ohio/Michigan, Tennessee earned-income, or preliminary Indiana/Pennsylvania wage-only cases.';}function removePath(id){paths=paths.filter(p=>p.id!==id);drawPaths();dirty=true}function check(){if(paths.length<2){alert('Add at least two paths.');return false}for(const p of paths){if(!p.name.trim()||!p.state||!p.city||p.city==='__other__'){alert('Give every future a name and choose its state and city.');return false}for(const k of ['housing','other','health'])if(p[k]===''||!Number.isFinite(Number(p[k]))){alert('Enter '+k+' expenses for '+p.name+' (use 0 only if accurate).');return false}if(p.type==='job'&&(p.salary===''||Number(p.salary)<=0)){alert('Enter a starting salary for '+p.name);return false}if(p.type==='school'&&(p.salary===''||p.tuition===''||p.enrollIncome==='')){alert('Enter education cost, income during school, and post-graduation salary for '+p.name);return false}if(p.type==='business'&&(p.revenue===''||p.goal===''||p.startup==='')){alert('Enter Year 1 revenue, Year 5 income goal, and startup investment for '+p.name);return false}}if(paths.some(p=>p.type==='business'&&(p.margin<=0||p.reinvest>=100||p.revenue<=0))){alert('Business paths need positive Year-1 revenue and margin, and reinvestment below 100%.');return false}return true}function validateStartingPoint(){
if(!$('state').value||!$('city').value||($('city').value==='__other__'&&!$('cityOther').value.trim())){alert('Choose your current state and city.');return false}
for(const id of ['currentIncome','cash','investments','retirement','debt']){
if($(id).value.trim()===''){alert('Enter your '+({currentIncome:'current annual income',cash:'cash/savings',investments:'investments',retirement:'retirement savings',debt:'existing debt'}[id])+' (enter 0 if none).');$(id).focus();return false}}
if(Number($('debt').value)>0&&(!$('debtApr').value.trim()||!$('debtMin').value.trim())){alert('Enter the interest rate and required payment for your existing debt.');return false}
return true}
function go(n){if(n===1&&!validateStartingPoint())return;if(n===2&&!check()){go(1);return}for(let i=0;i<3;i++){$('page'+i).classList.toggle('hide',i!==n);$('tab'+i).classList.toggle('active',i===n)}if(n===1)drawPaths();if(n===2)renderResults();window.scrollTo({top:0,behavior:'smooth'})}function loan(label,balance,apr,minAnnual,termYears=0){return {label,balance:Math.max(0,balance),apr:Math.max(0,apr),minMonthly:Math.max(0,minAnnual)/12,termYears,interestPaid:0}}
function monthlyPayment(balance,apr,months){let r=apr/12;return months<=0?0:r>0?balance*r/(1-Math.pow(1+r,-months)):balance/months}
function simulate(p,scenario='base',override={}){
 let s=initial(),growth=(Number(p.growth)||0)/100+(scenario==='lower'?-.01:scenario==='higher'?.01:0),infl=.023+(scenario==='lower'?.01:scenario==='higher'?-.01:0),ir=.055+(scenario==='lower'?-.02:scenario==='higher'?.02:0),cr=.033;
 let ledger={cash:s.cash,invest:s.invest,ret:s.ret,unfunded:0,loans:[loan('Existing debt',s.debt,s.apr,s.min)],interestPaid:0,missedMinimum:0,paidOffMonth:null,cumulativeShortfall:0,cumulativeShortfallRepaid:0};
 const outstanding=()=>ledger.loans.reduce((a,l)=>a+l.balance,0);
 const snapshot=(y,extra={})=>({year:y,cash:ledger.cash,invest:ledger.invest,ret:ledger.ret,assets:ledger.cash+ledger.invest+ledger.ret,debt:outstanding(),unfunded:ledger.unfunded,cumulativeShortfall:ledger.cumulativeShortfall,cumulativeShortfallRepaid:ledger.cumulativeShortfallRepaid,nw:ledger.cash+ledger.invest+ledger.ret-outstanding()-ledger.unfunded,interestPaid:ledger.interestPaid,missedMinimum:ledger.missedMinimum,debtFreeYear:ledger.paidOffMonth===null?null:ledger.paidOffMonth/12,...extra});
 let rows=[snapshot(0)],cashMonthly=Math.pow(1+cr,1/12)-1,investMonthly=Math.pow(1+ir,1/12)-1;
 for(let y=1;y<=10;y++){
  let income=0,taxes=0,cost=0,rev=0,profit=0,reinv=0,tuition=0,added=[];
  let living=(Number(p.housing)+Number(p.other)+Number(p.health||0))*12*Math.pow(1+infl,y-1);
  if(p.type==='job'){income=(override.salary??p.salary)*Math.pow(1+growth,y-1);taxes=tax(income,p.state,s.filing,y)}
  else if(p.type==='school'){
   if(y<=p.schoolYears){income=p.enrollIncome;tuition=p.tuition;let financed=tuition*p.loanShare/100;cost=tuition-financed;if(financed)added.push(loan('Education year '+y,financed,p.loanApr/100,0))}
   else{income=(override.salary??p.salary)*Math.pow(1+growth,y-p.schoolYears-1);for(let l of ledger.loans)if(l.label.startsWith('Education')&&l.minMonthly===0&&l.balance>0)l.minMonthly=monthlyPayment(l.balance,l.apr,120)}
   taxes=tax(income,p.state,s.filing,y);
  }else{
   let margin=(override.margin??p.margin)/100,share=(override.reinvest??p.reinvest)/100,goal=override.goal??p.goal,year5=override.year5Revenue??(goal/Math.max(.000001,margin*(1-share))),r1=p.revenue;
   if(y<=5)rev=r1*Math.pow(year5/r1,(y-1)/4);else{let after=override.after5??p.after5;rev=year5*Math.pow(1+(after===0?infl:after/100),y-5)}
   profit=rev*margin;reinv=profit*share;income=profit-reinv;taxes=tax(profit,p.state,s.filing,y,true);
   if(y===1){let startup=override.startup??p.startup,borrow=startup*p.startBorrow/100;cost=startup-borrow;if(borrow)added.push(loan('Business startup',borrow,p.bizApr/100,0,5))}
  }
  // New borrowing is a liability, not earnings. Unborrowed tuition/startup expenses are paid at the beginning of the year.
  ledger.loans.push(...added);
  for(let l of added)if(l.termYears)l.minMonthly=monthlyPayment(l.balance,l.apr,l.termYears*12);
  let yearMinPaid=0,yearExtraPaid=0,yearInterest=0,yearMissed=0,yearShortfallRepaid=0;
  for(let month=1;month<=12;month++){
   let globalMonth=(y-1)*12+month;
   ledger.cash*=1+cashMonthly;ledger.invest*=1+investMonthly;ledger.ret*=1+investMonthly;
   if(p.type==='job')ledger.ret+=Number(p.employer)/12;
   for(let l of ledger.loans){let interest=l.balance*l.apr/12;l.balance+=interest;l.interestPaid+=interest;ledger.interestPaid+=interest;yearInterest+=interest}
   let available=(income-taxes-living)/12-(month===1?cost:0);
   // Pay ordinary expenses with current cash flow, then existing liquid assets. Any uncovered expense is tracked separately.
   if(available<0){let shortage=-available;for(let key of ['cash','invest']){let take=Math.min(ledger[key],shortage);ledger[key]-=take;shortage-=take}ledger.unfunded+=shortage;ledger.cumulativeShortfall+=shortage;available=0}
   // Minimums are not silently paid when cash is unavailable. Unpaid portions remain in loan balances and continue accruing interest.
   for(let l of ledger.loans){if(l.balance<.000001)continue;let due=Math.min(l.minMonthly,l.balance),fromFlow=Math.min(available,due);available-=fromFlow;let rest=due-fromFlow,fromAssets=0;for(let key of ['cash','invest']){let take=Math.min(ledger[key],rest);ledger[key]-=take;rest-=take;fromAssets+=take}let paid=fromFlow+fromAssets;l.balance-=paid;yearMinPaid+=paid;yearMissed+=rest;ledger.missedMinimum+=rest}
   // Repay previously unfunded ordinary expenses from new positive cash flow before optional loan prepayments.
   // Existing cash and investments are not automatically liquidated for historical shortfalls.
   let shortfallPayment=Math.min(Math.max(0,available),ledger.unfunded);
   ledger.unfunded-=shortfallPayment;ledger.cumulativeShortfallRepaid+=shortfallPayment;available-=shortfallPayment;yearShortfallRepaid+=shortfallPayment;
   // Extra repayment only uses positive monthly surplus after all minimums and prior shortfalls, prioritizing the highest APR.
   let extraBudget=Math.max(0,available)*Math.max(0,Math.min(1,s.share));
   for(let l of [...ledger.loans].sort((a,b)=>b.apr-a.apr)){let pay=Math.min(extraBudget,l.balance);l.balance-=pay;extraBudget-=pay;available-=pay;yearExtraPaid+=pay}
   if(available>0){ledger.invest+=available*s.alloc;ledger.cash+=available*(1-s.alloc)}
   if(ledger.paidOffMonth===null&&outstanding()<.005&&ledger.unfunded<.005)ledger.paidOffMonth=globalMonth;
  }
  rows.push(snapshot(y,{income,taxes,living,tuition,revenue:rev,profit,reinvest:reinv,phase:p.type==='school'?(y<=p.schoolYears?'In school':'After graduation'):p.type==='business'?'Conditional business goal':'Job',deficit:ledger.unfunded>0,minimumPaid:yearMinPaid,extraDebtPaid:yearExtraPaid,interestThisYear:yearInterest,missedMinimumThisYear:yearMissed,shortfallRepaidThisYear:yearShortfallRepaid}));
 }
 return rows
}function bisect(p,target,horizon,key,lo,hi){let f=x=>{try{return simulate(p,'base',{[key]:x})[horizon].nw-target}catch(e){if(e.message==='HIGH_INCOME_QBI_DETAILS')return NaN;throw e}};if(!Number.isFinite(f(hi)))return {status:'needsdetails'};if(f(lo)>=0)return {status:'already',value:lo};if(f(hi)<0)return {status:'unreachable'};for(let i=0;i<55;i++){let mid=(lo+hi)/2;if(f(mid)<0)lo=mid;else hi=mid}return {status:'solved',value:(lo+hi)/2}}function crossover(a,b){for(let y=1;y<a.length;y++){let prev=a[y-1].nw-b[y-1].nw,now=a[y].nw-b[y].nw;if(prev*now<0){return y-1+Math.abs(prev)/(Math.abs(prev)+Math.abs(now))}}return null}function renderResults(){const labels={base:'Base scenario',lower:'Lower outcome',higher:'Higher outcome'};$('scenarioLabel').textContent='Viewing: '+(labels[$('scenario').value]||'Base scenario')+' · Job and education estimates change with this setting; business goal paths use base assumptions.';let h=Number($('horizon').value),scenario=$('scenario').value,results;try{results=paths.map(p=>({p,rows:simulate(p,p.type==='business'?'base':scenario)}))}catch(e){if(e.message!=='HIGH_INCOME_QBI_DETAILS')throw e;$('cards').innerHTML='<div class="notice"><strong>More business tax details needed.</strong> This business reaches an income level where its tax deduction depends on information we do not collect yet. We cannot show a trustworthy comparison for this case. Try a different scenario or return when advanced business taxes are supported.</div>';$('chart').innerHTML='';$('yearTable').innerHTML='';$('analysis').innerHTML='';$('bizAnalysis').innerHTML='';$('bizPanel').classList.add('hide');return;}let sorted=[...results].sort((a,b)=>b.rows[h].nw-a.rows[h].nw);$('cards').innerHTML=sorted.map((r,i)=>`<div class="metric"><small>${esc(r.p.type==='business'?'Conditional goal · '+r.p.name:r.p.name)}</small><strong>${money(r.rows[h].nw)}</strong><small>Year ${h} personal net worth · Interest ${r.p.interest}/10</small><div class="hint">${r.p.type==='business'?'Not a forecast':i===0?'Highest modeled net worth at this horizon':'Difference from leader: '+money(r.rows[h].nw-sorted[0].rows[h].nw)}</div></div>`).join('');drawChart(results);if($("cmfMode"))cmfConfigureExplorer();$('yearTable').innerHTML='<table><thead><tr><th>Year</th>'+results.map(r=>`<th>${esc(r.p.name)}</th>`).join('')+'</tr></thead><tbody>'+Array.from({length:11},(_,y)=>'<tr><td>'+y+'</td>'+results.map(r=>`<td>${money(r.rows[y].nw)}</td>`).join('')+'</tr>').join('')+'</tbody></table>';let leader=sorted[0],other=sorted[1];let text=`<h3>What matters most at Year ${h}</h3><p><strong>${esc(leader.p.name)}</strong> has the highest modeled personal net worth at this horizon (${money(leader.rows[h].nw)}). It is ${money(leader.rows[h].nw-other.rows[h].nw)} above <strong>${esc(other.p.name)}</strong>. ${leader.p.type==='business'?'This is conditional on reaching its business goal; it is not the most likely path.':'This ranking reflects the chosen planning assumptions, not a guaranteed outcome.'}</p>`;for(let r of results){let row=r.rows[h];text+=`<h3>${esc(r.p.name)} — Why this outcome?</h3><p>By Year ${h}, modeled assets total ${money(row.assets)} and liabilities total ${money(row.debt+row.unfunded)}, leaving ${money(row.nw)} in personal net worth. ${row.debt+row.unfunded<0.005?`Your modeled liabilities are $0 because all included loans have been repaid and no unpaid shortfall remains. ${r.rows[0].debt+r.rows[0].unfunded<0.005 && r.rows.slice(1,h+1).every(z=>z.debt+z.unfunded<0.005)?"No debt or unfunded shortfalls were modeled for this pathway. ":row.debtFreeYear!==null?`You cleared modeled debts and shortfalls around Year ${row.debtFreeYear.toFixed(1)}. `:""}Total modeled loan interest paid through this year: ${money(row.interestPaid)}. Rent, groceries, and future bills still count as living expenses, not outstanding debt.`:`Remaining liabilities include ${money(row.debt)} in loans and ${money(row.unfunded)} in unfunded shortfalls. These reduce net worth until paid. Total modeled loan interest paid through this year: ${money(row.interestPaid)}. ${row.missedMinimum>0?`Required loan payments not covered by available cash or liquid assets have totaled ${money(row.missedMinimum)}; these unpaid amounts remain in loan balances rather than disappearing.`:""}`} ${r.p.type==='job'?`Annual income is ${money(row.income)}, estimated taxes are ${money(row.taxes)}, and living expenses are ${money(row.living)}.`:r.p.type==='school'?`The model includes tuition borrowing and ${h<=r.p.schoolYears?'earnings while enrolled':'post-graduation earnings'}; education costs can delay wealth accumulation.`:`This result assumes ${money(row.revenue)} in annual revenue, a ${r.p.margin}% operating margin, and ${r.p.reinvest}% of profit reinvested. It does not assign a sale value to the business.`}</p>`}if(results.length===2&&results.every(r=>r.p.type!=='business')){let cross=crossover(results[0].rows,results[1].rows);text+=`<h3>When do they cross over?</h3><p>${cross===null?'No crossover is identified within the 10-year model.':'The modeled net-worth lines cross around Year '+cross.toFixed(1)+'. This is an interpolation between annual estimates, not an exact calendar date.'}</p>`}text+=`<h3>Money vs. What You Want</h3><p>Interest ratings are shown alongside financial results, but they do not change the calculations. The highest-net-worth future is not automatically the best personal decision.</p>`;// Show school funding gaps separately from student loans; never imply that an unfunded bill is a real financing facility.
const fundingTimeline=(r,h)=>{const amounts=r.rows.map(z=>Math.max(0,Number(z.unfunded)||0));const peak=amounts.reduce((best,v,y)=>v>best.amount?{amount:v,year:y}:best,{amount:0,year:0});const now=amounts[h];const end=amounts[10];const note=now<.005?'The model shows the earlier unpaid expenses have been paid off by this year. In real life, those bills would still need to be paid on time or covered by an agreed financing or payment arrangement.':'The model still shows expenses that have not been paid. You would need a real way to cover them.';return `<div class="cmf-money-guide"><h4>How your unpaid school or living expenses change</h4><p>These are bills your plan could not cover at the time. The model keeps track of the unpaid amount and uses available money in later years to reduce it. <strong>This is separate from your loans.</strong></p><div class="cmf-story-steps"><div class="cmf-story-step"><span class="cmf-step-num">1</span><small>Most expenses left unpaid · End of Year ${peak.year}</small><strong>${money(peak.amount)}</strong><span>The largest amount your plan was short at a year-end.</span></div><div class="cmf-story-step"><span class="cmf-step-num">2</span><small>Unpaid expenses left · End of Year ${h}</small><strong>${money(now)}</strong><span>${now<.005?'Later income in the model has paid off this shortage.':'Some expenses still have not been paid in the model.'}</span></div><div class="cmf-story-step"><span class="cmf-step-num">3</span><small>Unpaid expenses left · End of Year 10</small><strong>${money(end)}</strong><span>${end<.005?'The model shows the shortage paid off by Year 10.':'The model still shows expenses that need to be paid.'}</span></div></div><p class="cmf-money-note"><strong>What this means:</strong> ${note} When the amount goes down, the model is using money earned later to pay off earlier expenses. <strong>Important:</strong> This is a planning illustration, not permission to leave bills unpaid; you would need financing or a payment arrangement to cover them when due.</p></div>`};
const schoolGaps=results.filter(r=>r.p.type==='school').map(r=>{
 const during=r.rows[Math.min(r.p.schoolYears,10)], current=r.rows[h],gap=during.unfunded;
 if(gap<=.005)return `<div class="cmf-insight"><h3>🎓 ${esc(r.p.name)} · Education pathway</h3><p><strong>No modeled school funding gap.</strong> Based on these inputs, income, assets, and specified student loans cover school-period expenses. This does not guarantee financing eligibility.</p></div>`;
 return `<div class="cmf-insight"><h3>🎓 ${esc(r.p.name)} · School costs and what you still owe</h3><div class="cmf-insight-metrics"><div><small>School and living costs not paid yet · End of Year ${Math.min(r.p.schoolYears,10)}</small><strong>${money(gap)}</strong></div><div><small>Total loans still owed · End of school</small><strong>${money(during.debt)}</strong></div></div><p><strong>Why is there money left unpaid?</strong> Tuition, rent, healthcare, and other monthly living expenses during school cost more than the income, savings, and student loans available to cover them. This is the combined amount still uncovered, not a separate bill or a second student loan.</p><p><strong>In plain English:</strong> During school, your income, savings, and planned loans leave ${money(gap)} of school and living costs unpaid. The model uses money earned in later years to pay down that amount. Separately, you finish school with ${money(during.debt)} in total loans to repay (including any debt you already had before school). <strong>Unpaid expenses and loan balances are two different amounts.</strong> In real life, you must arrange to cover bills when due; repayment after school is only possible if you obtain financing or an agreed payment plan.</p>${fundingTimeline(r,h)}<details class="cmf-details"><summary>More details about school costs and repayment</summary><p>This amount represents tuition and living bills the model could not pay during school. The model carries that unpaid amount forward and uses later available income to reduce it. It is <strong>not</strong> an approved loan or credit line. To pay these bills when they are due, you would need a real arrangement, such as eligible borrowing, financial aid, family support, more earnings, lower costs, or an agreed payment plan.</p><p>Total outstanding loan balance at the end of school, including any existing debt: <strong>${money(during.debt)}</strong>. Unfunded expenses are shown separately and are assumed to accrue <strong>no interest</strong> in this simplified model. At Year ${h}, remaining unfunded expenses: <strong>${money(current.unfunded)}</strong>. If the balance reaches $0 later, that means the model paid it down using later money—not that the bills were free or could necessarily be postponed.</p><p><strong>Check how you would cover bills during school before relying on this comparison.</strong> Try adjusting tuition, loan funding, income during school, or monthly expenses, and review the results again.</p></details></div>`;
}).join('');
// Explain startup funding needs and cash-flow stress without treating unpaid bills as available financing.
const businessGaps=results.filter(r=>r.p.type==='business').map(r=>{
 const p=r.p,initialBorrow=Number(p.startup)*Number(p.startBorrow)/100,ownStartup=Math.max(0,Number(p.startup)-initialBorrow),initialLiquid=Math.max(0,Number($('cash').value||0))+Math.max(0,Number($('investments').value||0)),initialGap=Math.max(0,ownStartup-initialLiquid),peak=r.rows.reduce((best,z)=>z.unfunded>best.amount?{amount:z.unfunded,year:z.year}:best,{amount:0,year:0}),missed=r.rows[10].missedMinimum,atH=r.rows[h];
 if(initialGap<.005&&peak.amount<.005&&missed<.005)return `<div class="cmf-insight"><h3>💼 ${esc(p.name)} · Business pathway</h3><p><strong>No modeled business funding shortage.</strong> The model finds no uncovered startup contribution, year-end unpaid expenses, or missed required loan payments. This does not establish that the business is viable or financed.</p></div>`;
 return `<div class="cmf-insight"><h3>💼 ${esc(p.name)} · Business cash-flow warning</h3><div class="cmf-insight-metrics"><div><small>Largest year-end balance of unpaid expenses${peak.year?' · Year '+peak.year:''}</small><strong>${money(peak.amount)}</strong></div><div><small>Scheduled loan payments not made on time · 10-year total</small><strong>${money(missed)}</strong></div></div><p><strong>In plain English:</strong> The business may make an operating profit but still lack cash to pay its bills. Its worst <em>year-end</em> unpaid-expense balance was ${money(peak.amount)}; at Year ${h}, ${money(atH.unfunded)} remains uncovered. The ${money(missed)} in missed scheduled loan payments is a <strong>10-year cumulative amount</strong>, not an additional loan or necessarily the amount still overdue today.</p>${fundingTimeline(r,h)}<details class="cmf-details"><summary>Understand the business funding gap and assumptions</summary><p>Startup investment: <strong>${money(p.startup)}</strong>; startup borrowing: <strong>${money(initialBorrow)}</strong>; startup contribution from other funds: <strong>${money(ownStartup)}</strong>. Starting liquid assets: <strong>${money(initialLiquid)}</strong>. ${initialGap>.005?`<strong>Initial startup funding gap: ${money(initialGap)}.</strong> This is the amount not covered by starting liquid assets or the specified startup loan, before ongoing business cash flow and living expenses.`:'The startup contribution is covered by starting liquid assets under this simplified test.'}</p><p>Largest <strong>year-end</strong> unfunded expense balance: <strong>${money(peak.amount)}</strong>${peak.year?` (Year ${peak.year})`:''}. Remaining at Year ${h}: <strong>${money(atH.unfunded)}</strong>. ${missed>.005?`Across the 10-year model, <strong>${money(missed)}</strong> of scheduled minimum loan payments could not be covered when due; those unpaid amounts remain in loan balances and may accrue interest.`:'No missed minimum loan payments are recorded in the 10-year annual model.'}</p><p><strong>Operating profit is not the same as available cash.</strong> Startup costs, personal living expenses, taxes, reinvestment, and required debt payments can create a funding need even when the business reports an operating profit. This scenario assumes the Year-5 revenue goal is achieved; it is <strong>not a forecast</strong>.</p><p>Unfunded expenses are hypothetical liabilities, <strong>not approved financing</strong>; they accrue no interest in this simplified model. Real-world unpaid bills, missed loan payments, and unavailable financing can have additional consequences. The maximum shown is based on year-end snapshots and may understate a temporary intra-year peak. <strong>Review how the business would fund startup and operating shortages before relying on this comparison.</strong></p></details></div>`;
}).join('');
const riskSummary=results.map(r=>{const peak=r.rows.reduce((a,z)=>Math.max(a,z.unfunded||0),0),missed=r.rows[10].missedMinimum||0;return {name:r.p.name,peak,missed}}).filter(x=>x.peak>.005||x.missed>.005);const overview='<div class="cmf-insight cmf-overview"><strong>Start here · Your results in plain English</strong><p>'+esc(sorted[0].p.name)+' has the highest modeled Year '+h+' personal net worth ('+money(sorted[0].rows[h].nw)+'). '+(riskSummary.length?riskSummary.length+' of '+results.length+' pathways show an unfunded-expense or missed-payment warning somewhere in the 10-year model. Check affordability before comparing final balances.':'No pathway shows a year-end unfunded balance or missed required payment under these assumptions.')+'</p><p class="muted">Business outcomes are conditional goals, not predictions. Highest net worth does not automatically mean the best life choice.</p></div>';const explain='<details class="cmf-details"><summary>Why each pathway ends up here · detailed explanations</summary>'+text+'</details>';$('analysis').innerHTML=overview+schoolGaps+businessGaps+explain;renderBusiness(results,h)}function drawChart(results){let W=950,H=315,pad={l:70,r:22,t:20,b:42},vals=results.flatMap(r=>r.rows.map(x=>x.nw)),min=Math.min(0,...vals),max=Math.max(1,...vals),spread=max-min||1,x=y=>pad.l+y/10*(W-pad.l-pad.r),y=v=>H-pad.b-(v-min)/spread*(H-pad.t-pad.b),colors=['#2563eb','#d97706','#139c88','#9b59b6','#df5b6b'];let svg=`<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Net worth by year for selected paths">`;for(let i=0;i<=4;i++){let v=min+spread*i/4,yy=y(v);svg+=`<line x1="${pad.l}" x2="${W-pad.r}" y1="${yy}" y2="${yy}" stroke="#e3eaf3"/><text x="${pad.l-10}" y="${yy+4}" font-size="12" fill="#60718a" text-anchor="end">${money(v)}</text>`}for(let i=0;i<=10;i+=2)svg+=`<text x="${x(i)}" y="${H-15}" text-anchor="middle" font-size="12" fill="#60718a">${i}</text>`;results.forEach((r,i)=>{let pts=r.rows.map((v,j)=>`${x(j)},${y(v.nw)}`).join(' ');svg+=`<polyline points="${pts}" fill="none" stroke="${colors[i]}" stroke-width="3" ${r.p.type==='business'?'stroke-dasharray="7 5"':''}/>`});svg+=`</svg><div style="display:flex;flex-wrap:wrap;gap:16px">`+results.map((r,i)=>`<span style="font-size:13px"><span style="color:${colors[i]}">●</span> ${esc(r.p.name)}${r.p.type==='business'?' (goal)':''}</span>`).join('')+'</div>';$('chart').innerHTML=svg}function renderBusiness(results,h){let bs=results.filter(r=>r.p.type==='business');$('bizPanel').classList.toggle('hide',!bs.length);if(!bs.length)return;let competitors=results.filter(r=>r.p.type!=='business');let html='';for(let r of bs){let p=r.p,row=r.rows[h],personal=row.profit-row.reinvest,cumulativeReinvest=r.rows.slice(1,h+1).reduce((sum,year)=>sum+(year.reinvest||0),0);html+=`<div class="divider"></div><h3>${esc(p.name)} · What does ${money(row.nw)} mean?</h3><p>At Year ${h}, this conditional goal scenario produces ${money(row.assets)} in modeled personal assets and ${money(row.debt+row.unfunded)} in liabilities. Negative net worth does not necessarily mean the business has an operating loss. Business sale value is intentionally excluded.</p><p>At this horizon, revenue is ${money(row.revenue)}, operating profit ${money(row.profit)}, planned reinvestment ${money(row.reinvest)}, and pre-tax personal income ${money(personal)}. Taxes are assessed on operating profit, not automatically reduced by reinvestment.</p><div class="notice"><h3>Where Your Business Money Goes</h3><p><strong>Reinvested in Year ${h}:</strong> ${money(row.reinvest)}<br><strong>Total reinvested through Year ${h}:</strong> ${money(cumulativeReinvest)}</p><p class="muted">This is money put back into the business, not its current value. We don't guess what the business could sell for.</p></div>`;if(competitors.length){html+=`<h3>Revenue required to match another future</h3>`;for(let c of competitors){let target=c.rows[h].nw;if(h===1){html+=`<p><strong>${esc(c.p.name)}, Year 1:</strong> Year-1 revenue is fixed at ${money(p.revenue)} in this scenario. A separate Year-1 revenue solver is pending.</p>`;continue}let sol=bisect(p,target,h,'year5Revenue',.01,100000000);html+=`<p><strong>${esc(c.p.name)}, Year ${h}:</strong> ${sol.status==='solved'?`Required Year-5 revenue endpoint ${money(sol.value)}, implying ${((sol.value/p.revenue)**.25-1)*100<0?'a decline of ':'growth of '}${Math.abs(((sol.value/p.revenue)**.25-1)*100).toFixed(1)}% annually from Year 1 to Year 5. ${h===10?'The Year-10 result additionally assumes the selected post-Year-5 revenue rule.':''}`:sol.status==='already'?'The business scenario already meets the target at the minimum revenue tested.':sol.status==='needsdetails'?'Requires more business tax details to calculate reliably.':'No breakeven found within the search range.'} This is a required scenario, not a forecast.</p>`}}html+=`<h3>Your Three Biggest Business Levers</h3>`;let levers=[{label:'Improve operating margin by 5 percentage points',o:{margin:Math.min(100,p.margin+5)},caveat:'Requires better pricing, sales mix, or cost control; may not be achievable.'},{label:'Increase cash available for personal use (reinvest 10 percentage points less)',o:{reinvest:Math.max(0,p.reinvest-10)},caveat:'This may leave less money for future business growth.'},{label:'Reduce startup investment by 20%',o:{startup:p.startup*.8},caveat:'May reduce equipment, marketing, or operating capacity.'}].map(l=>{let delta;try{delta=simulate(p,'base',l.o)[h].nw-row.nw}catch(e){if(e.message!=='HIGH_INCOME_QBI_DETAILS')throw e;delta=NaN}return {...l,delta}}).sort((a,b)=>b.delta-a.delta);html+='<ol>'+levers.map(l=>`<li><strong>${esc(l.label)}</strong> → modeled Year-${h} net-worth change ${Number.isFinite(l.delta)?money(l.delta):'Unavailable without more tax details'}. ${esc(l.caveat)}</li>`).join('')+'</ol>';html+=`<h3>Business Efficiency Explorer</h3><p class="muted">Adjust the margin and reinvestment rate to see the revenue required for your Year-5 pre-tax personal-income goal. This simplified relationship is not the complete net-worth breakeven calculation.</p><div class="grid two"><div class="field"><label>Operating profit margin (%)</label><input id="m${p.id}" type="number" min="1" max="100" value="${p.margin}" oninput="efficiency(${p.id})"></div><div class="field"><label>Profit reinvested (%)</label><input id="r${p.id}" type="number" min="0" max="99" value="${p.reinvest}" oninput="efficiency(${p.id})"></div></div><p id="e${p.id}"></p><p><strong>Financial improvement opportunities:</strong> Review prices and cost of goods, recurring overhead, borrowing costs, and whether reinvested funds are producing value. These are levers to investigate, not guarantees of improved sales or business success.</p>`} $('bizAnalysis').innerHTML=html;bs.forEach(r=>efficiency(r.p.id))}function efficiency(id){let p=paths.find(p=>p.id===id),m=Number($('m'+id)?.value)/100,r=Number($('r'+id)?.value)/100;if(!m||m<=0||r>=1){$('e'+id).textContent='Enter a positive margin and reinvestment below 100%.';return}let profit=p.goal/(1-r),revenue=profit/m;$('e'+id).innerHTML=`<strong>${money(revenue)} annual revenue required</strong> to provide ${money(p.goal)} pre-tax personal income at Year 5, with ${money(profit)} operating profit before reinvestment. This excludes personal income taxes.`}const STARTING_KEYS=['city','state','filing','currentIncome','cash','investments','retirement','debt','debtApr','debtMin','debtStrategy','customDebt','allocation'];
function scenarioChanged(){renderResults();queueAutosave()}
function snapshot(){return {version:3,scenario:$('scenario').value,starting:Object.fromEntries(STARTING_KEYS.map(k=>[k,k==='city'&&$('city').value==='__other__'?$('cityOther').value:$(k).value])),paths:JSON.parse(JSON.stringify(paths)),nextId};}
function applySnapshot(data){if(!data||!data.starting||!Array.isArray(data.paths))throw Error('This file is not a valid Compare My Futures save.');if(data.paths.length>100)throw Error('Too many paths in save file.');for(const p of data.paths){if(!p||!['job','school','business'].includes(p.type)||!Number.isInteger(p.id))throw Error('Invalid future path in save file.');}for(let [k,v] of Object.entries(data.starting)){if(!STARTING_KEYS.includes(k)||!$(k))continue;if(k==='city'){$('city').dataset.otherValue=String(v??'');$('city').value='';}else $(k).value=String(v??'');}$('scenario').value=['base','lower','higher'].includes(data.scenario)?data.scenario:'base';paths=data.paths;paths.forEach(p=>{if(p.health===undefined)p.health=0;p.costCustom=p.costCustom||{}});nextId=Number.isInteger(data.nextId)?data.nextId:Math.max(1,...paths.map(p=>p.id+1));syncStartingCity();syncDebtFields();drawPaths();dirty=false;}
let importMode='comparison';
function chooseImport(mode){importMode=mode;const input=$('importFile');input.value='';input.click()}
function safeFileName(value){return String(value||'my-pathway').trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,55)||'my-pathway'}
function downloadJson(payload,filename){const blob=new Blob([JSON.stringify(payload,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download=filename;document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),2000)}
function exportPath(id){const p=paths.find(x=>x.id===id);if(!p)return;downloadJson({format:'compare-my-futures-pathway',version:1,pathway:JSON.parse(JSON.stringify(p))},'cmf-pathway-'+safeFileName(p.name)+'.json');const st=$('saveStatus');if(st)st.textContent='Downloaded '+(p.name||'your pathway')+'. You can add it to another comparison later.'}
// Reject malformed and potentially hostile imported values before mutating saved work.
function validImportedPath(p){
 if(!p||typeof p!=='object'||!['job','school','business'].includes(p.type)||typeof p.name!=='string'||p.name.length>150||typeof p.city!=='string'||p.city.length>120||typeof p.state!=='string'||p.state.length>3)return false;
 const keys=['housing','other','health','salary','growth','employer','schoolYears','tuition','loanShare','loanApr','enrollIncome','revenue','margin','reinvest','goal','startup','startBorrow','bizApr','after5','interest'];
 return keys.every(k=>p[k]===undefined||p[k]===''||(Number.isFinite(Number(p[k]))&&Math.abs(Number(p[k]))<=1e10))&&['housing','other','health','salary','employer','tuition','loanApr','enrollIncome','revenue','goal','startup','bizApr'].every(k=>p[k]===undefined||p[k]===''||Number(p[k])>=0)&&['loanShare','margin','reinvest','startBorrow'].every(k=>p[k]===undefined||p[k]===''||(Number(p[k])>=0&&Number(p[k])<=100));
}
function validImportedStarting(s){
 if(!s||typeof s!=='object')return false;
 const keys=['currentIncome','cash','investments','retirement','debt','debtApr','debtMin'];
 return keys.every(k=>s[k]===undefined||s[k]===''||(Number.isFinite(Number(s[k]))&&Number(s[k])>=0&&Number(s[k])<=1e11));
}
async function importSelectedFile(input){const file=input.files&&input.files[0];if(!file)return;try{if(file.size>2000000)throw Error('That file is too large.');const data=JSON.parse(await file.text());if(importMode==='pathway'){
if(data?.format!=='compare-my-futures-pathway'||!data.pathway||!['job','school','business'].includes(data.pathway.type))throw Error('This is not a saved individual pathway. Choose a file downloaded with Save This Pathway.');
if(paths.length>=5)throw Error('You can compare up to five pathways. Remove one before adding another.');
if(!validImportedPath(data.pathway))throw Error('The pathway contains invalid or unsafe values. Your current work was not changed.');
const p=JSON.parse(JSON.stringify(data.pathway));p.id=nextId++;p.costCustom=p.costCustom&&typeof p.costCustom==='object'?p.costCustom:{};p.name=String(p.name||'Imported pathway').slice(0,120);paths.push(p);dirty=true;drawPaths();queueAutosave();
for(let i=0;i<3;i++){$('page'+i).classList.toggle('hide',i!==1);$('tab'+i).classList.toggle('active',i===1)}
$('saveStatus').textContent='Added '+p.name+' without replacing your existing pathways. Results will use your current Starting Point.';window.scrollTo(0,0);
}else{
if(!data||!data.starting||!Array.isArray(data.paths))throw Error('This is not a saved full comparison. Choose a file downloaded with Download My Comparison.'); if(data.paths.length>5||new Set(data.paths.map(p=>p.id)).size!==data.paths.length||data.paths.some(p=>!p||!['job','school','business'].includes(p.type)||!Number.isInteger(p.id)))throw Error('Invalid or duplicate pathways in the saved comparison.');
if(data.paths.some(p=>!validImportedPath(p)))throw Error('One or more pathways contain invalid values. Your current work was not changed.');
if(!validImportedStarting(data.starting))throw Error('The starting point contains invalid values. Your current work was not changed.');
if(!confirm('Open this saved comparison? Your current Starting Point and pathways will be replaced. Download your current comparison first if you want to keep it.'))return;
applySnapshot(data);queueAutosave();for(let i=0;i<3;i++){$('page'+i).classList.toggle('hide',i!==1);$('tab'+i).classList.toggle('active',i===1)}
$('saveStatus').textContent='Opened your saved comparison with '+paths.length+' pathway(s).';window.scrollTo(0,0);
}
}catch(e){alert('Could not open the saved file: '+e.message)}finally{input.value=''}}
let autosaveTimer=null, autosaveFailed=false;
function autosaveNow(){if(autosaveTimer){clearTimeout(autosaveTimer);autosaveTimer=null}const status=$('autosaveStatus');try{localStorage.setItem('compare-my-futures-v1',JSON.stringify(snapshot()));dirty=false;autosaveFailed=false;if(status)status.textContent='✓ Progress saved on this device';return true}catch(e){autosaveFailed=true;if(status)status.textContent='Automatic saving unavailable in this browser. Please use Download My Comparison to keep your work.';return false}}
function queueAutosave(){dirty=true;const status=$('autosaveStatus');if(status)status.textContent='Saving changes…';clearTimeout(autosaveTimer);autosaveTimer=setTimeout(autosaveNow,550)}
function save(){return autosaveNow()}
function restore(){try{const raw=localStorage.getItem('compare-my-futures-v1');if(raw){applySnapshot(JSON.parse(raw));const st=$('autosaveStatus');if(st)st.textContent='✓ Previous progress restored from this device';}}catch(e){console.warn('Could not restore saved data',e);const st=$('autosaveStatus');if(st)st.textContent='Browser storage unavailable. Download My Comparison to keep your work.'}}
function exportData(){try{downloadJson(snapshot(),'cmf-my-comparison-'+new Date().toISOString().replace(/[-:]/g,'').replace('T','-').replace('Z','').replace('.','-')+'.json');const st=$('saveStatus');if(st)st.textContent='Your full comparison was downloaded. Keep the file to reopen your work later.'}catch(e){alert('Could not download: '+e.message)}}
function setNoDebt(){['debt','debtApr','debtMin'].forEach(id=>$(id).value='0');dirty=true;syncDebtFields();queueAutosave()}
function syncDebtFields(){let noDebt=$('debt').value.trim()!==''&&Number($('debt').value)===0;['debtApr','debtMin'].forEach(id=>{if(noDebt)$(id).value='0';$(id).disabled=noDebt});$('debtStrategyBox').style.display=noDebt?'none':'';$('customDebtBox').style.display=noDebt?'none':($('debtStrategy').value==='custom'?'block':'none');$('noDebtStatus').textContent=noDebt?'No existing debt: interest rate and required payment are set to $0. You can still compare paths that involve new student or business loans.':'If you have no existing debt, enter $0 or use the button above.'}
$('debt').addEventListener('input',syncDebtFields);
function syncStartingCity(){const state=$('state').value,chosen=$('city').dataset.otherValue||$('city').value,cities=SUPPORTED_CITY_NAMES[state]||[];const selected=!state?'':cities.includes(chosen)?chosen:'__other__';$('city').innerHTML=cityOptions(state,selected);$('city').value=selected;$('cityOther').classList.toggle('hide',selected!=='__other__');if(selected==='__other__')$('cityOther').value=chosen==='__other__'?'':chosen;}
$('state').addEventListener('change',()=>{$('city').dataset.otherValue=(SUPPORTED_CITY_NAMES[$('state').value]||[])[0]||'';syncStartingCity();dirty=true});$('city').addEventListener('change',()=>{$('cityOther').classList.toggle('hide',$('city').value!=='__other__');dirty=true});$('cityOther').addEventListener('input',()=>dirty=true);
$('debtStrategy').addEventListener('change',syncDebtFields);document.querySelectorAll('#page0 input,#page0 select').forEach(e=>e.addEventListener('input',()=>dirty=true));window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue=''}});restore();syncDebtFields();syncStartingCity();drawPaths();
// Capture all edits, including dynamically created pathway inputs and select changes.
document.addEventListener('input',e=>{if(e.target.closest('#page0,#page1'))queueAutosave()},true);
document.addEventListener('change',e=>{if(e.target.closest('#page0,#page1'))queueAutosave()},true);
document.addEventListener('click',e=>{if(e.target.closest('#page1')&&e.target.closest('button')&&!e.target.closest('button[onclick*="export"],button[onclick*="chooseImport"]'))queueAutosave()},true);
window.addEventListener('pagehide',()=>{if(dirty)autosaveNow()});


// Competition-ready offline landing page and question assistant; no external requests.
function cmfStart(resume){
  if(!resume){let existing=false;try{existing=!!localStorage.getItem('compare-my-futures-v1')}catch(e){};
    if(existing&&!confirm('Start a new comparison? Your saved browser progress will be replaced when you make changes. Download a backup first if you want to keep it.'))return;
    try{localStorage.removeItem('compare-my-futures-v1')}catch(e){};
    for(const id of ['currentIncome','cash','investments','retirement','debt','debtApr','debtMin'])$(id).value='';
    $('state').value='';$('city').dataset.otherValue='';$('cityOther').value='';syncStartingCity();paths=[];nextId=1;drawPaths();
  }
  $('cmfHome').classList.add('hidden');$('cmfApp').classList.add('active');
  for(let i=0;i<3;i++){$('page'+i).classList.toggle('hide',i!==0);$('tab'+i).classList.toggle('active',i===0)}
  window.scrollTo(0,0);
}
function cmfConfigureExplorer(){
 const mode=$('cmfMode').value, target=['salaryTarget','tuitionTarget','revenueTarget'].includes(mode),change=mode==='change';
 const eligible=paths.filter(p=>mode==='tuitionTarget'?p.type==='school':mode==='revenueTarget'?p.type==='business':mode==='salaryTarget'?p.type==='job':true);
 const subj=$('cmfSubject'),ref=$('cmfReference'),prev=subj.value,prevRef=ref.value;
 subj.innerHTML=eligible.map(p=>'<option value="'+p.id+'">'+esc(p.name)+'</option>').join('');ref.innerHTML=paths.map(p=>'<option value="'+p.id+'">'+esc(p.name)+'</option>').join('');
 if(eligible.some(p=>String(p.id)===prev))subj.value=prev;
 if(paths.some(p=>String(p.id)===prevRef))ref.value=prevRef;
 if(ref.value===subj.value&&paths.length>1)ref.value=String(paths.find(p=>String(p.id)!==subj.value).id);
 $('cmfSubjectWrap').style.display=target||change?'':'none';$('cmfReferenceWrap').style.display=target?'':'none';$('cmfChangeWrap').style.display=change?'':'none';$('cmfAmountWrap').style.display=change?'':'none';$('cmfDirectionWrap').style.display=change?'':'none';$('cmfYearWrap').style.display=['crossovers','leaders','funding'].includes(mode)?'none':'';
 const field=$('cmfField').value;
 if(change){const types=field==='tuition'?['school']:['startup','margin','reinvest'].includes(field)?['business']:field==='salary'?['job','school']:['job','school','business'];const opts=paths.filter(p=>types.includes(p.type));subj.innerHTML=opts.map(p=>'<option value="'+p.id+'">'+esc(p.name)+'</option>').join('');if(opts.some(p=>String(p.id)===prev))subj.value=prev;}
}
function cmfRunExplorer(){
 const mode=$('cmfMode').value,year=$('cmfYear').value,subject=paths.find(p=>String(p.id)===$('cmfSubject').value),reference=paths.find(p=>String(p.id)===$('cmfReference').value);
 if(paths.length<2){$('qaAnswer').textContent='Create at least two pathways to explore comparisons.';return}
 let q='';
 if(mode==='ranking')q='highest net worth year '+year;
 else if(mode==='crossovers')q='show all crossover pairs';
 else if(mode==='leaders')q='which path leads each year';
 else if(mode==='funding')q='biggest funding gap';
 else if(mode==='debt')q='how much debt remains in year '+year;
 else if(mode==='cashflow')q='income taxes and living expense breakdown year '+year;
 else if(['salaryTarget','tuitionTarget','revenueTarget'].includes(mode)){
  if(!subject||!reference||subject.id===reference.id){$('qaAnswer').textContent='Choose two different pathways.';return}
  const kind=mode==='salaryTarget'?'salary':mode==='tuitionTarget'?'tuition':'revenue';
  // Dedicated fixed-selection target: avoid fragile natural-language matching.
  cmfRunTarget(kind,subject,reference,Number(year));return;
 }else if(mode==='change'){
  if(!subject){$('qaAnswer').textContent='Choose a pathway that supports this adjustment.';return}
  const value=Number($('cmfAmount').value),field=$('cmfField').value,dir=$('cmfDirection').value;
  if(!Number.isFinite(value)||value<=0){$('qaAnswer').textContent='Enter a positive change amount.';return}
  const words={housing:'rent',other:'other expenses',health:'healthcare',salary:'salary',tuition:'tuition',startup:'startup investment',margin:'operating margin',reinvest:'reinvestment'};
  q='What if '+subject.name+' '+words[field]+' '+(dir==='decrease'?'decreased':'increased')+' by '+(field==='margin'||field==='reinvest'?value+'%':'$'+value)+(field==='salary'?' per year':'')+' in year '+year+'?';
 }
 $('cmfQuestion').value=q;cmfAnswer();
}
function cmfRunTarget(kind,subject,reference,year){
 const output=$('qaAnswer'),fmt=money;
 let original,base,target;
 try{base=simulate(subject,subject.type==='business'?'base':$('scenario').value)[year].nw;target=simulate(reference,reference.type==='business'?'base':$('scenario').value)[year].nw;}catch(e){output.textContent='This comparison requires financial details the current model cannot reliably calculate.';return}
 original=kind==='revenue'?Number(subject.goal)/Math.max(.000001,subject.margin/100*(1-subject.reinvest/100)):Number(subject[kind]);
 const calc=v=>{try{return simulate(subject,subject.type==='business'?'base':$('scenario').value,kind==='revenue'?{year5Revenue:v}:{[kind]:v})[year].nw}catch(e){return NaN}};
 if(kind==='revenue'&&year===1){output.textContent='Choose Year 5 or Year 10: the Year-5 business revenue goal cannot change Year-1 results.';return}
 const a=calc(0),isTuition=kind==='tuition';
 if(!Number.isFinite(a)){output.textContent='This target requires unsupported financial details. No estimate is being guessed.';return}
 if(isTuition&&a<target-1){output.textContent='TUITION TARGET NOT POSSIBLE BY TUITION ALONE · YEAR '+year+'\nEven with annual tuition reduced to $0, '+subject.name+' would have '+fmt(a)+' in modeled personal net worth, below '+reference.name+' at '+fmt(target)+'.\n\nThat means tuition reductions alone cannot close the gap. Other factors—such as years out of work, living costs, loan funding, or post-school pay—would also need to change.\n\nThe school funding gap is an amount of expenses the model cannot pay, not money automatically available to borrow.';return}
 if(!isTuition&&a>=target){output.textContent=subject.name+' already meets this net-worth target even at a zero '+kind+' assumption. A positive minimum target is not required.';return}
 let lo=0,hi=isTuition?Math.max(original*3,100000):Math.max(original*1.5,100000),max=isTuition?hi:kind==='revenue'?100000000:2000000,b=calc(hi);
 if(!isTuition)while(Number.isFinite(b)&&b<target&&hi<max){hi=Math.min(max,hi*1.5+1000);b=calc(hi)}
 if(!Number.isFinite(b)){output.textContent='The calculation enters a tax range the model does not support. No target is being guessed.';return}
 if((isTuition&&b>target)||(!isTuition&&b<target)){output.textContent='No supported '+kind+' target can be calculated in the tested range.';return}
 for(let i=0;i<48;i++){let mid=(lo+hi)/2,z=calc(mid);if(!Number.isFinite(z)){output.textContent='The target crosses an unsupported tax range; no reliable answer is available.';return}if(isTuition?z>target:z<target)lo=mid;else hi=mid}
 const needed=(lo+hi)/2,delta=needed-original;
 output.textContent='WHAT WOULD IT TAKE? · YEAR '+year+'\n'+subject.name+' to match '+reference.name+' ('+fmt(target)+' personal net worth)\nRequired '+(kind==='revenue'?'Year-5 annual business revenue':kind==='tuition'?'annual tuition':'annual salary')+': '+fmt(needed)+'\nCurrent assumption: '+fmt(original)+'\nChange needed: '+(delta>=0?'+':'')+fmt(delta)+'\nCurrent modeled net worth: '+fmt(base)+'\n\nThis is a model-based target, not a forecast. The adjustment is temporary and your saved pathways are unchanged.';
}
function cmfAskPreset(q){$('cmfQuestion').value=q;cmfAnswer()}
// Preview enhancement: offline what-if comparisons use the existing 10-year financial engine.
function cmfAnswer(){
 const output=$('qaAnswer'),raw=$('cmfQuestion').value.trim(),q=raw.toLowerCase();
 if(!q){output.textContent='Ask a question or choose an example above.';return}
 let base;try{if(paths.length<2)throw Error('Create at least two pathways first.');base=paths.map(p=>({p,rows:simulate(p,p.type==='business'?'base':$('scenario').value)}))}catch(e){output.textContent=e.message==='HIGH_INCOME_QBI_DETAILS'?'More business tax details are required for a reliable answer.':'Unable to calculate: '+e.message;return}
 const yrMatch=q.match(/\byear\s*(10|[0-9])\b/),year=yrMatch?Number(yrMatch[1]):Number($('horizon').value||10);
 const fmt=(n)=>money(n),note='\n\nAll values are modeled estimates, not guarantees. Business pathways are conditional goals, not forecasts.';
 const named=base.filter(r=>r.p.name.trim().length>1&&q.includes(r.p.name.toLowerCase()));
 const crossPairs=(arr)=>{const lines=[];for(let i=0;i<arr.length;i++)for(let j=i+1;j<arr.length;j++){const a=arr[i],b=arr[j];let hits=[];for(let y=1;y<=10;y++){const d0=a.rows[y-1].nw-b.rows[y-1].nw,d1=a.rows[y].nw-b.rows[y].nw;if(Math.abs(d0)<.005&&y===1)hits.push('Year 0 (equal starting value)');if(d0*d1<0||Math.abs(d1)<.005){const t=Math.abs(d1)<.005?y:y-1+Math.abs(d0)/(Math.abs(d0)+Math.abs(d1));if(!hits.some(x=>x==='Year '+t.toFixed(1)))hits.push('Year '+t.toFixed(1))}}lines.push(a.p.name+' vs '+b.p.name+': '+(hits.length?hits.join(', '):'no crossover in Years 1–10'))}return lines};
 // Reverse-target exploration: use the same simulation engine, without changing saved inputs.
 const targetIntent=/(?:what\s+(?:salary|pay|tuition|revenue)|how\s+much\s+(?:salary|pay|tuition|revenue)|what\s+would\s+it\s+take|need\s+to\s+(?:match|catch|equal)|required\s+(?:salary|tuition|revenue))/.test(q)&&/(?:match|catch|equal|leader|highest|need|take|required)/.test(q);
 if(targetIntent){
  const kind=/tuition|school\s+cost/.test(q)?'tuition':/revenue|business/.test(q)?'revenue':/salary|pay|earn/.test(q)?'salary':null;
  const eligible=base.filter(r=>kind==='tuition'?r.p.type==='school':kind==='revenue'?r.p.type==='business':r.p.type==='job'||r.p.type==='school');
  if(!kind||!eligible.length){output.textContent='Choose a salary, tuition, or business revenue target for a pathway of the appropriate type.';return}
  const ranked=[...base].sort((a,b)=>b.rows[year].nw-a.rows[year].nw);
  const subject=named.find(r=>eligible.includes(r))||eligible.slice().sort((a,b)=>a.rows[year].nw-b.rows[year].nw)[0];
  const reference=named.find(r=>r!==subject)||ranked.find(r=>r!==subject);
  if(!reference){output.textContent='Add another pathway to set a comparison target.';return}
  const goalNW=reference.rows[year].nw,originalNW=subject.rows[year].nw;
  const original=kind==='revenue'?Number(subject.p.goal/Math.max(.000001,subject.p.margin/100*(1-subject.p.reinvest/100))):Number(subject.p[kind]);
  if(!Number.isFinite(original)||original<0){output.textContent='This pathway has no usable starting value for that target.';return}
  if(kind==='revenue'&&year===1){output.textContent='Year-1 business revenue is fixed by the starting revenue input. The Year-5 revenue goal cannot change Year-1 results. Choose Year 5 or Year 10.';return}
  const calc=v=>{const opts=kind==='revenue'?{year5Revenue:v}:{[kind]:v};try{return simulate(subject.p,subject.p.type==='business'?'base':$('scenario').value,opts)[year].nw}catch(e){if(e.message==='HIGH_INCOME_QBI_DETAILS')return NaN;throw e}};
  const ascending=kind!=='tuition';
  const low=0,maxHigh=kind==='tuition'?Math.max(100000,original*3):kind==='revenue'?Math.max(100000000,original*3):Math.max(2000000,original*5);
  let lo=low,hi=kind==='tuition'?maxHigh:Math.max(1000,original*1.25),a=calc(lo),b=calc(hi);
  if(ascending&&Number.isFinite(a)){while(Number.isFinite(b)&&b<goalNW&&hi<maxHigh){lo=hi;hi=Math.min(maxHigh,hi*1.4+1000);b=calc(hi)}}
  if(!Number.isFinite(a)||!Number.isFinite(b)){output.textContent='A reliable target cannot be calculated within the supported tax model. No answer is being guessed.'+note;return}
  const achievable=ascending?(a<=goalNW&&b>=goalNW):(a>=goalNW&&b<=goalNW);
  if(!achievable){
   if((ascending&&a>goalNW)||(!ascending&&b>goalNW)){output.textContent=subject.p.name+' already meets or exceeds '+reference.p.name+' at the relevant extreme. A unique target is not needed under these assumptions.'+note;return}
   output.textContent='No reliable '+kind+' target was found within the tested range. The target may be unreachable, or the financial model may need more detail.'+note;return;
  }
  for(let i=0;i<55;i++){const mid=(lo+hi)/2,v=calc(mid);if(!Number.isFinite(v)){output.textContent='The target crosses an unsupported business tax range, so no reliable answer is available.'+note;return}if(ascending?(v<goalNW):(v>goalNW))lo=mid;else hi=mid}
  const needed=(lo+hi)/2,delta=needed-original;
  output.textContent='WHAT WOULD IT TAKE? · YEAR '+year+'\n'+subject.p.name+' to match '+reference.p.name+' ('+fmt(goalNW)+' personal net worth)\n'+(kind==='revenue'?'Required Year-5 annual revenue endpoint':kind==='tuition'?'Required annual tuition':'Required annual salary')+': '+fmt(needed)+'\nCurrent assumption: '+fmt(original)+'\nChange needed: '+(delta>=0?'+':'')+fmt(delta)+'\nCurrent modeled net worth: '+fmt(originalNW)+'\n\nThis is a mathematical scenario target, not a forecast or a promise that the change is achievable. '+(kind==='revenue'?'The business tax model and post-Year-5 growth rule constrain the result. Business value is excluded.':kind==='tuition'?'Student-loan funding changes with tuition under the selected loan-share assumption.':'Taxes and debt repayment are recalculated with the adjusted earnings.')+' The change is temporary; your saved pathways remain unchanged.'+note;return;
 }
 const change=/(?:what\s+if|suppose|if\s+my|if\s+i|increase|decrease|raise|lower|reduce|cut|go(?:es)?\s+up|go(?:es)?\s+down|more|less)/.test(q);
 const amountMatch=q.match(/\$\s*([\d,]+(?:\.\d+)?)/)||q.match(/\b([\d,]+(?:\.\d+)?)\s*(?:dollars?|per month|monthly|per year|annually|a year)\b/);
 const amount=amountMatch?Number(amountMatch[1].replace(/,/g,'')):NaN;
 const percentMatch=q.match(/(\d+(?:\.\d+)?)\s*(?:percentage\s+points?|%)/);
 const down=/decreas|reduc|lower|cut|less|drop|fall|down/.test(q),sign=down?-1:1;
 const rent=/\brent\b|\bhousing\b|\bmortgage\b/.test(q),health=/healthcare|health insurance/.test(q),living=/\bexpenses?\b|\bspending\b|\bliving costs?\b|\butilities\b|\bgroceries\b/.test(q),salary=/\bsalary\b|\bpay\b|\bincome\b|\bearn\b|\bwages?\b/.test(q),tuition=/tuition|school cost/.test(q),margin=/\bmargin\b/.test(q),reinvest=/reinvest/.test(q),startup=/startup|start-up/.test(q);
 if(change&&(rent||health||living||salary||tuition||margin||reinvest||startup)){
  let field=rent?'housing':health?'health':tuition?'tuition':margin?'margin':reinvest?'reinvest':startup?'startup':living?'other':'salary';
  let value=(field==='margin'||field==='reinvest')&&percentMatch?Number(percentMatch[1]):amount;
  if(!Number.isFinite(value)||value<=0){output.textContent='Include a change amount, such as “What if my rent increased by $300 per month?” or “What if UR sports reinvestment decreased by 10%?”';return}
  const annual=/annual|per year|a year|yearly/.test(q),monthly=/monthly|per month|a month/.test(q);
  if(['housing','health','other','tuition','startup'].includes(field)&&annual&&field!=='tuition'&&field!=='startup')value/=12;
  if(field==='salary'&&monthly)value*=12;
  const targets=named.length?named:base;
  const lines=[];let changed=0;
  try{for(const r of targets){const p=r.p;
   if((field==='salary'&&p.type==='business')||(field==='tuition'&&p.type!=='school')||(['margin','reinvest','startup'].includes(field)&&p.type!=='business')){lines.push(p.name+': not applicable to this pathway type.');continue}
   const copy={...p,[field]:Math.max(0,Number(p[field]||0)+sign*value)};
   if(['margin','reinvest'].includes(field))copy[field]=Math.min(field==='reinvest'?99:100,copy[field]);
   const after=simulate(copy,p.type==='business'?'base':$('scenario').value)[year],before=r.rows[year];changed++;
   lines.push(p.name+': '+fmt(before.nw)+' → '+fmt(after.nw)+' ('+(after.nw-before.nw>=0?'+':'')+fmt(after.nw-before.nw)+')'+(after.unfunded>.005?' · Unfunded expenses '+fmt(after.unfunded):''));
  }}catch(e){output.textContent=e.message==='HIGH_INCOME_QBI_DETAILS'?'This change needs advanced business tax details that the model does not collect.':'Could not calculate this change: '+e.message;return}
  output.textContent='TEMPORARY WHAT-IF · '+(down?'Decrease ':'Increase ')+field+' by '+(field==='margin'||field==='reinvest'?value+' percentage points':fmt(value))+'\nYear '+year+' personal net worth (original → changed):\n'+lines.join('\n')+(changed?'\n\nYour saved pathways have not changed.':'')+note;return;
 }
 if(/cross|overtake|break.?even|catch up|pass (?:the |another )?path/.test(q)){
  if(named.length===1){output.textContent='CROSSOVERS INVOLVING '+named[0].p.name+'\n'+crossPairs(base).filter(s=>s.startsWith(named[0].p.name+' vs ')||s.includes(' vs '+named[0].p.name+':')).join('\n')+'\n\nCrossovers are interpolated between annual values; they are not exact dates.'+note;return}
  const selected=named.length>=2?named:base;
  output.textContent='ALL PAIRWISE CROSSOVERS ('+selected.length+' pathways)\n'+crossPairs(selected).join('\n')+'\n\nA crossover is when two modeled personal-net-worth trajectories change order. Equal starting values do not count as a later crossover. Times are interpolated between annual snapshots.'+note;return;
 }
 if(/leader|lead each|each year|when.*highest/.test(q)){
  const lines=[];let previous='';for(let y=0;y<=10;y++){const ranked=[...base].sort((a,b)=>b.rows[y].nw-a.rows[y].nw),winner=ranked[0].p.name;if(y===0||winner!==previous||y===10)lines.push('Year '+y+': '+winner+' ('+fmt(ranked[0].rows[y].nw)+')');previous=winner}
  output.textContent='MODELED LEADERSHIP CHANGES\n'+lines.join('\n')+'\n\nShown at annual checkpoints; another pathway could briefly lead between checkpoints.'+note;return;
 }
 if(/funding|shortfall|afford|unfunded|missed payment|risk/.test(q)){
  output.textContent='FUNDING & AFFORDABILITY CHECK\n'+base.map(r=>{const peak=r.rows.reduce((a,z)=>z.unfunded>a.amount?{amount:z.unfunded,year:z.year}:a,{amount:0,year:0});return r.p.name+': peak year-end unfunded expenses '+fmt(peak.amount)+(peak.amount? ' (Year '+peak.year+')':'')+'; missed required loan payments '+fmt(r.rows[10].missedMinimum||0)}).join('\n')+'\n\nUnfunded expenses are NOT approved financing and may make a pathway infeasible. Year-end snapshots can miss intra-year peaks.'+note;return;
 }
 if(/debt|loan|owe|borrow/.test(q)){output.textContent='YEAR '+year+' REMAINING LOANS AND UNFUNDED EXPENSES\n'+base.map(r=>r.p.name+': loans '+fmt(r.rows[year].debt)+' + unfunded '+fmt(r.rows[year].unfunded)+' = '+fmt(r.rows[year].debt+r.rows[year].unfunded)).join('\n')+note;return}
 if(/tax|income|revenue|living expense|expense breakdown/.test(q)){
  output.textContent='YEAR '+year+' CASH-FLOW SNAPSHOT\n'+base.map(r=>r.p.name+': income '+fmt(r.rows[year].income||0)+'; taxes '+fmt(r.rows[year].taxes||0)+'; living costs '+fmt(r.rows[year].living||0)+(r.p.type==='business'?'; conditional revenue '+fmt(r.rows[year].revenue||0):'')).join('\n')+'\n\nThese are annual estimates, not take-home pay or a detailed tax return.'+note;return;
 }
 if(/net worth|best|highest|more money|wealth|compare|winning|rich|save|rank/.test(q)){
  const sorted=[...base].sort((a,b)=>b.rows[year].nw-a.rows[year].nw);
  output.textContent='YEAR '+year+' MODELED PERSONAL NET WORTH\n'+sorted.map((r,i)=>(i+1)+'. '+r.p.name+': '+fmt(r.rows[year].nw)+(r.p.type==='business'?' (conditional goal)':'')).join('\n')+'\n\nLeader: '+sorted[0].p.name+'. Gap between first and second: '+fmt(sorted[0].rows[year].nw-sorted[1].rows[year].nw)+note;return;
 }
 output.textContent='I can explain: rankings, all pairwise crossovers, leadership by year, loans, funding gaps, cash flow, and temporary changes to rent, living costs, salary, tuition, startup costs, operating margin and reinvestment. Try “What salary would Sales need to match Worker in Year 10?” or use a button above. This is an offline rule-based assistant, not a general AI chatbot.';
}

try{if(localStorage.getItem('compare-my-futures-v1'))$('cmfResume').style.display='inline-block'}catch(e){}
</script></div></body></html>

Reaches out to

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

  • www.huduser.gov
  • www.fns.usda.gov
  • www.bls.gov

Licence

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

Copyright © 2026 Anthony Adduci. 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.