import SwiftUI
import SharedModels
import SwiftData

struct BookChapterListView: View {
    let book: Book

    @Query private var allChapters: [BookChapter]

    init(book: Book) {
        self.book = book
        let slug = book.slug
        _allChapters = Query(
            filter: #Predicate<BookChapter> { $0.bookSlug == slug },
            sort: \BookChapter.number
        )
    }

    var body: some View {
        List {
            ForEach(allChapters) { chapter in
                NavigationLink(value: chapter) {
                    HStack(spacing: 12) {
                        Text("\(chapter.number)")
                            .font(.subheadline.weight(.bold).monospacedDigit())
                            .foregroundStyle(.secondary)
                            .frame(width: 32, alignment: .trailing)

                        VStack(alignment: .leading, spacing: 2) {
                            Text(chapter.title)
                                .font(.subheadline.weight(.medium))
                            Text("\(chapter.paragraphCount) paragraph\(chapter.paragraphCount == 1 ? "" : "s")")
                                .font(.caption2)
                                .foregroundStyle(.tertiary)
                        }
                    }
                }
            }
        }
        .navigationTitle(book.title.prefix(while: { $0 != ":" }).description)
        .navigationBarTitleDisplayMode(.inline)
    }
}
