import SwiftUI
import UIKit

struct CameraView: UIViewControllerRepresentable {
    @Binding var isPresented: Bool
    let onImageSelected: (UIImage) -> Void
    @Environment(\.presentationMode) private var presentationMode
    
    func makeUIViewController(context: Context) -> UIViewController {
        let viewController = UIViewController()
        viewController.view.backgroundColor = .clear
        return viewController
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        if isPresented {
            DispatchQueue.main.async {
                if let rootVC = UIApplication.shared.windows.first?.rootViewController {
                    ImageCaptureManager.shared.captureImage(from: rootVC) { image in
                        if let image = image {
                            onImageSelected(image)
                        }
                        isPresented = false
                        presentationMode.wrappedValue.dismiss()
                    }
                }
            }
        }
    }
}