import SwiftUI

struct TagListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @Binding
    var selectedTag: Tag?

    @State
    private var searchString = ""

    init(selectedTag: Binding<Tag?>) {
        _selectedTag = selectedTag
    }

    private var filteredTags: [Tag] {
        guard !searchString.isEmpty else {
            return content.tags
        }
        return content.tags.filter { $0.localized(in: language).name.contains(searchString) }
    }

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