//
//  FocusedTextField.swift
//  SodaLive
//
//  Created by klaus on 1/9/25.
//

import SwiftUI

struct FocusedTextField: UIViewRepresentable {
    @Binding var text: String
    var isFirstResponder: Bool
    
    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: FocusedTextField
        
        init(_ parent: FocusedTextField) {
            self.parent = parent
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            parent.text = textField.text ?? ""
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.delegate = context.coordinator
        textField.font = UIFont(name: Font.medium.rawValue, size: 13.3)
        textField.textColor = UIColor(hex: "eeeeee", alpha: 1.0)
        textField.tintColor = UIColor(hex: "3bb9f1", alpha: 1.0)
        textField.keyboardType = .default
        textField.autocapitalizationType = .none
        textField.autocorrectionType = .no
        
        let placeholder = "검색어를 2글자 이상 입력하세요"
        textField.placeholder = placeholder
        textField.attributedPlaceholder = NSAttributedString(
            string: placeholder,
            attributes: [.foregroundColor: UIColor(hex: "555555", alpha: 1.0)]
        )
        
        return textField
    }
    
    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
        if isFirstResponder {
            uiView.becomeFirstResponder()
        }
    }
}
