import SwiftUI
import AppKit

// MARK: - NSViewRepresentable wrapper for SheetMusicView

/// Bridges the AppKit SheetMusicView into SwiftUI.
struct SheetMusicViewContainer: NSViewRepresentable {
    let song: Song?
    @Binding var selection: Selection
    @Binding var playbackMeasure: Int
    @Binding var playbackBeatFraction: Double

    func makeNSView(context: Context) -> NSScrollView {
        let scrollView = NSScrollView()
        scrollView.hasVerticalScroller = true
        scrollView.hasHorizontalScroller = false
        scrollView.autohidesScrollers = true
        scrollView.backgroundColor = .white
        scrollView.drawsBackground = true

        let sheetMusicView = SheetMusicView(frame: NSRect(x: 0, y: 0, width: 800, height: 600))
        sheetMusicView.autoresizingMask = [.width]
        sheetMusicView.song = song
        sheetMusicView.selection = selection
        sheetMusicView.playbackMeasure = playbackMeasure
        sheetMusicView.playbackBeatFraction = playbackBeatFraction

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

        scrollView.documentView = sheetMusicView

        return scrollView
    }

    func updateNSView(_ scrollView: NSScrollView, context: Context) {
        guard let sheetMusicView = scrollView.documentView as? SheetMusicView else { return }

        // Always update the song — the view's didSet handles layout recalculation
        sheetMusicView.song = song

        // Update the view width to match the scroll view's visible width
        let visibleWidth = scrollView.contentView.bounds.width
        if visibleWidth > 0 && sheetMusicView.bounds.width != visibleWidth {
            sheetMusicView.setFrameSize(NSSize(width: visibleWidth, height: sheetMusicView.bounds.height))
        }

        sheetMusicView.selection = selection
        sheetMusicView.playbackMeasure = playbackMeasure
        sheetMusicView.playbackBeatFraction = playbackBeatFraction
    }
}
