//
//  BearingCompassView.swift
//  TestApp
//

import UIKit

/// Small compass showing current map bearing: rotating "N" points north, label shows degrees.
final class BearingCompassView: UIView {

  private let northContainer = UIView()
  private let northLabel: UILabel = {
    let l = UILabel()
    l.text = "N"
    l.font = .boldSystemFont(ofSize: 14)
    l.textColor = .label
    l.textAlignment = .center
    l.translatesAutoresizingMaskIntoConstraints = false
    return l
  }()

  private let degreesLabel: UILabel = {
    let l = UILabel()
    l.font = .monospacedDigitSystemFont(ofSize: 11, weight: .regular)
    l.textColor = .secondaryLabel
    l.translatesAutoresizingMaskIntoConstraints = false
    return l
  }()

  override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = UIColor.systemBackground.withAlphaComponent(0.85)
    layer.cornerRadius = 8
    clipsToBounds = true

    northContainer.translatesAutoresizingMaskIntoConstraints = false
    addSubview(northContainer)
    northContainer.addSubview(northLabel)
    addSubview(degreesLabel)
    NSLayoutConstraint.activate([
      northContainer.centerXAnchor.constraint(equalTo: centerXAnchor),
      northContainer.topAnchor.constraint(equalTo: topAnchor, constant: 6),
      northLabel.centerXAnchor.constraint(equalTo: northContainer.centerXAnchor),
      northLabel.centerYAnchor.constraint(equalTo: northContainer.centerYAnchor),
      degreesLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
      degreesLabel.topAnchor.constraint(equalTo: northContainer.bottomAnchor, constant: 2),
      degreesLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6),
    ])
    update(bearing: 0)
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  override var intrinsicContentSize: CGSize {
    CGSize(width: 44, height: 52)
  }

  /// Bearing in degrees (0 = north, 90 = east). Rotates "N" so it points to geographic north.
  func update(bearing: Double) {
    let degrees = (bearing.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360)
    degreesLabel.text = String(format: "%.0f°", degrees)
    let radians = -degrees * .pi / 180
    northContainer.transform = CGAffineTransform(rotationAngle: CGFloat(radians))
  }
}
