import SwiftUI
import UIKit

// MARK: - UIViewRepresentable wrapper for SheetMusicView_iOS

/// Bridges the UIKit SheetMusicView_iOS into SwiftUI, embedded in a UIScrollView.
struct SheetMusicViewContainer_iOS: UIViewRepresentable {
    let song: Song?
    @Binding var selection: Selection
    @Binding var playbackMeasure: Int
    @Binding var playbackBeatFraction: Double

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UIScrollView {
        let scrollView = UIScrollView()
        scrollView.showsVerticalScrollIndicator = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.backgroundColor = .white

        let sheetMusicView = SheetMusicView_iOS(frame: CGRect(x: 0, y: 0, width: 375, height: 600))
        sheetMusicView.song = song
        sheetMusicView.selection = selection
        sheetMusicView.playbackMeasure = playbackMeasure
        sheetMusicView.playbackBeatFraction = playbackBeatFraction
        sheetMusicView.tag = 100  // Tag for finding it later

        sheetMusicView.onSelectionChanged = { newSelection in
            DispatchQueue.main.async {
                self.selection = newSelection
            }
        }

        scrollView.addSubview(sheetMusicView)
        scrollView.delegate = context.coordinator

        return scrollView
    }

    func updateUIView(_ scrollView: UIScrollView, context: Context) {
        guard let sheetMusicView = scrollView.viewWithTag(100) as? SheetMusicView_iOS else { return }

        // Update the view width to match the scroll view
        let visibleWidth = scrollView.bounds.width
        if visibleWidth > 0 {
            let currentWidth = sheetMusicView.bounds.width
            if abs(currentWidth - visibleWidth) > 1 {
                sheetMusicView.frame = CGRect(
                    x: 0, y: 0,
                    width: visibleWidth,
                    height: sheetMusicView.layout.totalSize.height
                )
                sheetMusicView.recalculateLayout()
            }
        }

        sheetMusicView.song = song
        sheetMusicView.selection = selection
        sheetMusicView.playbackMeasure = playbackMeasure
        sheetMusicView.playbackBeatFraction = playbackBeatFraction

        // Update scroll view content size
        scrollView.contentSize = sheetMusicView.layout.totalSize

        // Auto-scroll to keep one full line ahead of playback visible
        if playbackMeasure >= 0 {
            let layout = sheetMusicView.layout
            // Look one system (line) ahead so the user can see what's coming
            let lookAheadMeasure = playbackMeasure + max(1, layout.measuresPerSystem)
            let targetMeasure = min(lookAheadMeasure, (song?.totalMeasures ?? 1) - 1)
            if let aheadFrame = layout.frame(forMeasure: targetMeasure) {
                let visibleRect = scrollView.bounds
                if !visibleRect.contains(CGPoint(x: aheadFrame.rect.midX, y: aheadFrame.rect.maxY)) {
                    scrollView.scrollRectToVisible(aheadFrame.rect.insetBy(dx: 0, dy: -40), animated: true)
                }
            }
        }
    }

    // MARK: - Coordinator

    class Coordinator: NSObject, UIScrollViewDelegate {
        var parent: SheetMusicViewContainer_iOS

        init(_ parent: SheetMusicViewContainer_iOS) {
            self.parent = parent
        }
    }
}
