import SwiftUI

struct ThreadListView: View {
	@Bindable var viewModel: MailViewModel

	var body: some View {
		List(viewModel.threads, selection: Binding(
			get: { viewModel.selectedThread?.threadId },
			set: { newId in
				if let thread = viewModel.threads.first(where: { $0.threadId == newId }) {
					Task { await viewModel.loadMessages(for: thread) }
				}
			}
		)) { thread in
			ThreadRow(thread: thread)
				.tag(thread.threadId)
		}
		.listStyle(.inset)
		.navigationTitle(viewModel.selectedPerspective.rawValue)
		.overlay {
			if viewModel.isLoading {
				ProgressView()
			} else if viewModel.threads.isEmpty {
				ContentUnavailableView(
					"No Messages",
					systemImage: "tray",
					description: Text("Inbox is empty")
				)
			}
		}
	}
}

struct ThreadRow: View {
	let thread: ThreadSummary

	var body: some View {
		VStack(alignment: .leading, spacing: 4) {
			HStack {
				Text(thread.authors)
					.fontWeight(thread.isUnread ? .bold : .regular)
					.lineLimit(1)
				Spacer()
				Text(thread.date, style: .relative)
					.font(.caption)
					.foregroundStyle(.secondary)
			}
			Text(thread.subject)
				.font(.subheadline)
				.lineLimit(1)
			if thread.totalMessages > 1 {
				Text("\(thread.totalMessages) messages")
					.font(.caption2)
					.foregroundStyle(.tertiary)
			}
		}
		.padding(.vertical, 2)
	}
}
