//
//  LightTextField.swift
//  vibes
//
//  Custom TextField with light keyboard appearance for versions exploration
//

import SwiftUI
import UIKit

struct LightTextField: UIViewRepresentable {
    @Binding var text: String
    var placeholder: String
    var font: UIFont
    var textColor: UIColor
    var onSubmit: () -> Void

    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.delegate = context.coordinator
        textField.font = font
        textField.textColor = textColor
        textField.keyboardAppearance = .light  // Force light keyboard
        textField.returnKeyType = .default
        textField.autocorrectionType = .default
        textField.autocapitalizationType = .sentences
        textField.tintColor = UIColor(Color(hex: "#ff6a00"))  // Orange cursor

        // Set text alignment and other properties
        textField.textAlignment = .left

        // Style placeholder with proper color
        if !placeholder.isEmpty {
            let placeholderColor = UIColor(Color(hex: "#5b5b62")).withAlphaComponent(0.5)
            textField.attributedPlaceholder = NSAttributedString(
                string: placeholder,
                attributes: [
                    .foregroundColor: placeholderColor,
                    .font: font
                ]
            )
        }

        return textField
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
        uiView.font = font
        uiView.textColor = textColor

        // Update attributed placeholder
        if !placeholder.isEmpty {
            let placeholderColor = UIColor(Color(hex: "#5b5b62")).withAlphaComponent(0.5)
            uiView.attributedPlaceholder = NSAttributedString(
                string: placeholder,
                attributes: [
                    .foregroundColor: placeholderColor,
                    .font: font
                ]
            )
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(text: $text, onSubmit: onSubmit)
    }

    class Coordinator: NSObject, UITextFieldDelegate {
        @Binding var text: String
        var onSubmit: () -> Void

        init(text: Binding<String>, onSubmit: @escaping () -> Void) {
            _text = text
            self.onSubmit = onSubmit
        }

        func textFieldDidChangeSelection(_ textField: UITextField) {
            text = textField.text ?? ""
        }

        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            onSubmit()
            return true
        }
    }
}
