import SwiftUI
import Models

struct SidebarView: View {
	@Bindable var viewModel: MailViewModel

	var body: some View {
		List {
			Section("Perspectives") {
				ForEach(Perspective.allCases) { perspective in
					Button {
						viewModel.loadPerspective(perspective)
					} label: {
						Label(perspective.label, systemImage: perspective.systemImage)
							.badge(viewModel.perspectiveCounts[perspective] ?? 0)
					}
					.buttonStyle(.plain)
					.listItemTint(viewModel.selectedPerspective == perspective ? .accentColor : nil)
					.fontWeight(viewModel.selectedPerspective == perspective ? .semibold : .regular)
				}
			}

			Section("Mailboxes") {
				ForEach(viewModel.mailboxes) { mailbox in
					Button {
						viewModel.selectedMailbox = mailbox
					} label: {
						Label(mailbox.name, systemImage: mailbox.systemImage)
							.badge(mailbox.unreadCount)
					}
					.buttonStyle(.plain)
				}
			}
		}
		.navigationTitle("Magnum Opus")
		.listStyle(.sidebar)
		.toolbar {
			ToolbarItem {
				Button {
					Task { await viewModel.syncNow() }
				} label: {
					switch viewModel.syncState {
					case .syncing:
						ProgressView()
							.controlSize(.small)
					default:
						Label("Sync", systemImage: "arrow.trianglehead.2.clockwise")
					}
				}
			}
		}
		.onAppear {
			viewModel.loadAllPerspectiveCounts()
		}
	}
}
