import NitroModules
import UIKit

/// Nitro HybridView backing the JS `<Canvas>` component. It owns a
/// `ThorCanvasView`, forwards the scene to it, and renders once per prop batch.
final class HybridThorView: HybridThorViewSpec {
  var view: ThorCanvasView = ThorCanvasView()

  // Props (batched between beforeUpdate()/afterUpdate())
  var shapes: [ThorShape] = [] {
    didSet { view.shapes = shapes }
  }

  // iOS is CPU-only for now; the GL backend is Android-only. Stored to satisfy
  // the generated spec; ignored.
  var backend: ThorBackend? = nil

  func afterUpdate() {
    view.renderIfNeeded()
  }

  /// Imperative worklet fast-path (see `ThorViewMethods.drawShapes`). Called from
  /// a worklet (off the JS thread); UIKit / CALayer must be touched on the main
  /// thread, so hop there. The rasterize itself is CPU-only ThorVG work.
  func drawShapes(shapes: [ThorShape]) throws {
    if Thread.isMainThread {
      view.shapes = shapes
      view.renderIfNeeded()
    } else {
      DispatchQueue.main.async { [weak self] in
        guard let self = self else { return }
        self.view.shapes = shapes
        self.view.renderIfNeeded()
      }
    }
  }
}
