import SwiftUI

// A reusable component to handle optional strings with a TextField
struct OptionalTextField: View {

    let titleKey: LocalizedStringKey

    // The optional text that will be passed in and out of the component
    @Binding var text: String?

    let prompt: String?

    init(_ titleKey: LocalizedStringKey, text: Binding<String?>, prompt: String? = nil) {
        self.titleKey = titleKey
        self._text = text
        self.prompt = prompt
    }

    var body: some View {
        TextField(titleKey, text: Binding(
            get: {
                // Convert `nil` to an empty string for display
                text ?? ""
            },
            set: { newValue in
                // Convert an empty string to `nil`
                text = newValue.isEmpty ? nil : newValue
            }
        ), prompt: prompt.map(Text.init))
    }
}
