import SwiftUI import BucksleyKit import BucksleyUI /// Whether the smart budget walkthrough is showing, so Ask Bucksley can open it on the Budgets screen. @MainActor @Observable final class SmartBudgetFlow { static let shared = SmartBudgetFlow() var presented = false var step = 0 func open() { step = 0; presented = true } } /// Four steps: your money at a glance and a savings goal, fixed bills, flexible spending, then review /// and create. Amounts start at Bucksley's recommendation; every one can be changed or left out. struct SmartBudgetWalkthrough: View { @Environment(AppModel.self) private var model @Environment(\.palette) private var palette @State private var flow = SmartBudgetFlow.shared @State private var savingsRate = 20 @State private var amounts: [String: Decimal] = [:] @State private var skipped: Set = [] static let steps = ["Your money", "Fixed bills", "Flexible spending", "Review"] var plan: SmartBudgetPlan { model.ledger.smartBudgetPlan(savingsRate: savingsRate) } var body: some View { let plan = plan VStack(alignment: .leading, spacing: 18) { stepper Group { switch flow.step { case 0: overview(plan) case 1: items(plan.fixedItems, title: "Fixed bills", note: "Spending you can't easily change, like rent, insurance and utilities. Each is budgeted at what you've spent lately and never cut. Wrong category here? Move it to flexible.") case 2: items(plan.flexible, title: "Flexible spending", note: "Set a little under what you've spent lately, so the budget nudges you down. Anything trimmed further for your savings goal says so. Can't change one? Mark it fixed.") default: review(plan) } } .frame(maxWidth: 760, alignment: .leading) navigation(plan) } } // MARK: Steps var stepper: some View { HStack(spacing: 8) { ForEach(Array(Self.steps.enumerated()), id: \.offset) { index, name in Button { flow.step = index } label: { HStack(spacing: 6) { Text("\(index + 1)").font(.system(size: 11, weight: .bold)).frame(width: 20, height: 20) .foregroundStyle(index <= flow.step ? palette.accentText : palette.muted) .background(index <= flow.step ? palette.accent : palette.card, in: Circle()) Text(name).font(.system(size: 12, weight: index == flow.step ? .semibold : .regular)) .foregroundStyle(index == flow.step ? palette.text : palette.muted) } } .buttonStyle(.plain) if index < Self.steps.count - 1 { Rectangle().fill(palette.line).frame(width: 24, height: 1) } } } } func overview(_ plan: SmartBudgetPlan) -> some View { VStack(alignment: .leading, spacing: 16) { HStack(spacing: 14) { Panel { stat("Recent income", plan.income, note: "a month") } Panel { stat("Recent spending", plan.typicalSpending, note: "a month, \(plan.items.count) categories") } Panel { stat("Savings goal", plan.savingsGoal, note: "\(plan.savingsRate)% of income") } } VStack(alignment: .leading, spacing: 8) { Text("How much of your income do you want to keep free each month?").font(.system(size: 13, weight: .semibold)) PillPicker([(10, "10%"), (15, "15%"), (20, "20%"), (25, "25%"), (30, "30%")], selection: $savingsRate) .fixedSize() .onChange(of: savingsRate) { amounts = [:] } } coach(plan.summary) } } func items(_ items: [SmartBudgetPlan.Item], title: String, note: String) -> some View { VStack(alignment: .leading, spacing: 12) { Text(note).font(.system(size: 13)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) if items.isEmpty { Text("Nothing here yet. Bucksley budgets categories you spend $10 or more in during a typical month.").font(.system(size: 13)).foregroundStyle(palette.muted) } ForEach(items) { item in row(item) } } } func row(_ item: SmartBudgetPlan.Item) -> some View { let included = !skipped.contains(item.categoryID) let category = model.workspace.category(item.categoryID) return HStack(alignment: .center, spacing: 14) { Button { if included { skipped.insert(item.categoryID) } else { skipped.remove(item.categoryID) } } label: { Image(systemName: included ? "checkmark.circle.fill" : "circle").font(.system(size: 18)) .foregroundStyle(included ? palette.accent : palette.muted) } .buttonStyle(.plain).accessibilityLabel(included ? "Leave out \(item.name)" : "Include \(item.name)") VStack(alignment: .leading, spacing: 4) { Text("\(category?.icon ?? "") \(item.name)").font(.system(size: 14, weight: .semibold)) Text(item.reason).font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) HStack(spacing: 10) { Button(item.fixed ? "Move to flexible" : "Mark as fixed") { setFixed(item, !item.fixed) } .buttonStyle(.plain).font(.system(size: 11, weight: .semibold)).foregroundStyle(palette.accent) if let current = item.current { Text("Your budget now: \(Money.format(current, cents: false))").font(.system(size: 11)).foregroundStyle(palette.muted) } } } Spacer(minLength: 12) HStack(spacing: 10) { Button { nudge(item, by: -1) } label: { Image(systemName: "minus").frame(width: 22, height: 22) } .buttonStyle(.plain).background(palette.canvas, in: Circle()).accessibilityLabel("Less") TextField("", value: amountBinding(item), format: .currency(code: "USD").precision(.fractionLength(0))) .textFieldStyle(.plain).font(palette.figure(15, weight: .semibold)).multilineTextAlignment(.center).frame(width: 84) Button { nudge(item, by: 1) } label: { Image(systemName: "plus").frame(width: 22, height: 22) } .buttonStyle(.plain).background(palette.canvas, in: Circle()).accessibilityLabel("More") } .opacity(included ? 1 : 0.4).disabled(!included) } .padding(14) .background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)) } func review(_ plan: SmartBudgetPlan) -> some View { let chosen = plan.items.filter { !skipped.contains($0.categoryID) } let total = chosen.reduce(Decimal(0)) { $0 + amount($1) } let left = plan.income - total return VStack(alignment: .leading, spacing: 16) { HStack(spacing: 14) { Panel { stat("Budgeted", total, note: "\(chosen.count) categories") } if plan.income > 0 { Panel { stat("Left each month", left, note: left >= plan.savingsGoal ? "meets your \(plan.savingsRate)% goal" : "\(Money.format(plan.savingsGoal - left, cents: false)) short of your goal") } } } VStack(alignment: .leading, spacing: 0) { ForEach(chosen) { item in HStack { Text("\(model.workspace.category(item.categoryID)?.icon ?? "") \(item.name)").font(.system(size: 13)) Spacer() MoneyText(amount(item), size: 13, cents: false) Text("/mo").font(.system(size: 11)).foregroundStyle(palette.muted) } .padding(.vertical, 8) Divider().opacity(0.5) } } .padding(.horizontal, 14).padding(.vertical, 6) .background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)) Text("Budgets you already have in other categories stay as they are. You can change any of these later on the Budgets screen.") .font(.system(size: 12)).foregroundStyle(palette.muted) } } func navigation(_ plan: SmartBudgetPlan) -> some View { let chosen = plan.items.filter { !skipped.contains($0.categoryID) } return HStack(spacing: 10) { Button("Cancel") { flow.presented = false }.buttonStyle(SecondaryButtonStyle()) Spacer() if flow.step > 0 { Button("Back") { flow.step -= 1 }.buttonStyle(SecondaryButtonStyle()) } if flow.step == 0 && !plan.items.isEmpty { Button("Use Bucksley's plan") { create(plan.items, plan) }.buttonStyle(SecondaryButtonStyle()) .help("Create every recommended budget now") } if flow.step < Self.steps.count - 1 { Button("Next") { flow.step += 1 }.buttonStyle(PrimaryButtonStyle()).disabled(plan.items.isEmpty) } else { Button("Create \(chosen.count) budget\(chosen.count == 1 ? "" : "s")") { create(chosen, plan) } .buttonStyle(PrimaryButtonStyle()).disabled(chosen.isEmpty) } } .frame(maxWidth: 760) } // MARK: Helpers func coach(_ text: String) -> some View { HStack(alignment: .top, spacing: 10) { Image(systemName: "sparkles").foregroundStyle(palette.accent) Text(text).font(palette.theme == .almanac ? .system(size: 14, design: .serif) : .system(size: 13)).fixedSize(horizontal: false, vertical: true) } .padding(14).frame(maxWidth: .infinity, alignment: .leading) .background(palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius)) } func stat(_ label: String, _ value: Decimal, note: String) -> some View { VStack(alignment: .leading, spacing: 4) { Text(label).font(.system(size: 12, weight: .medium)).foregroundStyle(palette.muted) MoneyText(value, size: 22, cents: false) Text(note).font(.system(size: 11)).foregroundStyle(palette.muted) } } /// Remembers the choice on the category, so the next plan and the budget suggestions follow it. func setFixed(_ item: SmartBudgetPlan.Item, _ fixed: Bool) { amounts[item.categoryID] = nil model.updateWorkspace { ws in if let i = ws.categories.firstIndex(where: { $0.id == item.categoryID }) { ws.categories[i].fixed = fixed } } } func amount(_ item: SmartBudgetPlan.Item) -> Decimal { amounts[item.categoryID] ?? item.recommended } func amountBinding(_ item: SmartBudgetPlan.Item) -> Binding { Binding(get: { amount(item) }, set: { amounts[item.categoryID] = max($0, 0) }) } /// Steps of $5 under $50, $10 under $200, $25 under $1,000, then $50. func nudge(_ item: SmartBudgetPlan.Item, by direction: Int) { let value = amount(item).double let step: Double = value < 50 ? 5 : value < 200 ? 10 : value < 1000 ? 25 : 50 amounts[item.categoryID] = Decimal(max(step, value + Double(direction) * step)) } func create(_ items: [SmartBudgetPlan.Item], _ plan: SmartBudgetPlan) { let chosen = items let values = Dictionary(uniqueKeysWithValues: chosen.map { ($0.categoryID, amount($0)) }) model.updateWorkspace { SmartBudgetPlan.apply(chosen, amounts: values, to: &$0) } SupportPrompt.recordCoreAction() flow.presented = false } }