import Foundation
import UIKit

// MARK: - Selection Renderer (iOS)

/// Renders the cursor, selection highlight, and playback position on the sheet music.
/// UIKit port — UIColor instead of NSColor. Drawing logic identical to macOS.
struct SelectionRenderer_iOS {

    func drawSelection(
        _ selection: Selection,
        layout: SheetMusicLayout,
        in context: CGContext
    ) {
        // Draw selection range highlight
        if let range = selection.measureRange {
            let highlightColor = UIColor.systemBlue
                .withAlphaComponent(AppConstants.SelectionStyle.highlightAlpha)
            context.setFillColor(highlightColor.cgColor)

            for measureIndex in range.start...range.end {
                if let frame = layout.frame(forMeasure: measureIndex) {
                    context.fill(frame.rect)
                }
            }
        }

        // Draw cursor line
        if selection.cursor >= 0 && !selection.hasSelection {
            if let frame = layout.frame(forMeasure: selection.cursor) {
                context.setStrokeColor(UIColor.systemBlue.withAlphaComponent(0.6).cgColor)
                context.setLineWidth(2.0)
                context.move(to: CGPoint(x: frame.rect.minX + 1, y: frame.rect.minY))
                context.addLine(to: CGPoint(x: frame.rect.minX + 1, y: frame.rect.maxY))
                context.strokePath()
            }
        }
    }

    func drawPlaybackPosition(
        measure: Int,
        beatFraction: Double,
        layout: SheetMusicLayout,
        in context: CGContext
    ) {
        guard let frame = layout.frame(forMeasure: measure) else { return }

        let x = frame.rect.minX + CGFloat(beatFraction) * frame.rect.width
        let y = frame.rect.minY
        let height = frame.rect.height

        context.setStrokeColor(UIColor.systemRed.withAlphaComponent(0.8).cgColor)
        context.setLineWidth(2.0)
        context.move(to: CGPoint(x: x, y: y))
        context.addLine(to: CGPoint(x: x, y: y + height))
        context.strokePath()
    }
}
