import SwiftUI
import Models

struct SidebarView: View {
	@Bindable var viewModel: MailViewModel

	var body: some View {
		List(selection: Binding(
			get: { viewModel.selectedMailbox?.id },
			set: { newId in
				viewModel.selectedMailbox = viewModel.mailboxes.first { $0.id == newId }
			}
		)) {
			Section("Mailboxes") {
				ForEach(viewModel.mailboxes) { mailbox in
					Label(mailbox.name, systemImage: mailbox.systemImage)
						.tag(mailbox.id)
						.badge(mailbox.unreadCount)
				}
			}
		}
		.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")
					}
				}
			}
		}
	}
}
