import SwiftUI

struct ShelfPickerView: View {

    @ObservedObject var viewModel: ShareViewModel
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        content
            .navigationTitle("Select Shelf")
            .navigationBarTitleDisplayMode(.inline)
    }

    @ViewBuilder
    private var content: some View {
        if viewModel.isLoading && viewModel.shelves.isEmpty {
            ProgressView("Loading shelves…")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
        } else if viewModel.shelves.isEmpty {
            ContentUnavailableView(
                "No shelves found",
                systemImage: "books.vertical",
                description: Text("No shelves were found on the server.")
            )
        } else {
            List(viewModel.shelves) { shelf in
                Button {
                    Task {
                        await viewModel.selectShelf(shelf)
                        dismiss()
                    }
                } label: {
                    HStack {
                        Text(shelf.name)
                            .foregroundStyle(.primary)
                        Spacer()
                        if viewModel.selectedShelf?.id == shelf.id {
                            Image(systemName: "checkmark")
                                .foregroundStyle(Color.accentColor)
                        }
                    }
                }
            }
        }
    }
}
