import SwiftUI

struct ChapterPickerView: View {

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

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

    @ViewBuilder
    private var content: some View {
        if viewModel.isLoading && viewModel.chapters.isEmpty {
            ProgressView("Loading chapters…")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
        } else {
            List {
                Button {
                    viewModel.selectedChapter = nil
                    dismiss()
                } label: {
                    HStack {
                        Text("No chapter (directly in book)")
                            .foregroundStyle(.primary)
                        Spacer()
                        if viewModel.selectedChapter == nil {
                            Image(systemName: "checkmark")
                                .foregroundStyle(Color.accentColor)
                        }
                    }
                }

                if viewModel.chapters.isEmpty {
                    Text("This book has no chapters.")
                        .foregroundStyle(.secondary)
                        .listRowBackground(Color.clear)
                } else {
                    ForEach(viewModel.chapters) { chapter in
                        Button {
                            viewModel.selectedChapter = chapter
                            dismiss()
                        } label: {
                            HStack {
                                Text(chapter.name)
                                    .foregroundStyle(.primary)
                                Spacer()
                                if viewModel.selectedChapter?.id == chapter.id {
                                    Image(systemName: "checkmark")
                                        .foregroundStyle(Color.accentColor)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
