import SwiftUI

struct PageListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @Binding
    private var selectedPage: Page?

    @State
    private var searchString = ""

    init(selectedPage: Binding<Page?>) {
        self._selectedPage = selectedPage
    }

    private var filteredPages: [Page] {
        guard !searchString.isEmpty else {
            return content.pages
        }
        return content.pages.filter { $0.localized(in: language).title.contains(searchString) }
    }

    var body: some View {
        VStack {
            TextField("", text: $searchString, prompt: Text("Search"))
                .textFieldStyle(.roundedBorder)
                .padding(.horizontal, 8)
            List(filteredPages, selection: $selectedPage) { page in
                Text(page.localized(in: language).title).tag(page)
            }
        }
        .onAppear {
            if selectedPage == nil {
                selectedPage = content.pages.first
            }
        }
    }
}

#Preview {
    PageListView(selectedPage: .constant(nil))
        .environmentObject(Content.mock)
}
