import SwiftUI
import WebRTC

// Wraps RTCMTLVideoView for SwiftUI
struct VideoView: UIViewRepresentable {
    let track: RTCVideoTrack?
    var onRenderStart: (() -> Void)? = nil // Callback for when video starts rendering
    
    func makeUIView(context: Context) -> RTCMTLVideoView {
        let videoView = RTCMTLVideoView(frame: .zero)
        videoView.videoContentMode = .scaleAspectFill
        videoView.delegate = context.coordinator // Set delegate
        return videoView
    }
    
    func updateUIView(_ uiView: RTCMTLVideoView, context: Context) {
        // If track changed, we need to re-hook
        if let track = track {
            track.add(uiView)
        } else {
            // Optional: clear view if track is nil
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, RTCVideoViewDelegate {
        var parent: VideoView
        var hasNotifiedRender = false
        
        init(_ parent: VideoView) {
            self.parent = parent
        }
        
        func videoView(_ videoView: RTCVideoRenderer, didChangeVideoSize size: CGSize) {
            // This delegate method is called when the first frame is received and dimensions are known.
            // It's a good proxy for "Video is visible now"
            
            if !hasNotifiedRender && size.width > 0 && size.height > 0 {
                print("[VideoView] Video rendering started with size: \(size)")
                hasNotifiedRender = true
                
                DispatchQueue.main.async {
                    self.parent.onRenderStart?()
                }
            }
        }
    }
}
