import SwiftUI
@preconcurrency import Translation

struct ContentView: View {
   @State private var textInput: String = ""
   @State private var configuration: TranslationSession.Configuration? = nil

   var body: some View {
      VStack {
         HStack {
            TextField("Insert Text", text: $textInput)
               .textFieldStyle(.roundedBorder)
            Button("Translate") {
               let text = textInput.trimmingCharacters(in: .whitespacesAndNewlines)
               if !text.isEmpty {
                  if configuration != nil {
                     configuration?.invalidate()
                  } else {
                     configuration = TranslationSession.Configuration()
                  }
               }
            }
            .buttonStyle(.borderedProminent)
         }
         Spacer()
      }
      .padding()
      .translationTask(configuration) { session in
         do {
            let response = try await session.translate(textInput)
            textInput = response.targetText
         } catch {
            print("Error translating the text: \(error)")
         }
      }
   }
}