import UIKit

/// The UIView that hosts the ThorVG-rendered output. It keeps the latest scene,
/// marks itself dirty when it changes, and renders into `layer.contents`
/// (a CGImage) on demand and whenever its size changes.
final class ThorCanvasView: UIView {
  var shapes: [ThorShape] = [] {
    didSet { setNeedsThorRender() }
  }

  private var needsRender = true
  // Last rasterized pixel size; lets layoutSubviews skip a re-render when the
  // size hasn't actually changed and the content isn't dirty.
  private var lastPixelWidth = 0
  private var lastPixelHeight = 0

  // Reusable marshalling buffers (parallel primitive arrays, ready for the
  // bridge). One view renders on the main thread only, so these are reused
  // across frames with no per-frame allocation once they reach steady size.
  private var mTypes: [Int32] = []
  private var mFills: [UInt32] = []
  private var mStrokes: [UInt32] = []
  private var mParams: [Float] = [] // stride 8 per shape
  private var mPointsFlat: [Float] = []
  private var mPointCounts: [Int32] = []
  private var colorCache: [String: UInt32] = [:]

  override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = .clear
    layer.contentsGravity = .resize
  }

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

  func setNeedsThorRender() {
    needsRender = true
  }

  /// Called once per prop-update batch (from the HybridView's `afterUpdate()`).
  func renderIfNeeded() {
    if needsRender {
      render()
    }
  }

  override func layoutSubviews() {
    super.layoutSubviews()
    // Only re-render when the pixel size actually changed (a layout pass can
    // fire for unrelated reasons). A size change forces a re-rasterize at the
    // new dimensions; otherwise fall through to the normal dirty check.
    let scale = window?.screen.scale ?? UIScreen.main.scale
    let pixelWidth = Int((bounds.width * scale).rounded())
    let pixelHeight = Int((bounds.height * scale).rounded())
    if pixelWidth != lastPixelWidth || pixelHeight != lastPixelHeight {
      needsRender = true
    }
    renderIfNeeded()
  }

  private func render() {
    let scale = window?.screen.scale ?? UIScreen.main.scale
    let pixelWidth = Int((bounds.width * scale).rounded())
    let pixelHeight = Int((bounds.height * scale).rounded())
    guard pixelWidth > 0, pixelHeight > 0 else { return }

    let count = marshal(shapes, scale: Float(scale))

    guard let image = ThorRenderBridge.image(
      withWidth: Int32(pixelWidth),
      height: Int32(pixelHeight),
      count: Int32(count),
      types: mTypes,
      fills: mFills,
      strokes: mStrokes,
      params: mParams,
      pointsFlat: mPointsFlat,
      pointCounts: mPointCounts
    ) else { return }

    // Disable implicit animations so content/size swaps don't fade or move.
    CATransaction.begin()
    CATransaction.setDisableActions(true)
    layer.contents = image.cgImage
    layer.contentsScale = scale
    CATransaction.commit()

    lastPixelWidth = pixelWidth
    lastPixelHeight = pixelHeight
    needsRender = false
  }

  // MARK: - Marshalling

  /// Fills the reusable parallel arrays from `shapes` (scaled to device pixels)
  /// and returns the shape count. Mirrors the Android `ThorSceneMarshal`.
  private func marshal(_ shapes: [ThorShape], scale: Float) -> Int {
    let n = shapes.count
    if mTypes.count != n {
      mTypes = [Int32](repeating: 0, count: n)
      mFills = [UInt32](repeating: 0, count: n)
      mStrokes = [UInt32](repeating: 0, count: n)
      mParams = [Float](repeating: 0, count: n * 8)
      mPointCounts = [Int32](repeating: 0, count: n)
    }

    var totalPoints = 0
    for s in shapes {
      if case .polygon = s.type { totalPoints += s.points?.count ?? 0 }
    }
    if mPointsFlat.count != totalPoints {
      mPointsFlat = [Float](repeating: 0, count: totalPoints)
    }

    var pOff = 0
    for i in 0..<n {
      let s = shapes[i]
      mTypes[i] = Int32(ThorCanvasView.typeCode(s.type))
      mFills[i] = color(s.fill)
      mStrokes[i] = color(s.stroke)
      mPointCounts[i] = 0
      let b = i * 8
      // Only params[b] (strokeWidth) and params[b+7] (closed) are always read;
      // the bridge reads geometry slots per-type, so stale slots are never used.
      mParams[b] = Float(s.strokeWidth ?? 1.0) * scale
      mParams[b + 7] = (s.closed == false) ? 0 : 1
      switch s.type {
      case .rect:
        mParams[b + 1] = Float(s.x ?? 0) * scale
        mParams[b + 2] = Float(s.y ?? 0) * scale
        mParams[b + 3] = Float(s.width ?? 0) * scale
        mParams[b + 4] = Float(s.height ?? 0) * scale
        mParams[b + 5] = Float(s.rx ?? 0) * scale
        mParams[b + 6] = Float(s.ry ?? 0) * scale
      case .circle:
        mParams[b + 1] = Float(s.cx ?? 0) * scale
        mParams[b + 2] = Float(s.cy ?? 0) * scale
        mParams[b + 3] = Float(s.radius ?? 0) * scale
      case .line:
        mParams[b + 1] = Float(s.x1 ?? 0) * scale
        mParams[b + 2] = Float(s.y1 ?? 0) * scale
        mParams[b + 3] = Float(s.x2 ?? 0) * scale
        mParams[b + 4] = Float(s.y2 ?? 0) * scale
      case .polygon:
        if let pts = s.points {
          mPointCounts[i] = Int32(pts.count)
          for k in 0..<pts.count { mPointsFlat[pOff + k] = Float(pts[k]) * scale }
          pOff += pts.count
        }
      }
    }
    return n
  }

  // MARK: - Conversion

  private static func typeCode(_ type: ThorShapeType) -> Int {
    switch type {
    case .rect: return 0
    case .circle: return 1
    case .line: return 2
    case .polygon: return 3
    }
  }

  /// Parses a hex color through a per-view cache (the same few strings recur
  /// every frame). nil / no color -> 0 (alpha 0 == "none").
  private func color(_ hex: String?) -> UInt32 {
    guard let hex = hex else { return 0 }
    if let cached = colorCache[hex] { return cached }
    let value = ThorCanvasView.parseHexColor(hex)
    colorCache[hex] = value
    return value
  }

  /// Parses "#RGB", "#RRGGBB", or "#AARRGGBB" into a 0xAARRGGBB value.
  static func parseHexColor(_ hex: String) -> UInt32 {
    var str = hex.trimmingCharacters(in: .whitespacesAndNewlines)
    if str.hasPrefix("#") { str.removeFirst() }

    var value: UInt64 = 0
    Scanner(string: str).scanHexInt64(&value)

    switch str.count {
    case 3: // RGB shorthand
      let r = (value & 0xF00) >> 8
      let g = (value & 0x0F0) >> 4
      let b = value & 0x00F
      let rr = r << 4 | r
      let gg = g << 4 | g
      let bb = b << 4 | b
      return 0xFF00_0000 | UInt32(rr << 16 | gg << 8 | bb)
    case 6: // RRGGBB -> opaque
      return 0xFF00_0000 | UInt32(value & 0xFF_FFFF)
    case 8: // AARRGGBB
      return UInt32(value & 0xFFFF_FFFF)
    default:
      return 0xFF00_0000
    }
  }
}
