File size: 62,282 Bytes
3f893e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
const root = document.querySelector('#app');
const modalRoot = document.querySelector('#modal-root');
const toast = document.querySelector('#toast');

const state = {
  data: null,
  month: null,
  panel: 'summary',
  summaryMode: 'planned',
  editingGroup: null,
  detailItem: null,
  mobilePanel: false,
};

const icons = {budget:'▤',transactions:'$',planning:'◷',learn:'◇',goals:'◎',roadmap:'⌁',insights:'▥',trusted:'♙',coaching:'□',feed:'▦',help:'?',settings:'⚙',signout:'⇥'};

function esc(value='') {
  return String(value).replace(/[&<>'"]/g, char => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[char]));
}

function money(value, whole=false) {
  return new Intl.NumberFormat('en-US', {style:'currency', currency:'USD', minimumFractionDigits:whole?0:2, maximumFractionDigits:whole?0:2}).format(Number(value || 0));
}

function mark() { return '<span class="brand-mark" aria-hidden="true"><i></i></span>'; }
function wordmark() { return `<a class="wordmark" href="/">${mark()}<span>EveryDollar</span></a>`; }

async function api(path, options={}) {
  const response = await fetch(path, {headers:{'Content-Type':'application/json', ...(options.headers||{})}, ...options});
  let payload = {};
  try { payload = await response.json(); } catch (_) {}
  if (!response.ok) throw new Error(payload.error || `Request failed (${response.status})`);
  return payload;
}

function showToast(message) {
  toast.textContent = message;
  toast.classList.add('show');
  window.clearTimeout(showToast.timer);
  showToast.timer = window.setTimeout(() => toast.classList.remove('show'), 2200);
}

function go(path) {
  history.pushState({}, '', path);
  state.editingGroup = null;
  state.detailItem = null;
  state.mobilePanel = false;
  render();
}

function marketingFooter(asset) {
  return `<footer class="ramsey-footer" id="footer"><div class="ed-container footer-grid"><img src="${asset}/ramsey-logo.svg" alt="Ramsey"><nav><a href="#top">Get Started</a><a href="#footer">Careers</a><a href="/app/help">Contact Us</a><a href="#footer">Newsletter</a><a href="#footer">Newsroom</a><a href="#footer">Ramsey Press</a><a href="#footer">About</a></nav><nav class="legal"><a href="/company/privacy-policy">Privacy Policy</a><a href="/company/terms-of-use">Terms of Use</a><a href="#footer">Accessibility</a><a href="#footer">Editorial Guidelines</a></nav><p>©2026 Lampo Licensing, LLC. All rights reserved.</p></div></footer>`;
}

const LEGAL_PAGES = {
  '/company/terms-of-use': {
    title: 'Terms of Use',
    intro: 'These terms describe how this local EveryDollar recreation may be used.',
    sections: [
      ['Acceptance of these terms', 'By creating an account or using the budgeting tools on this site you agree to these terms. This is an offline WebsiteBench recreation, so no agreement is formed with Ramsey Solutions or Lampo Licensing, LLC.'],
      ['Your account', 'You are responsible for the credentials you create here. Accounts, budgets, transactions and goals live only in this local database and are never transmitted anywhere.'],
      ['Acceptable use', 'Do not attempt to use this recreation to reach the live EveryDollar service, and do not enter real banking credentials, card numbers or other sensitive personal data.'],
      ['No financial advice', 'Budget totals, insights and goal projections shown here are illustrative only and are not financial, tax or legal advice.'],
      ['Changes', 'These terms may be updated as the recreation changes. Continued use after an update means you accept the revised terms.'],
    ],
  },
  '/company/privacy-policy': {
    title: 'Privacy Policy',
    intro: 'This policy explains what this local EveryDollar recreation stores and what it never collects.',
    sections: [
      ['What we store', 'Your display name, email address, password hash, budget items, transactions, goals and notification preferences are written to a SQLite database on the machine running this site.'],
      ['What we never collect', 'No bank credentials, account numbers, card details or government identifiers are requested or accepted anywhere in this recreation.'],
      ['No third parties', 'Nothing is shared with Ramsey Solutions, advertisers or analytics providers. The site makes no outbound network requests at runtime.'],
      ['Email', 'Password recovery and account verification are previewed locally. No message is ever sent to any address you enter.'],
      ['Deleting your data', 'Removing the local database file erases every account, budget and transaction created here.'],
    ],
  },
};

function legalPage(pathname) {
  const asset = '/static/assets/everydollar-2026';
  const page = LEGAL_PAGES[pathname];
  root.innerHTML = `<main class="marketing ed-site legal-page">
    <header class="ramsey-masthead"><div class="masthead-top ed-container"><a class="ramsey-home" href="/money/everydollar" aria-label="Ramsey home"><img src="${asset}/ramsey-logo.svg" alt="Ramsey"></a><a class="masthead-signin" href="/app/sign-in">Sign In</a></div></header>
    <section class="legal-body"><div class="ed-container"><p class="legal-eyebrow">RAMSEY SOLUTIONS</p><h1>${esc(page.title)}</h1><p class="legal-intro">${esc(page.intro)}</p><p class="legal-updated">Last updated August 2026</p>
    ${page.sections.map(([heading, copy]) => `<section><h2>${esc(heading)}</h2><p>${esc(copy)}</p></section>`).join('')}
    <div class="legal-links"><a href="/company/terms-of-use">Terms of Use</a><a href="/company/privacy-policy">Privacy Policy</a><a href="/app/sign-up">Back to sign up</a><a href="/money/everydollar">Back to EveryDollar</a></div></div></section>
    ${marketingFooter(asset)}
  </main>`;
}

function marketingPage() {
  const asset = '/static/assets/everydollar-2026';
  root.innerHTML = `<main class="marketing ed-site">
    <header class="ramsey-masthead">
      <div class="masthead-top ed-container"><a class="ramsey-home" href="#top" aria-label="Ramsey home"><img src="${asset}/ramsey-logo.svg" alt="Ramsey"></a><form class="masthead-search" data-site-search><span aria-hidden="true">⌕</span><input name="q" aria-label="Search Ramsey" placeholder="What are you looking for?"><button type="submit">Search</button></form><a class="masthead-signin" href="/app/sign-in">Sign In</a><button class="mobile-menu" type="button" aria-label="Open menu">☰</button></div>
      <nav class="ramsey-toolbar" aria-label="Ramsey navigation"><div class="ed-container toolbar-inner"><a href="#features">Money</a><a href="#features">Investing &amp; Retirement</a><a href="#features">Real Estate</a><a href="#features">Insurance</a><a href="#features">Life &amp; Career</a><a href="#stories">Shows</a><a href="#faq">Free Tools</a><a href="#footer">For Businesses</a><a href="#footer">Store</a></div></nav>
    </header>
    <nav class="everydollar-subnav" aria-label="EveryDollar navigation"><div class="ed-container subnav-inner"><a href="#top" class="ed-logo"><img src="${asset}/logo.svg" alt="EveryDollar"></a><div class="subnav-links"><a href="#method">Learn to Budget</a><a href="#features">Features</a><a href="#method">Gift</a></div><a class="ed-button" href="/app/sign-up">Start for Free</a></div></nav>
    <section class="ed-hero" id="top"><div class="ed-container hero-grid"><div class="hero-copy"><h1>Budgeting Meets<br>Simplicity</h1><p>EveryDollar is the easy-to-use zero-based budgeting app that helps you keep tabs on your money at a glance—anytime, anywhere</p><a class="ed-button ed-button-large" href="/app/sign-up">Create Your Free Account</a></div><div class="hero-visual"><img src="${asset}/hero-budget-app.png" alt="EveryDollar app on two phones showing budget screens"></div></div><div class="ed-container social-proof"><picture><source media="(max-width:560px)" srcset="${asset}/community-mobile.svg"><img src="${asset}/community-desktop.svg" alt="Millions of people are budgeting with EveryDollar"></picture><picture><source media="(max-width:560px)" srcset="${asset}/reviews-ratings-mobile.png"><img src="${asset}/reviews-ratings-desktop.png" alt="59,000 five-star ratings and featured publications"></picture></div></section>
    <section class="feature-story" id="features"><div class="ed-container"><h2>Tell Your Money Where to Go,<br>Instead of Wondering Where It Went</h2><article class="story-row"><div class="story-art"><img src="${asset}/unique-budget.png" alt="EveryDollar custom budget screen"></div><div class="story-copy"><h3>Create a Budget<br>That’s as Unique as You</h3><p>Whether you’re saving for a high-tech mermaid costume or stocking up on staycation snacks, EveryDollar makes it so easy to plan for it all. Customize your budget with unlimited categories!</p><a class="ed-button" href="/app/sign-up">Create Your Free Account</a></div></article><article class="story-row reverse"><div class="story-art"><img src="${asset}/track-transactions.png" alt="EveryDollar transaction tracking screen"></div><div class="story-copy"><h3>Track Your Transactions<br>Quickly and Easily</h3><p>Stream transaction updates from your bank to your budget. Check balances on the go and see upcoming expenses at a glance. EveryDollar keeps up so you can keep moving!</p><a class="ed-button" href="/app/sign-up">Create Your Free Account</a></div></article><article class="story-row"><div class="story-art"><img src="${asset}/bank-accounts.png" alt="EveryDollar financial accounts screen"></div><div class="story-copy"><h3>See All Your Financial<br>Accounts in One Place</h3><p>Streamline the way you manage your money by seeing all of your financial accounts conveniently in one place. No need to switch between different apps to stay on top of your finances.</p><a class="ed-button" href="/app/sign-up">Create Your Free Account</a></div></article></div></section>
    <section class="budgeter-proof"><picture><source media="(max-width:560px)" srcset="${asset}/budgeters-mobile.svg"><img class="budgeter-swoop" src="${asset}/budgeters-desktop.svg" alt="EveryDollar budgeters"></picture><div class="ed-container proof-grid"><div><img src="${asset}/moneybag.svg" alt=""><p>Uncover an extra<br><strong>$395 on average</strong></p></div><div><img src="${asset}/credit-card.svg" alt=""><p>Cut monthly<br><strong>expenses by 9%</strong></p></div><div><img src="${asset}/graph.svg" alt=""><p>Build better<br><strong>budgeting habits</strong></p></div></div></section>
    <section class="benefits-showcase"><div class="ed-container benefits-grid"><img class="benefits-device" src="${asset}/phone-tablet.png" alt="EveryDollar on a phone and tablet"><div class="benefits-copy"><picture><source media="(max-width:560px)" srcset="${asset}/benefits-mobile.svg"><img src="${asset}/benefits-desktop.svg" alt="Plan, track, connect, and make progress with EveryDollar"></picture><a class="ed-button ed-button-large" href="/app/sign-up">Create Your Free Account</a></div></div></section>
    <section class="method" id="method"><div class="ed-container"><h2>EveryDollar’s zero-based budgeting method helps you manage your money with confidence and ease.</h2><div class="method-grid"><article><img src="${asset}/gift.svg" alt=""><h3>GIVE</h3><p>Plan out your giving for the causes you care about.</p><a href="#give">More About Giving →</a></article><article><img src="${asset}/piggy-bank.svg" alt=""><h3>SAVE</h3><p>Get ahead of pop-up expenses by saving proactively.</p><a href="#save">More About Saving →</a></article><article><img src="${asset}/paycheck.svg" alt=""><h3>SPEND</h3><p>Earn the freedom to enjoy guilt-free spending.</p><a href="#spend">More About Spending →</a></article></div>
      <div class="method-detail"><article id="give"><h3>More About Giving</h3><p>Giving comes first in a zero-based budget. Create a Giving group, add the causes you support, and plan an amount for each one before you assign anything else. EveryDollar tracks what you have given this month so the plan stays honest.</p><a class="ed-button" href="/app/sign-up">Create Your Free Account</a></article>
      <article id="save"><h3>More About Saving</h3><p>Saving works best when every goal has a name. Add a budget item for your emergency fund, then use Goals to track a target amount and the month you want to hit it. Progress carries forward as you move between months.</p><a class="ed-button" href="/app/goals">See Goals</a></article>
      <article id="spend"><h3>More About Spending</h3><p>Once giving and saving are planned, the rest is yours to spend on purpose. Add transactions as they happen, assign each one to a budget item, and the Remaining column tells you exactly what is left in every category.</p><a class="ed-button" href="/app/budget">Open the Budget</a></article></div></div></section>
    <section class="testimonials" id="stories"><div class="ed-container"><h2>We love our budgeters! Here’s why they love EveryDollar:</h2><div class="testimonial-grid"><article><img src="${asset}/colby.png" alt="Colby D."><blockquote>“We thought it was going to take 12 months to pay off our debt. It only took six to seven. That gave us a reason to celebrate.”</blockquote><strong>Colby D.</strong><span>EveryDollar Budgeter</span></article><article><img src="${asset}/couple.png" alt="Francisco and Brishithe T."><blockquote>“We were losing like five grand a month on nonsense. Now, there’s so many doors that opened up that we don’t have to rely on anybody.”</blockquote><strong>Francisco and Brishithe T.</strong><span>EveryDollar Budgeters</span></article><article><img src="${asset}/woman.png" alt="Christina I."><blockquote>“I cried the first time we finished a month and actually had money left over. That had never happened before.”</blockquote><strong>Christina I.</strong><span>EveryDollar Budgeter</span></article></div></div></section>
    <section class="charge-section"><div class="ed-container charge-grid"><picture><source media="(max-width:560px)" srcset="${asset}/who-is-in-charge-mobile.svg"><img src="${asset}/who-is-in-charge.svg" alt="You tell your money who is in charge"></picture><img src="${asset}/budget-with-phone.png" alt="A debt-free couple and the EveryDollar app"></div></section>
    <section class="device-cta"><div class="ed-container"><img src="${asset}/devices.png" alt="EveryDollar app device icons"><h2>Anytime. Anywhere. Any Device.</h2><a class="ed-button ed-button-large" href="/app/sign-up">Create Your Free Account</a></div></section>
    <section class="faq-section" id="faq"><div class="ed-container faq-wrap"><h2>Frequently Asked Questions</h2><div class="faq-list"><details open><summary>What features should I look for in a budgeting app?</summary><div><p>Look for a budget app that makes it easy to plan your spending, track transactions, see what’s left to spend, set goals, stay on top of bills, share a budget with a partner, and stay motivated.</p></div></details><details><summary>Is EveryDollar free?</summary><div><p>EveryDollar has a free version you can use as long as you want. New users can also start a 14-day free trial of EveryDollar premium.</p></div></details><details><summary>What’s included in EveryDollar premium?</summary><div><p>Premium adds automatic bank transactions, personalized recommendations, debt payoff tracking, expert coaching, and weekly live training.</p></div></details><details><summary>Does EveryDollar connect to my bank and import transactions?</summary><div><p>Yes. With EveryDollar premium, bank connect pulls your transactions into your budget for you.</p></div></details><details><summary>Is EveryDollar good for couples or shared budgets?</summary><div><p>Yes. The household feature lets couples manage one budget together, even with separate sign-ins.</p></div></details><details><summary>What is zero-based budgeting and how does EveryDollar use it?</summary><div><p>Zero-based budgeting means planning where every dollar goes before you spend it, so income minus expenses equals zero.</p></div></details><details><summary>Can EveryDollar help with debt-payoff planning?</summary><div><p>Yes. EveryDollar helps you work the debt snowball method and track your progress.</p></div></details><details><summary>How much does EveryDollar cost?</summary><div><p>The free version costs nothing. Premium is available after a 14-day trial with monthly or annual billing.</p></div></details></div></div></section>
    ${marketingFooter(asset)}
  </main>`;
  root.querySelector('[data-site-search]')?.addEventListener('submit', event => { event.preventDefault(); const q=new FormData(event.currentTarget).get('q') || ''; go(`/app/help?q=${encodeURIComponent(q)}`); });
}

function previewMarkup() {
  return `<div class="app-preview" aria-label="EveryDollar budget preview"><div class="preview-toolbar"><i></i><i></i><i></i></div><div class="preview-shell"><aside class="preview-side">${mark()}<b>▤ Budget</b><span></span><span></span><span></span><span></span></aside><div class="preview-budget"><h3>January 2026⌄</h3><small style="color:#2fc56b">✓ It’s an EveryDollar budget!</small><div class="preview-card"><div class="preview-row"><strong>Income</strong><span>Planned</span><span>Received</span></div><div class="preview-row"><span>Paycheck 1</span><span>$2,500</span><span>$2,500</span></div><div class="preview-row"><span>Paycheck 2</span><span>$2,500</span><span>$0</span></div></div><div class="preview-card"><div class="preview-row"><strong>Housing</strong><span>Planned</span><span>Balance</span></div><div class="preview-row"><span>Mortgage / Rent</span><span>$1,500</span><span>$1,500</span></div><div class="preview-row"><span>Utilities</span><span>$250</span><span>$175</span></div></div></div><aside class="preview-summary"><strong>Summary</strong><div class="mini-donut"></div><small>Planned · Spent · Remaining</small></aside></div></div>`;
}

function authPage(mode) {
  const register = mode === 'sign-up';
  const recover = mode === 'forgot-password';
  const title = register ? 'Create your account' : recover ? 'Reset your password' : 'Welcome back';
  const intro = register ? 'Start telling every dollar where to go.' : recover ? 'Enter your email to preview the recovery flow.' : 'Sign in to continue to your budget.';
  root.innerHTML = `<main class="auth-shell"><section class="auth-visual"><div class="auth-quote">${mark()}<h2>Make progress with a plan for every dollar.</h2><p>A simple monthly budget helps you spend with confidence, save intentionally and stay focused on what matters.</p></div></section><section class="auth-panel">${wordmark()}<div class="auth-form"><h1>${title}</h1><p>${intro}</p><form id="auth-form">${register?'<div class="field"><label for="display-name">Full name</label><input id="display-name" name="display_name" autocomplete="name" required></div>':''}<div class="field"><label for="auth-email">Email address</label><input id="auth-email" name="email" type="email" autocomplete="email" required></div>${recover?'':`<div class="field"><label for="auth-password">Password</label><input id="auth-password" name="password" type="password" autocomplete="${register?'new-password':'current-password'}" minlength="8" required></div>`}${register?'<label class="auth-terms"><input type="checkbox" name="terms" required> I agree to the <a href="/company/terms-of-use">Terms of Use</a> and <a href="/company/privacy-policy">Privacy Policy</a>. Your email address is verified locally—this site never sends mail.</label>':''}<div class="form-error" id="auth-error"></div><button class="btn" type="submit">${register?'Create Account':recover?'Continue':'Sign In'}</button></form><div class="auth-links">${register?'<a href="/app/sign-in">Already have an account?</a>':recover?'<a href="/app/sign-in">Back to Sign In</a>':'<a href="/app/sign-up">Create Account</a><a href="/app/forgot-password">Forgot Password?</a>'}</div><p class="offline-note">This is an isolated local recreation. It never sends email or contacts EveryDollar.</p></div></section></main>`;
}

const PREMIUM_NAV = new Set(['roadmap','planning','insights']);

function sidebar(active='budget') {
  const main = [['budget','Budget','/app/budget'],['goals','Goals','/app/goals'],['roadmap','Roadmap','/app/roadmap'],['planning','Paycheck Planning','/app/paycheck-planning'],['insights','Insights','/app/insights'],['learn','Learn to Budget','/app/learn'],['trusted','RamseyTrusted','/app/localproviders'],['coaching','Coaching','/app/coaching']];
  const lower = [['feed','My Feed','/app/my-feed'],['help','Help Center','/app/help'],['settings','Settings','/app/settings'],['signout','Sign out','/app/sign-out']];
  const links = list => list.map(([id,label,path]) => `<a class="nav-link ${active===id?'active':''} ${PREMIUM_NAV.has(id)?'premium':''}" href="${path}" data-nav-id="${id}"><span>${icons[id]}</span><span>${label}</span>${PREMIUM_NAV.has(id)?'<span class="premium-spark" title="Premium feature" aria-label="premium">✦</span>':''}${id==='coaching'?'<span class="ext-mark" aria-hidden="true">↗</span>':''}</a>`).join('');
  const account = state.data?.account;
  const display = account?.display_name || 'Local Budgeter';
  const email = account?.email_normalized || 'Preview mode';
  return `<aside class="app-sidebar">${mark()}<nav class="nav-section">${links(main)}</nav><div class="nav-spacer"></div><nav class="nav-section">${links(lower)}</nav><div class="account-chip"><span class="avatar">${esc(display).slice(0,2).toUpperCase()}</span><div><strong>${esc(display)}</strong><small>${esc(email)}</small></div></div></aside>`;
}

async function loadData(month=state.month) {
  const query = month ? `?month=${encodeURIComponent(month)}` : '';
  state.data = await api(`/api/bootstrap${query}`);
  state.month = state.data.month;
  return state.data;
}

function monthLabel(month) {
  const [year, m] = month.split('-').map(Number);
  return new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric',timeZone:'UTC'}).format(new Date(Date.UTC(year,m-1,1)));
}

function shiftMonth(month, delta) {
  const [year,m] = month.split('-').map(Number);
  const value = new Date(Date.UTC(year,m-1+delta,1));
  return `${value.getUTCFullYear()}-${String(value.getUTCMonth()+1).padStart(2,'0')}`;
}

function statusMarkup(summary) {
  const left = Number(summary.left_to_budget);
  if (Math.abs(left) < .005) return '<div class="budget-status">✓ <strong>It’s an EveryDollar Budget!</strong></div>';
  if (left > 0) return `<div class="budget-status warn">● <strong>${money(left)} left to budget</strong></div>`;
  return `<div class="budget-status warn">! <strong>${money(Math.abs(left))} over budget</strong></div>`;
}

function groupMarkup(group) {
  const income = group.name === 'Income';
  const actualLabel = income ? 'Received' : 'Remaining';
  const items = group.items.map(item => `<div class="budget-row" data-item-row="${item.id}"><button class="item-name" data-open-item="${item.id}">${item.favorite?'★ ':''}${esc(item.label)}</button><label class="money-input-wrap"><span>$</span><input class="money-input" type="number" min="0" step="0.01" value="${Number(item.planned).toFixed(2)}" aria-label="Planned amount for ${esc(item.label)}" data-planned-item="${item.id}"></label><span class="${income?'actual-value':'remaining-value'}">${money(income?item.actual:item.remaining,state.data.preferences.whole_numbers)}</span></div>`).join('');
  const editing = state.editingGroup === group.name ? `<form class="inline-editor" data-new-item-form="${esc(group.name)}"><input name="label" aria-label="New ${income?'income':'budget'} item name" placeholder="${income?'Income source':'Label'}" required autofocus><input class="planned-new" name="planned" type="number" min="0" step="0.01" aria-label="Planned amount" placeholder="$0.00" required><button class="btn" type="submit">Add</button></form>` : '';
  return `<section class="budget-card" style="--group-color:${group.color}" data-group="${esc(group.name)}"><header class="group-head"><div class="group-title"><span class="group-dot"></span><strong>${esc(group.name)}${income?` <span style="font-weight:400">for ${monthLabel(state.month).split(' ')[0]}</span>`:''}</strong><button class="collapse" aria-label="Collapse ${esc(group.name)}">⌃</button></div><span class="column-label">Planned</span><span class="column-label">${actualLabel}</span></header>${items || '<div class="empty-group">No budget items yet.</div>'}${editing}<div class="group-total"><button class="add-item" data-add-item="${esc(group.name)}">⊕ ${income?'Add Income':'Add Item'}</button><span style="text-align:right">${money(group.planned,state.data.preferences.whole_numbers)}</span><span style="text-align:right">${money(income?group.actual:group.remaining,state.data.preferences.whole_numbers)}</span></div></section>`;
}

function summaryPanel() {
  const summary = state.data.summary;
  const expenseGroups = state.data.groups.filter(group => group.name !== 'Income' && group.planned > 0);
  const total = Math.max(1, summary.planned);
  let cursor = 0;
  const stops = expenseGroups.map(group => { const start=cursor; cursor += group.planned/total*360; return `${group.color} ${start}deg ${Math.min(360,cursor)}deg`; });
  const donut = stops.length ? `conic-gradient(${stops.join(',')})` : '#e3e8ea';
  return `<div class="panel-content"><div class="summary-donut" style="background:${donut}"><div class="donut-copy"><small>INCOME</small><strong>${money(summary.income,true)}</strong></div></div><div class="summary-switch"><button class="${state.summaryMode==='planned'?'active':''}" data-summary-mode="planned">PLANNED</button><button class="${state.summaryMode==='spent'?'active':''}" data-summary-mode="spent">SPENT</button><button class="${state.summaryMode==='remaining'?'active':''}" data-summary-mode="remaining">REMAINING</button></div>${expenseGroups.map(group => { const value = state.summaryMode==='planned'?group.planned:state.summaryMode==='spent'?group.actual:group.remaining; const pct = summary.planned ? Math.round(group.planned/summary.planned*100):0; return `<div class="summary-line" style="--line-color:${group.color}"><i></i><strong>${esc(group.name)}</strong><span>${money(value,state.data.preferences.whole_numbers)}</span><small>(${pct}%)</small></div>`; }).join('') || '<div class="transaction-empty">Add planned expenses to build your summary.</div>'}<div class="summary-total"><span>Left to Budget</span><strong>${money(summary.left_to_budget)}</strong></div></div>`;
}

function transactionsPanel() {
  const rows = state.data.transactions;
  return `<div class="panel-content"><h2>Transactions</h2>${rows.length?`<div class="transaction-list">${rows.map(row=>`<article class="transaction-card"><div><strong>${esc(row.merchant)}</strong><strong style="color:${row.kind==='income'?'#2fc56b':'#1f292e'}">${row.kind==='income'?'+':'−'}${money(row.amount)}</strong></div><small>${esc(row.date)} · ${esc(row.account_name)}${row.item_id?' · Tracked':''}</small><br><button class="text-button" data-edit-transaction="${row.id}">Edit</button> · <button class="text-button" data-delete-transaction="${row.id}">Delete</button></article>`).join('')}</div>`:'<div class="transaction-empty"><div style="font-size:46px">↔</div><h3>No transactions yet</h3><p>Add an expense or income transaction and assign it to a budget item.</p></div>'}<button class="floating-add" data-open-transaction aria-label="Add transaction">+</button></div>`;
}

function accountsPanel() {
  return `<div class="panel-content accounts-preview"><div class="bank-graphic">▣</div><h2>Connect your accounts</h2><p>EveryDollar Premium can stream bank transactions into your budget. In this offline recreation, you can inspect the choices without entering bank credentials.</p><button class="btn" data-open-bank>View Connection Options</button><p class="offline-note">No account numbers, credentials or external connection will be requested.</p></div>`;
}

function itemPanel(item) {
  return `<div class="panel-content"><div class="item-detail-head"><button data-close-item aria-label="Back">←</button><button data-toggle-favorite="${item.id}" aria-label="Favorite">${item.favorite?'★':'☆'}</button></div><div class="balance-box"><strong>${money(item.remaining)}</strong><span>Remaining</span></div><label class="field"><span>Budget item name</span><input data-item-label="${item.id}" value="${esc(item.label)}"></label><div class="detail-stats"><div><small>PLANNED</small><strong>${money(item.planned)}</strong></div><div><small>SPENT</small><strong>${money(item.actual)}</strong></div><div><small>REMAINING</small><strong>${money(item.remaining)}</strong></div></div><div class="detail-actions"><button data-open-transaction="${item.id}">⊕ Add Transaction</button><button data-move-item="${item.id}" data-direction="up">↑ Move Up</button><button data-move-item="${item.id}" data-direction="down">↓ Move Down</button><button disabled title="Unavailable in this local preview">▣ Set Due Date (unavailable)</button><button disabled title="Unavailable in this local preview">◎ Make This a Fund (unavailable)</button></div><div class="field detail-notes"><label>Notes</label><textarea data-item-notes="${item.id}" rows="4" placeholder="Add a note">${esc(item.notes)}</textarea></div><button class="text-button" style="margin-top:24px;color:#b42318" data-delete-item="${item.id}">Delete Budget Item</button></div>`;
}

function rightPanel() {
  let content;
  const item = state.detailItem && state.data.groups.flatMap(group=>group.items).find(candidate=>candidate.id===state.detailItem);
  if (item) content = itemPanel(item);
  else if (state.panel === 'transactions') content = transactionsPanel();
  else if (state.panel === 'accounts') content = accountsPanel();
  else content = summaryPanel();
  return `<aside class="right-panel ${state.mobilePanel?'mobile-open':''}"><nav class="panel-tabs"><button class="panel-tab ${state.panel==='summary'&&!item?'active':''}" data-panel="summary"><span>◉</span>Summary</button><button class="panel-tab ${state.panel==='transactions'&&!item?'active':''}" data-panel="transactions"><span>$</span>Transactions</button><button class="panel-tab ${state.panel==='accounts'&&!item?'active':''}" data-panel="accounts"><span>▣</span>Accounts</button></nav>${content}</aside>`;
}

function budgetPage() {
  const summary = state.data.summary;
  root.innerHTML = `<main class="budget-app">${sidebar('budget')}<section class="budget-main"><header class="budget-header"><div><div class="month-control"><button class="icon-button" data-month-shift="-1" aria-label="Previous month">‹</button><h1>${monthLabel(state.month)}</h1><button class="icon-button" data-month-shift="1" aria-label="Next month">›</button></div>${statusMarkup(summary)}</div><div class="month-actions"><button data-copy-prior>Copy Last Month</button><button data-open-transaction>+ Transaction</button></div></header>${state.data.groups.map(groupMarkup).join('')}<button class="add-group" data-add-custom>+ Add Group</button><div class="budget-footer-actions"><button class="text-button" data-copy-prior>Copy Last Month</button><button class="text-button" disabled title="Unavailable in this local preview">Download as CSV (unavailable)</button></div></section>${rightPanel()}<button class="mobile-panel-button" data-mobile-panel aria-label="Open summary">◉</button></main>`;
}

function transactionModal(defaultItem='', transaction=null) {
  const items = state.data.groups.flatMap(group=>group.items.map(item=>({...item,group:group.name})));
  const kind=transaction?.kind || 'expense', selected=transaction?.item_id || defaultItem;
  modalRoot.innerHTML = `<div class="modal-scrim" data-close-modal><section class="modal" role="dialog" aria-modal="true" aria-labelledby="transaction-title"><header class="modal-head"><h2 id="transaction-title">${transaction?'Edit':'Add'} ${kind==='income'?'Income':'Expense'}</h2><button class="modal-close" data-close-modal aria-label="Close">×</button></header><div class="modal-body"><form class="modal-form" id="transaction-form" data-transaction-id="${transaction?.id||''}"><div class="type-tabs"><button type="button" class="${kind==='expense'?'active':''}" data-transaction-kind="expense">− &nbsp; Expense</button><button type="button" class="${kind==='income'?'active':''}" data-transaction-kind="income">+ &nbsp; Income</button></div><input type="hidden" name="kind" value="${kind}"><div class="field"><label for="transaction-amount">Amount</label><input id="transaction-amount" name="amount" type="number" min="0.01" step="0.01" value="${transaction?.amount||''}" placeholder="$0.00" required autofocus></div><div style="display:grid;grid-template-columns:185px 1fr;gap:12px"><div class="field"><label for="transaction-date">Date</label><input id="transaction-date" name="date" type="date" value="${transaction?.date||(state.month===new Date().toISOString().slice(0,7)?new Date().toISOString().slice(0,10):state.month+'-01')}" required></div><div class="field"><label for="transaction-merchant">Merchant</label><input id="transaction-merchant" name="merchant" value="${esc(transaction?.merchant||'')}" placeholder="Where did you spend this money?" required></div></div><div class="field"><label for="transaction-account">Account</label><select id="transaction-account" name="account_name"><option ${transaction?.account_name==='Cash'?'selected':''}>Cash</option><option ${transaction?.account_name==='Checking (manual)'?'selected':''}>Checking (manual)</option><option ${transaction?.account_name==='Credit Card (manual)'?'selected':''}>Credit Card (manual)</option></select></div><div class="field"><label for="transaction-item">Budget Items</label><select id="transaction-item" name="item_id"><option value="">Choose Budget Item(s)</option>${items.map(item=>`<option value="${item.id}" ${item.id===selected?'selected':''}>${esc(item.group)} · ${esc(item.label)}</option>`).join('')}</select></div><button type="button" class="text-button" style="text-align:left" disabled title="Unavailable in this local preview">More Options (unavailable)</button><div class="form-error" id="modal-error"></div><div class="modal-actions"><button type="button" class="text-button" data-close-modal>Cancel</button><button class="btn" type="submit">${transaction?'Save':'Add'} ${kind==='income'?'Income':'Expense'}</button></div></form></div></section></div>`;
}

function customItemModal() {
  modalRoot.innerHTML = `<div class="modal-scrim" data-close-modal><section class="modal" role="dialog" aria-modal="true"><header class="modal-head"><h2>Add Budget Item</h2><button class="modal-close" data-close-modal>×</button></header><div class="modal-body"><form class="modal-form" id="custom-item-form"><div class="field"><label>Budget Group</label><input name="group" placeholder="Group name" required></div><div class="field"><label>Budget Item</label><input name="label" placeholder="Item name" required></div><div class="field"><label>Planned</label><input name="planned" type="number" min="0" step="0.01" placeholder="$0.00" required></div><div class="form-error" id="modal-error"></div><div class="modal-actions"><button type="button" class="text-button" data-close-modal>Cancel</button><button class="btn" type="submit">Add Item</button></div></form></div></section></div>`;
}

function bankModal() {
  modalRoot.innerHTML = `<div class="modal-scrim" data-close-modal><section class="modal" role="dialog" aria-modal="true"><header class="modal-head"><h2>Connect an Account</h2><button class="modal-close" data-close-modal>×</button></header><div class="modal-body"><div class="notice">Inspection-only local preview—no bank connection will be started.</div><h3>Choose a connection option</h3><div class="bank-options"><button class="bank-option" data-preview-bank><strong>Bank Connect</strong><small>Stream transactions automatically with EveryDollar Premium</small></button><button class="bank-option" data-preview-bank><strong>Add a manual account</strong><small>Track a checking, savings or credit account by hand</small></button></div><div class="form-error" id="modal-error"></div><div class="modal-actions"><button class="btn secondary" data-close-modal>Close</button></div></div></section></div>`;
}

function pageShell(active, content) {
  root.innerHTML = `<main class="content-page">${sidebar(active)}<section class="content-page-main">${content}</section></main>`;
}

function transactionsPage() {
  const rows = state.data.transactions;
  pageShell('transactions', `<header style="display:flex;justify-content:space-between;align-items:center"><div><h1>Transactions</h1><p>Track spending and income for ${monthLabel(state.month)}.</p></div><button class="btn" data-open-transaction>+ Add Transaction</button></header><section class="page-card"><div class="summary-switch"><button class="active">TRACKED</button><button disabled title="Unavailable in this local preview">NEW (unavailable)</button><button disabled title="Unavailable in this local preview">DELETED (unavailable)</button></div>${rows.length?rows.map(row=>`<article class="transaction-card"><div><strong>${esc(row.merchant)}</strong><strong>${row.kind==='income'?'+':'−'}${money(row.amount)}</strong></div><small>${esc(row.date)} · ${esc(row.account_name)}</small><br><button class="text-button" data-edit-transaction="${row.id}">Edit</button> · <button class="text-button" data-delete-transaction="${row.id}">Delete</button></article>`).join(''):'<div class="transaction-empty"><h2>No tracked transactions</h2><p>Add a manual transaction to begin tracking your budget.</p></div>'}</section>`);
}

function goalsPage() {
  pageShell('goals', `<h1>Goals</h1><p>Save toward what matters and track your progress.</p><section class="goal-grid">${state.data.goals.map(goal=>`<article class="goal-card"><small>TARGET ${esc(goal.target_month)}</small><h2>${esc(goal.label)}</h2><p><strong>${money(goal.saved)}</strong> of ${money(goal.target)}</p><div class="progress"><i style="width:${Math.min(100,goal.saved/goal.target*100)}%"></i></div><button class="text-button" data-goal-progress="${goal.id}">+ Add $50 progress</button></article>`).join('') || '<article class="goal-card"><h2>No goals yet</h2><p>Create a savings or debt goal to see it here.</p></article>'}</section><section class="page-card"><h2>Create a Goal</h2><form class="modal-form" id="goal-form"><div class="field"><label>Goal name</label><input name="label" placeholder="Emergency fund" required></div><div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px"><div class="field"><label>Target amount</label><input name="target" type="number" min="1" step=".01" required></div><div class="field"><label>Already saved</label><input name="saved" type="number" min="0" step=".01" value="0"></div><div class="field"><label>Target month</label><input name="target_month" type="month" value="${state.month}" required></div></div><div class="form-error" id="goal-error"></div><button class="btn" type="submit">Create Goal</button></form></section>`);
}

function insightsPage() {
  const summary = state.data.summary;
  const params = new URLSearchParams(location.search);
  const category = params.get('category') || '';
  const allGroups = state.data.groups.filter(group=>group.name!=='Income');
  const groups = category ? allGroups.filter(group=>group.name===category) : allGroups;
  pageShell('insights', `<h1>Insights</h1><p>Your ${monthLabel(state.month)} budget at a glance.</p><form class="report-filters" id="report-filters"><label>Month<input name="month" type="month" value="${state.month}"></label><label>Category<select name="category"><option value="">All categories</option>${allGroups.map(group=>`<option ${category===group.name?'selected':''}>${esc(group.name)}</option>`).join('')}</select></label><button class="btn">Apply Filters</button></form><section class="page-card insight-layout"><div><small>TOTAL INCOME</small><h2>${money(summary.income)}</h2><p>${money(summary.planned)} planned</p><p>${money(summary.spent)} spent</p><p>${money(summary.remaining)} remaining</p></div><div class="big-chart" aria-label="Planned amounts by group">${groups.map(group=>`<i title="${esc(group.name)} ${money(group.planned)}" style="height:${Math.max(5,group.planned/Math.max(1,...groups.map(x=>x.planned))*100)}%;background:${group.color}"></i>`).join('')}</div></section><section class="page-card"><h2>Budget Summary</h2>${groups.map(group=>`<div class="settings-row" data-report-category="${esc(group.name)}"><strong>${esc(group.name)}</strong><span>${money(group.planned)} planned · ${money(group.actual)} spent</span></div>`).join('') || '<p>No categories match this report filter.</p>'}</section>`);
}

function settingsPage() {
  const prefs = state.data.preferences;
  const account = state.data.account;
  pageShell('settings', `<h1>Settings</h1><section class="page-card"><h2>Profile</h2><p><strong>${esc(account?.display_name || 'Local Budgeter')}</strong><br>${esc(account?.email_normalized || 'Preview mode · Sign in to attach this budget to a local account')}</p>${account?'<button class="btn secondary" data-logout>Sign Out</button>':'<a class="btn" href="/app/sign-in">Sign In</a>'}</section><section class="page-card"><h2>Budget Preferences</h2>${[['reminders','Budget reminders'],['weekly_summary','Weekly summary'],['safe_to_spend','Safe to Spend'],['whole_numbers','Display whole numbers']].map(([key,label])=>`<div class="settings-row"><div><strong>${label}</strong><small style="display:block;color:#66767d">Saved only in this local EveryDollar site.</small></div><button class="switch ${prefs[key]?'on':''}" data-pref="${key}" aria-pressed="${prefs[key]}"></button></div>`).join('')}</section><section class="page-card"><h2>Subscription</h2><p>EveryDollar Free · Local benchmark preview</p><button class="btn secondary" data-preview-subscription>Manage Subscription</button><p class="offline-note">No payment details are collected and no subscription is changed.</p></section>`);
}

function helpPage() {
  const query = new URLSearchParams(location.search).get('q') || '';
  const topics = [
    ['Getting Started','Enter income, plan expenses and work toward a zero-based budget.'],
    ['Budget Items','Add, edit, reorder and track planned amounts within a group.'],
    ['Transactions','Add a manual expense or income and assign it to the right item.'],
    ['Account Access','Use the local sign-in, registration and no-send recovery pages.'],
    ['Monthly Budgets','Move between months and copy planned values forward.'],
    ['Contact Support','This offline recreation does not submit support requests.']
  ];
  const terms=query.toLowerCase().trim().split(/\s+/).filter(Boolean);
  const matches=topics.filter(row=>terms.every(term=>row.join(' ').toLowerCase().includes(term)));
  pageShell('help', `<h1>How can we help?</h1><form class="help-search" id="help-search"><input name="q" value="${esc(query)}" placeholder="Search EveryDollar help"><button class="btn">Search</button></form>${matches.length?`<section class="help-grid">${matches.map(([title,body])=>`<article><h2>${esc(title)}</h2><p>${esc(body)}</p></article>`).join('')}</section>`:`<section class="page-card"><h2>No results found</h2><p>No local help matched “${esc(query)}”. Try another budgeting topic.</p><a class="btn" href="/app/budget">Back to Budget</a></section>`}`);
}

function notFoundPage() {
  root.innerHTML = `<main class="content-page">${sidebar('')}<section class="content-page-main not-found"><h1>404</h1><h2>That page wandered off budget.</h2><p>Let’s get you back to telling every dollar where to go.</p><a class="btn" href="/app/budget">Return to Budget</a></section></main>`;
}

const TRIAL_BAR = `<section class="trial-bar"><strong>Try this premium feature&mdash;and more.</strong><button class="btn" data-preview-subscription>Start 14-Day Free Trial</button></section>`;

function premiumHead(id, label, heading, body) {
  return `<div class="feature-eyebrow"><span>${icons[id]}</span><b>${esc(label)}</b></div><span class="premium-pill">&#10022; Premium</span><h1 class="feature-h1">${esc(heading)}</h1><p class="feature-lede">${esc(body)}</p>`;
}

function roadmapPage() {
  pageShell('roadmap', `<section class="feature-page">${premiumHead('roadmap','Financial Roadmap','Get a plan for your entire money future.','From your starter emergency fund to millionaire status, see how your decisions today can pay off big in the future.')}<figure class="roadmap-figure" aria-label="Projected net worth roadmap"><div class="roadmap-steps">${[1,2,3,'3b',4,5,6,7].map((n,i)=>`<span class="step s${i}">${n}</span>`).join('')}</div><figcaption>Estimated Millionaire Year &middot; Projected Net Worth: <strong>$1.8 Million</strong></figcaption></figure>${TRIAL_BAR}</section>`);
}

function paycheckPlanningPage() {
  const quotes = [
    ['Paycheck planning has changed the way I view my spending on a week-by-week basis. It is super helpful to project and see where my finances are headed each month.','Brittany'],
    ['The paycheck planning feature is EXACTLY what I have been looking for. It allows me to plan and view a timeline of spending and what will be available at any given day of the month. Love it!','Terry'],
    ['Paycheck planning provides peace of mind knowing the exact money flow in our budget - exceptional tool for budgeting!','Michael']
  ];
  pageShell('planning', `<section class="feature-page">${premiumHead('planning','Paycheck Planning','Know when it is safe to spend throughout the month.','Set your pay and spending schedules, prepare for upcoming expenses, and know exactly how much money you have.')}<figure class="paycheck-figure" aria-label="Paycheck timeline preview"><ul><li class="pay">Paycheck<em>&#127881; Pay Day!</em></li><li>Mortgage</li><li>Groceries (1 of 2)</li><li class="today">AT&amp;T<em>Today</em></li></ul></figure><section class="quote-grid">${quotes.map(([q,who])=>`<article class="quote-card"><p>${esc(q)}</p><strong>${esc(who)}</strong><div class="stars" aria-label="5 out of 5 stars">&#9733;&#9733;&#9733;&#9733;&#9733;</div></article>`).join('')}</section>${TRIAL_BAR}</section>`);
}

function ramseyTrustedPage() {
  const popular = [
    ['Home &amp; Auto Insurance','Save big when you bundle home and auto insurance.'],
    ['Last Will &amp; Testament','Create your will online. No legal jargon. No hourly fees.'],
    ['Term Life Insurance','Term life insurance is the safest choice when it comes to protecting your family future.'],
    ['Investing &amp; Retirement','Get recommendations for up to five investing pros.']
  ];
  pageShell('trusted', `<section class="pros-page"><h1>Ramsey Pros</h1><p class="feature-lede">Top-notch service providers to help you navigate life big and small financial decisions. Fully vetted by our team.</p><h2 class="pros-h2">Start Here &#128075;</h2><article class="page-card featured-pro"><span class="featured-tag">&#9733; Featured</span><h3>Are You Covered With the Right Insurance?</h3><p>Take the Coverage Checkup for an action plan on what to keep, add or remove so you can feel confident in your coverage.</p><button class="btn" data-pro-checkup>Check Your Coverage</button></article><h2 class="pros-h2">Most Popular &#10024;</h2><section class="pros-grid">${popular.map(([t,d])=>`<article class="page-card"><h3>${t}</h3><p>${d}</p></article>`).join('')}</section></section>`);
}

function learnPage2() {
  const groups = [
    ['Welcome &#128075;','Let us go over some basics to get started.',[['How to Budget with EveryDollar','4 min'],['What is a Zero-Based Budget?','3 min'],['Building the Habit of Budgeting','3 min']]],
    ['Personalize Your Budget &#9999;&#65039;','Learn how to use EveryDollar to fit your needs.',[['How to Set Up Sinking Funds','1 min'],['Budgeting With Irregular Income','4 min'],['How to Set Up Due Dates with EveryDollar','1 min']]]
  ];
  const tips = [['How to Track Transactions','1 min'],['How to Use Sinking Funds','1 min'],['How to use Financial Roadmap','1 min'],['How to use Personal Goals','1 min'],['How to Budget an Irregular Income','2 min'],['How to Use Paycheck Planning','1 min']];
  pageShell('learn', `<section class="learn-page"><h1>Learn to Budget</h1>${groups.map(([t,d,rows])=>`<section class="page-card"><header class="learn-head"><div><h2>${t}</h2><p>${d}</p></div><span class="learn-count">0/${rows.length}</span></header>${rows.map(([n,m])=>`<button class="learn-row" data-lesson="${esc(n)}"><span>${esc(n)}</span><small>${m}</small></button>`).join('')}</section>`).join('')}<section class="learn-upsell"><span>&#10024; Customize your budget even more with premium.</span><button class="btn" data-preview-subscription>Start 14-Day Free Trial</button></section><section class="page-card"><h2>Quick Pro Tips</h2>${tips.map(([n,m])=>`<button class="learn-row" data-lesson="${esc(n)}"><span>${esc(n)}</span><small>${m}</small></button>`).join('')}</section></section>`);
}

function coachingPage() {
  const times = ['Sep 1, 12 PM CT','Sep 3, 12 PM CT','Sep 8, 12 PM CT','Sep 10, 12 PM CT','Sep 15, 12 PM CT'];
  pageShell('coaching', `<section class="coaching-page"><h1>Free Budget Help and EveryDollar Coaching</h1><p class="feature-lede">New to budgeting? Got questions about the app? You are in the right place. Join a free, live workshop and start feeling more confident budgeting with EveryDollar.</p><section class="page-card"><h2>Upcoming free workshops</h2><div class="session-grid">${times.map(t=>`<button class="session-chip" data-session="${esc(t)}">${esc(t)}</button>`).join('')}</div><button class="btn secondary" data-watch-recording>Watch a Recording</button></section><p class="offline-note">On the live site this control opens ramseysolutions.com. This offline recreation keeps the destination local and never contacts Ramsey.</p></section>`);
}

function myFeedPage() {
  pageShell('feed', `<section class="feed-page"><h1>My Feed</h1><section class="page-card"><h2>Surface not captured</h2><p>The live EveryDollar account menu exposes <strong>My Feed</strong>, but its contents could not be captured during source acquisition: an interstitial dialog blocked access on every attempt. This route exists so the navigation control resolves, and deliberately does not invent feed content.</p><a class="btn" href="/app/budget">Back to Budget</a></section></section>`);
}

async function render() {
  const path = location.pathname;
  modalRoot.innerHTML = '';
  if (path === '/app/sign-out') { try { await api('/api/auth/logout',{method:'POST',body:'{}'}); } catch (e) {} state.data=null; history.replaceState({},'','/money/everydollar'); marketingPage(); showToast('Signed out'); return; }
  if (path === '/' || path === '/money/everydollar') { marketingPage(); return; }
  if (LEGAL_PAGES[path]) { legalPage(path); return; }
  if (path === '/app/sign-in') { authPage('sign-in'); return; }
  if (path === '/app/sign-up') { authPage('sign-up'); return; }
  if (path === '/app/forgot-password') { authPage('forgot-password'); return; }
  if (path === '/app' || path === '/app/') { history.replaceState({},'', '/app/budget'); }
  const reportMonth = path === '/app/insights' ? new URLSearchParams(location.search).get('month') : null;
  try { await loadData(reportMonth || state.month); }
  catch (error) { root.innerHTML = `<main class="not-found"><h1>We hit a snag.</h1><p>${esc(error.message)}</p><button class="btn" data-retry>Try Again</button></main>`; return; }
  if (location.pathname === '/app/budget') budgetPage();
  else if (location.pathname === '/app/transactions') transactionsPage();
  else if (location.pathname === '/app/goals') goalsPage();
  else if (location.pathname === '/app/insights') insightsPage();
  else if (location.pathname === '/app/settings') settingsPage();
  else if (location.pathname === '/app/help') helpPage();
  else if (location.pathname === '/app/roadmap') roadmapPage();
  else if (location.pathname === '/app/paycheck-planning') paycheckPlanningPage();
  else if (location.pathname === '/app/localproviders') ramseyTrustedPage();
  else if (location.pathname === '/app/learn') learnPage2();
  else if (location.pathname === '/app/coaching') coachingPage();
  else if (location.pathname === '/app/my-feed') myFeedPage();
  else notFoundPage();
}

document.addEventListener('click', event => {
  const proCheck = event.target.closest('[data-pro-checkup]');
  if (proCheck) { showToast('The Coverage Checkup is not part of this offline recreation.'); return; }
  const watchRec = event.target.closest('[data-watch-recording]');
  if (watchRec) { showToast('No recording is streamed by this offline recreation.'); return; }
  const lesson = event.target.closest('[data-lesson]');
  if (lesson) { showToast(`“${lesson.dataset.lesson}” is catalogued here; lesson video is not included.`); return; }
  const session = event.target.closest('[data-session]');
  if (session) { showToast(`${session.dataset.session} — this recreation does not register you for workshops.`); return; }
});

document.addEventListener('click', async event => {
  const link = event.target.closest('a[href]');
  if (link && link.origin === location.origin && !link.hash) { event.preventDefault(); go(link.pathname + link.search); return; }
  if (event.target.closest('[data-retry]')) { render(); return; }
  const shift = event.target.closest('[data-month-shift]');
  if (shift) { state.month = shiftMonth(state.month, Number(shift.dataset.monthShift)); await loadData(state.month); budgetPage(); return; }
  const add = event.target.closest('[data-add-item]');
  if (add) { state.editingGroup = add.dataset.addItem; budgetPage(); document.querySelector('[data-new-item-form] input')?.focus(); return; }
  const planned = event.target.closest('[data-planned-item]');
  if (planned) return;
  const itemButton = event.target.closest('[data-open-item]');
  if (itemButton) { state.detailItem = itemButton.dataset.openItem; state.mobilePanel = true; budgetPage(); return; }
  if (event.target.closest('[data-close-item]')) { state.detailItem = null; budgetPage(); return; }
  const panel = event.target.closest('[data-panel]');
  if (panel) { state.panel = panel.dataset.panel; state.detailItem = null; state.mobilePanel = true; budgetPage(); return; }
  const summaryMode = event.target.closest('[data-summary-mode]');
  if (summaryMode) { state.summaryMode = summaryMode.dataset.summaryMode; budgetPage(); return; }
  const openTransaction = event.target.closest('[data-open-transaction]');
  if (openTransaction) { transactionModal(openTransaction.dataset.openTransaction || ''); return; }
  const editTransaction = event.target.closest('[data-edit-transaction]');
  if (editTransaction) { const row=state.data.transactions.find(item=>item.id===editTransaction.dataset.editTransaction); transactionModal(row?.item_id||'',row); return; }
  if (event.target.closest('[data-open-bank]')) { bankModal(); return; }
  if (event.target.closest('[data-add-custom]')) { customItemModal(); return; }
  if (event.target.matches('[data-close-modal]')) { modalRoot.innerHTML=''; return; }
  if (event.target.closest('[data-preview-bank]')) { document.querySelector('#modal-error').textContent='Connection preview complete. No external bank window was opened.'; return; }
  if (event.target.closest('[data-preview-subscription]')) { showToast('Subscription preview only—no payment action was taken.'); return; }
  const transactionKind = event.target.closest('[data-transaction-kind]');
  if (transactionKind) {
    document.querySelectorAll('[data-transaction-kind]').forEach(button=>button.classList.toggle('active',button===transactionKind));
    const form = document.querySelector('#transaction-form'); form.elements.kind.value=transactionKind.dataset.transactionKind;
    document.querySelector('#transaction-title').textContent = transactionKind.dataset.transactionKind==='income'?'Add Income':'Add Expense';
    form.querySelector('button[type=submit]').textContent = transactionKind.dataset.transactionKind==='income'?'Add Income':'Add Expense'; return;
  }
  const deleteTransaction = event.target.closest('[data-delete-transaction]');
  if (deleteTransaction) { if (confirm('Delete this transaction?')) { state.data=await api(`/api/transactions/${deleteTransaction.dataset.deleteTransaction}`,{method:'DELETE'}); showToast('Transaction deleted'); render(); } return; }
  const deleteItem = event.target.closest('[data-delete-item]');
  if (deleteItem) { if (confirm('Delete this budget item?')) { state.data=await api(`/api/budget/items/${deleteItem.dataset.deleteItem}`,{method:'DELETE'}); state.detailItem=null; showToast('Budget item deleted'); budgetPage(); } return; }
  const favorite = event.target.closest('[data-toggle-favorite]');
  if (favorite) { const item=state.data.groups.flatMap(g=>g.items).find(x=>x.id===favorite.dataset.toggleFavorite); state.data=await api(`/api/budget/items/${item.id}`,{method:'PATCH',body:JSON.stringify({favorite:!item.favorite})}); showToast(item.favorite?'Removed from favorites':'Added to favorites'); budgetPage(); return; }
  if (event.target.closest('[data-mobile-panel]')) { state.mobilePanel=true; budgetPage(); return; }
  const moveItem = event.target.closest('[data-move-item]');
  if (moveItem) { state.data=await api(`/api/budget/items/${moveItem.dataset.moveItem}/move`,{method:'POST',body:JSON.stringify({direction:moveItem.dataset.direction})}); showToast(`Budget item moved ${moveItem.dataset.direction}`); budgetPage(); return; }
  const goalProgress = event.target.closest('[data-goal-progress]');
  if (goalProgress) { const goal=state.data.goals.find(item=>item.id===goalProgress.dataset.goalProgress); state.data=await api(`/api/goals/${goal.id}`,{method:'PATCH',body:JSON.stringify({saved:goal.saved+50})}); showToast('Goal progress updated'); goalsPage(); return; }
  if (event.target.closest('[data-copy-prior]')) {
    const source=shiftMonth(state.month,-1); try { state.data=await api('/api/months/copy',{method:'POST',body:JSON.stringify({source,target:state.month})}); showToast(`Copied planned values from ${monthLabel(source)}`); budgetPage(); } catch(error){showToast(error.message)} return;
  }
  const pref = event.target.closest('[data-pref]');
  if (pref) { const next={...state.data.preferences,[pref.dataset.pref]:!state.data.preferences[pref.dataset.pref]}; state.data=await api('/api/preferences',{method:'POST',body:JSON.stringify(next)}); settingsPage(); showToast('Preference saved'); return; }
  if (event.target.closest('[data-logout]')) { await api('/api/auth/logout',{method:'POST',body:'{}'}); state.data=null; showToast('Signed out'); go('/app/sign-in'); }
});

document.addEventListener('change', async event => {
  const input = event.target.closest('[data-planned-item]');
  if (input) { try { state.data=await api(`/api/budget/items/${input.dataset.plannedItem}`,{method:'PATCH',body:JSON.stringify({planned:Number(input.value)})}); showToast('Planned amount saved'); budgetPage(); } catch(error){showToast(error.message)} return; }
  const notes = event.target.closest('[data-item-notes]');
  if (notes) { state.data=await api(`/api/budget/items/${notes.dataset.itemNotes}`,{method:'PATCH',body:JSON.stringify({notes:notes.value})}); showToast('Note saved'); }
  const label = event.target.closest('[data-item-label]');
  if (label) { state.data=await api(`/api/budget/items/${label.dataset.itemLabel}`,{method:'PATCH',body:JSON.stringify({label:label.value})}); showToast('Budget item renamed'); budgetPage(); }
});

document.addEventListener('submit', async event => {
  event.preventDefault();
  const form = event.target;
  if (form.id === 'auth-form') {
    const body=Object.fromEntries(new FormData(form)); const error=form.querySelector('#auth-error'); error.textContent='';
    const recover=location.pathname.endsWith('forgot-password'); const register=location.pathname.endsWith('sign-up');
    try { const result=await api(recover?'/api/auth/recovery-preview':register?'/api/auth/register':'/api/auth/login',{method:'POST',body:JSON.stringify(body)}); if(recover){error.style.color='#25834c';error.textContent=result.message}else{showToast(register?'Account created':'Signed in');go('/app/budget')}} catch(exc){error.textContent=exc.message} return;
  }
  if (form.matches('[data-new-item-form]')) {
    const body=Object.fromEntries(new FormData(form)); body.group=form.dataset.newItemForm; body.month=state.month;
    try { state.data=await api('/api/budget/items',{method:'POST',body:JSON.stringify(body)}); state.editingGroup=null; showToast(`${body.label} added`); budgetPage(); } catch(exc){showToast(exc.message)} return;
  }
  if (form.id === 'custom-item-form') {
    const body=Object.fromEntries(new FormData(form)); body.month=state.month;
    try { state.data=await api('/api/budget/items',{method:'POST',body:JSON.stringify(body)}); modalRoot.innerHTML=''; showToast(`${body.label} added`); budgetPage(); } catch(exc){form.querySelector('#modal-error').textContent=exc.message} return;
  }
  if (form.id === 'transaction-form') {
    const body=Object.fromEntries(new FormData(form)); body.month=state.month;
    const transactionId=form.dataset.transactionId;
    try { state.data=await api(transactionId?`/api/transactions/${transactionId}`:'/api/transactions',{method:transactionId?'PATCH':'POST',body:JSON.stringify(body)}); modalRoot.innerHTML=''; showToast(`${body.kind==='income'?'Income':'Expense'} ${transactionId?'updated':'added'}`); location.pathname==='/app/budget'?budgetPage():transactionsPage(); } catch(exc){form.querySelector('#modal-error').textContent=exc.message} return;
  }
  if (form.id === 'goal-form') {
    const body=Object.fromEntries(new FormData(form));
    try { state.data=await api('/api/goals',{method:'POST',body:JSON.stringify(body)}); showToast('Goal created'); goalsPage(); } catch(exc){form.querySelector('#goal-error').textContent=exc.message} return;
  }
  if (form.id === 'help-search') { const q=new FormData(form).get('q'); go(`/app/help?q=${encodeURIComponent(q)}`); }
  if (form.id === 'report-filters') { const data=new FormData(form); go(`/app/insights?${new URLSearchParams(data).toString()}`); }
});

window.addEventListener('popstate', render);
document.addEventListener('keydown', event => { if(event.key==='Escape' && modalRoot.innerHTML) modalRoot.innerHTML=''; });
render();