// Orthographic camera for a Scene2D. Position / zoom / rotation live natively. To make the camera
// track a node, attach a small update(dt) aspect that eases camera.position toward the node — there's
// no built-in follow() (and so nothing to dispose).

import { Vec2, cx, cy, type Vec2Like } from "../math/vec"
import type { CompAxis, CompWriter } from "../core/compWrite"

export class Camera2D implements CompWriter {
  private _x = 0
  private _y = 0
  private _zoom = 1
  private _rotation = 0

  private readonly sceneId: number
  constructor(sceneId: number) { this.sceneId = sceneId }

  get position(): Vec2 { return new Vec2(this._x, this._y) }
  set position(v: Vec2Like) { this._x = cx(v); this._y = cy(v); _creator2d.cameraSetPosition(this.sceneId, this._x, this._y) }
  /** @internal chisel `comp_write` (see core/compWrite.ts): `camera.position.<axis> = v` compiles to a call here. */
  static _comps = [ "position" ]
  _writeComp(_prop: string, axis: CompAxis, v: number): void {
    if (axis === "x") this.position = [ v, this._y ]
    else if (axis === "y") this.position = [ this._x, v ]
  }

  get zoom(): number { return this._zoom }
  set zoom(z: number) { this._zoom = z; _creator2d.cameraSetZoom(this.sceneId, z) }

  get rotation(): number { return this._rotation }
  set rotation(deg: number) { this._rotation = deg; _creator2d.cameraSetRotation(this.sceneId, deg) }

  screenToWorld(screenX: number, screenY: number): Vec2 {
    const o = _creator2d.cameraScreenToWorld(this.sceneId, screenX, screenY)
    return new Vec2(o[0], o[1])
  }
  worldToScreen(worldX: number, worldY: number): Vec2 {
    const o = _creator2d.cameraWorldToScreen(this.sceneId, worldX, worldY)
    return new Vec2(o[0], o[1])
  }
}
