import SwiftUI

struct PostListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @Binding
    private var selectedPost: Post?

    @State
    private var searchString = ""

    init(selectedPost: Binding<Post?>) {
        self._selectedPost = selectedPost
    }

    private var filteredPosts: [Post] {
        guard !searchString.isEmpty else {
            return content.posts
        }
        return content.posts.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(filteredPosts, selection: $selectedPost) { post in
                Text(post.localized(in: language).title).tag(post)
            }
        }.onAppear {
            if selectedPost == nil {
                selectedPost = content.posts.first
            }
        }
    }
}
