// Fluent 4×4 matrix (column-major) — the SDK's transform/projection type. Same contract as Vec/Quat:
// the methods are PURE (each returns a new Mat4), but — per the "never wrap away the metal" rule — the
// raw backing array is PUBLIC as `.m` (length 16). So low-level numeric surgery (`mat.m[12] += vx*dt`)
// drops straight to the array with zero ceremony, while the fluent methods express the high-level logic.
//
// Backing is a plain `number[]` (not a Float32Array) so a future optimizer can see through it; the
// Float32Array the host bridge wants is produced only at the edge via `toFloat32Array()`.
//
// This folds in the old `math/transform.ts` decomposition (position / scale / rotation / euler).

import { Vec3, type Vec3Like } from "./vec"
import { Quat, quatFromColMajor, eulerFromColMajor, type QuatLike, type EulerOrder } from "./quat"

export type Mat4Like = Mat4 | number[] | Float32Array | readonly number[]

const arr = (m: Mat4Like): ArrayLike<number> => (m as { m?: ArrayLike<number> }).m ?? (m as ArrayLike<number>)
const IDENTITY = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]

export class Mat4 {
  /** The raw column-major elements (length 16). Public on purpose — read/write directly when you want
   *  the metal: `mat.m[12] += vx * dt`. The fluent methods never mutate it (they return a new Mat4). */
  m: number[]

  constructor(src?: Mat4Like) {
    if (src === undefined) { this.m = IDENTITY.slice(); return }
    const s = arr(src)
    this.m = [ s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15] ]
  }

  // --- mutation ---
  set(values: ArrayLike<number>): this { for (let i = 0; i < 16; i++) this.m[i] = values[i]; return this }
  copy(src: Mat4Like): this { return this.set(arr(src)) }

  // --- products (pure) ---
  /** `this · b` (apply `b` first in local space, then `this`). */
  mul(b: Mat4Like): Mat4 {
    const a = this.m, o = arr(b), out = new Array(16)
    const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]
    const a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]
    const a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]
    const a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]
    for (let i = 0; i < 4; i++) {
      const b0 = o[i * 4], b1 = o[i * 4 + 1], b2 = o[i * 4 + 2], b3 = o[i * 4 + 3]
      out[i * 4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30
      out[i * 4 + 1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31
      out[i * 4 + 2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32
      out[i * 4 + 3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33
    }
    return fromArray(out)
  }
  /** `b · this` — multiply on the other side (apply `this` first, then `b`). */
  premul(b: Mat4Like): Mat4 { return new Mat4(b).mul(this) }

  invert(): Mat4 {
    const a = this.m
    const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]
    const a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]
    const a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]
    const a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]
    const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10
    const b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12
    const b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30
    const b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32
    let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06
    if (!det) return new Mat4() // singular → identity
    det = 1 / det
    return fromArray([
      (a11 * b11 - a12 * b10 + a13 * b09) * det, (a02 * b10 - a01 * b11 - a03 * b09) * det,
      (a31 * b05 - a32 * b04 + a33 * b03) * det, (a22 * b04 - a21 * b05 - a23 * b03) * det,
      (a12 * b08 - a10 * b11 - a13 * b07) * det, (a00 * b11 - a02 * b08 + a03 * b07) * det,
      (a32 * b02 - a30 * b05 - a33 * b01) * det, (a20 * b05 - a22 * b02 + a23 * b01) * det,
      (a10 * b10 - a11 * b08 + a13 * b06) * det, (a01 * b08 - a00 * b10 - a03 * b06) * det,
      (a30 * b04 - a31 * b02 + a33 * b00) * det, (a21 * b02 - a20 * b04 - a23 * b00) * det,
      (a11 * b07 - a10 * b09 - a12 * b06) * det, (a00 * b09 - a01 * b07 + a02 * b06) * det,
      (a31 * b01 - a30 * b03 - a32 * b00) * det, (a20 * b03 - a21 * b01 + a22 * b00) * det,
    ])
  }
  transpose(): Mat4 {
    const a = this.m
    return fromArray([ a[0], a[4], a[8], a[12], a[1], a[5], a[9], a[13], a[2], a[6], a[10], a[14], a[3], a[7], a[11], a[15] ])
  }
  determinant(): number {
    const a = this.m
    const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]
    const a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]
    const a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]
    const a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]
    const b0 = a00 * a11 - a01 * a10, b1 = a00 * a12 - a02 * a10, b2 = a01 * a12 - a02 * a11
    const b3 = a20 * a31 - a21 * a30, b4 = a20 * a32 - a22 * a30, b5 = a21 * a32 - a22 * a31
    const b6 = a00 * b5 - a01 * b4 + a02 * b3, b7 = a10 * b5 - a11 * b4 + a12 * b3
    const b8 = a20 * b2 - a21 * b1 + a22 * b0, b9 = a30 * b2 - a31 * b1 + a32 * b0
    return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9
  }

  // --- local-space transforms (post-multiply: this · T) ---
  /** `this · translate(v)`. */
  translate(v: Vec3Like): Mat4 {
    const a = this.m, x = ax(v), y = ay(v), z = az(v), out = a.slice()
    out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]
    out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]
    out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]
    out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]
    return fromArray(out)
  }
  /** `this · scale(v)`. Accepts a vector or a uniform scalar. */
  scale(v: Vec3Like | number): Mat4 {
    const a = this.m
    const x = typeof v === "number" ? v : ax(v), y = typeof v === "number" ? v : ay(v), z = typeof v === "number" ? v : az(v)
    return fromArray([
      a[0] * x, a[1] * x, a[2] * x, a[3] * x, a[4] * y, a[5] * y, a[6] * y, a[7] * y,
      a[8] * z, a[9] * z, a[10] * z, a[11] * z, a[12], a[13], a[14], a[15],
    ])
  }
  /** `this · rotate(axis, rad)`. */
  rotate(rad: number, axis: Vec3Like): Mat4 {
    let x = ax(axis), y = ay(axis), z = az(axis)
    let len = Math.hypot(x, y, z)
    if (len < 1e-6) return this.clone()
    len = 1 / len; x *= len; y *= len; z *= len
    const s = Math.sin(rad), c = Math.cos(rad), t = 1 - c
    const a = this.m
    const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]
    const a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]
    const a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]
    const b00 = x * x * t + c, b01 = y * x * t + z * s, b02 = z * x * t - y * s
    const b10 = x * y * t - z * s, b11 = y * y * t + c, b12 = z * y * t + x * s
    const b20 = x * z * t + y * s, b21 = y * z * t - x * s, b22 = z * z * t + c
    return fromArray([
      a00 * b00 + a10 * b01 + a20 * b02, a01 * b00 + a11 * b01 + a21 * b02, a02 * b00 + a12 * b01 + a22 * b02, a03 * b00 + a13 * b01 + a23 * b02,
      a00 * b10 + a10 * b11 + a20 * b12, a01 * b10 + a11 * b11 + a21 * b12, a02 * b10 + a12 * b11 + a22 * b12, a03 * b10 + a13 * b11 + a23 * b12,
      a00 * b20 + a10 * b21 + a20 * b22, a01 * b20 + a11 * b21 + a21 * b22, a02 * b20 + a12 * b21 + a22 * b22, a03 * b20 + a13 * b21 + a23 * b22,
      a[12], a[13], a[14], a[15],
    ])
  }
  rotateX(rad: number): Mat4 { return this.rotate(rad, AXIS_X) }
  rotateY(rad: number): Mat4 { return this.rotate(rad, AXIS_Y) }
  rotateZ(rad: number): Mat4 { return this.rotate(rad, AXIS_Z) }

  // --- vector transforms ---
  /** Transform a point (applies translation + perspective divide). */
  transformPoint(v: Vec3Like): Vec3 { return new Vec3(v).transform(this) }
  /** Transform a direction (rotation/scale only — no translation, no divide). */
  transformDirection(v: Vec3Like): Vec3 {
    const a = this.m, x = ax(v), y = ay(v), z = az(v)
    return new Vec3(a[0] * x + a[4] * y + a[8] * z, a[1] * x + a[5] * y + a[9] * z, a[2] * x + a[6] * y + a[10] * z)
  }

  // --- decomposition (folded from transform.ts) ---
  get position(): Vec3 { const a = this.m; return new Vec3(a[12], a[13], a[14]) }
  get scaling(): Vec3 {
    const a = this.m
    return new Vec3(Math.hypot(a[0], a[1], a[2]), Math.hypot(a[4], a[5], a[6]), Math.hypot(a[8], a[9], a[10]))
  }
  get rotation(): Quat { return quatFromColMajor(rotationOnly(this.m)) }
  get eulerAngles(): Vec3 { return eulerFromColMajor(rotationOnly(this.m), "YXZ") }
  toEuler(order: EulerOrder = "YXZ"): Vec3 { return eulerFromColMajor(rotationOnly(this.m), order) }
  /** `{ position, rotation, scale }` in one shot. */
  decompose(): { position: Vec3, rotation: Quat, scale: Vec3 } {
    return { position: this.position, rotation: this.rotation, scale: this.scaling }
  }

  /** Column basis vectors (the local X / Y / Z axes in world space). */
  get basisX(): Vec3 { const a = this.m; return new Vec3(a[0], a[1], a[2]) }
  get basisY(): Vec3 { const a = this.m; return new Vec3(a[4], a[5], a[6]) }
  get basisZ(): Vec3 { const a = this.m; return new Vec3(a[8], a[9], a[10]) }

  // --- interop ---
  clone(): Mat4 { return new Mat4(this) }
  toArray(): number[] { return this.m.slice() }
  toFloat32Array(): Float32Array { return Float32Array.from(this.m) }
  equals(b: Mat4Like, eps = 1e-6): boolean {
    const o = arr(b)
    for (let i = 0; i < 16; i++) {
      if (Math.abs(this.m[i] - o[i]) > eps * Math.max(1, Math.abs(this.m[i]), Math.abs(o[i]))) return false
    }
    return true
  }

  // --- factories ---
  static identity(): Mat4 { return new Mat4() }
  static from(src: Mat4Like): Mat4 { return new Mat4(src) }

  /** Translation · Rotation · Scale into one matrix. `scale` defaults to 1 and accepts a scalar. */
  static compose(position: Vec3Like, rotation: QuatLike, scale: Vec3Like | number = 1): Mat4 {
    const x = qx(rotation), y = qy(rotation), z = qz(rotation), w = qw(rotation)
    const x2 = x + x, y2 = y + y, z2 = z + z
    const xx = x * x2, xy = x * y2, xz = x * z2
    const yy = y * y2, yz = y * z2, zz = z * z2
    const wx = w * x2, wy = w * y2, wz = w * z2
    const sx = typeof scale === "number" ? scale : ax(scale)
    const sy = typeof scale === "number" ? scale : ay(scale)
    const sz = typeof scale === "number" ? scale : az(scale)
    return fromArray([
      (1 - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,
      (xy - wz) * sy, (1 - (xx + zz)) * sy, (yz + wx) * sy, 0,
      (xz + wy) * sz, (yz - wx) * sz, (1 - (xx + yy)) * sz, 0,
      ax(position), ay(position), az(position), 1,
    ])
  }
  static fromQuat(q: QuatLike): Mat4 { return Mat4.compose(ORIGIN, q, 1) }
  static fromTranslation(v: Vec3Like): Mat4 { const m = new Mat4(); m.m[12] = ax(v); m.m[13] = ay(v); m.m[14] = az(v); return m }
  static fromScale(v: Vec3Like | number): Mat4 { return new Mat4().scale(v) }
  static fromEuler(x: number, y: number, z: number, order: EulerOrder = "YXZ"): Mat4 {
    return Mat4.fromQuat(Quat.fromEuler(x, y, z, order))
  }

  /** A view matrix that looks from `eye` toward `center` with `up`. */
  static lookAt(eye: Vec3Like, center: Vec3Like, up: Vec3Like = Vec3.up): Mat4 {
    const ex = ax(eye), ey = ay(eye), ez = az(eye)
    let z0 = ex - ax(center), z1 = ey - ay(center), z2 = ez - az(center)
    let len = Math.hypot(z0, z1, z2)
    if (len < 1e-6) return new Mat4()
    len = 1 / len; z0 *= len; z1 *= len; z2 *= len
    const ux = ax(up), uy = ay(up), uz = az(up)
    let x0 = uy * z2 - uz * z1, x1 = uz * z0 - ux * z2, x2 = ux * z1 - uy * z0
    len = Math.hypot(x0, x1, x2)
    if (len) { len = 1 / len; x0 *= len; x1 *= len; x2 *= len } else { x0 = x1 = x2 = 0 }
    const y0 = z1 * x2 - z2 * x1, y1 = z2 * x0 - z0 * x2, y2 = z0 * x1 - z1 * x0
    return fromArray([
      x0, y0, z0, 0, x1, y1, z1, 0, x2, y2, z2, 0,
      -(x0 * ex + x1 * ey + x2 * ez), -(y0 * ex + y1 * ey + y2 * ez), -(z0 * ex + z1 * ey + z2 * ez), 1,
    ])
  }
  /** A world matrix that places something at `eye` oriented to look at `target`. */
  static targetTo(eye: Vec3Like, target: Vec3Like, up: Vec3Like = Vec3.up): Mat4 {
    const ex = ax(eye), ey = ay(eye), ez = az(eye)
    let z0 = ex - ax(target), z1 = ey - ay(target), z2 = ez - az(target)
    let len = z0 * z0 + z1 * z1 + z2 * z2
    if (len > 0) { len = 1 / Math.sqrt(len); z0 *= len; z1 *= len; z2 *= len }
    const ux = ax(up), uy = ay(up), uz = az(up)
    let x0 = uy * z2 - uz * z1, x1 = uz * z0 - ux * z2, x2 = ux * z1 - uy * z0
    len = x0 * x0 + x1 * x1 + x2 * x2
    if (len > 0) { len = 1 / Math.sqrt(len); x0 *= len; x1 *= len; x2 *= len }
    return fromArray([
      x0, x1, x2, 0, z1 * x2 - z2 * x1, z2 * x0 - z0 * x2, z0 * x1 - z1 * x0, 0,
      z0, z1, z2, 0, ex, ey, ez, 1,
    ])
  }
  /** Perspective projection (WebGL/OpenGL clip, NDC z ∈ [−1, 1]). `fovy` is in RADIANS. */
  static perspective(fovy: number, aspect: number, near: number, far: number): Mat4 {
    const f = 1 / Math.tan(fovy / 2), out = new Array(16).fill(0)
    out[0] = f / aspect; out[5] = f; out[11] = -1
    if (far !== Infinity) { const nf = 1 / (near - far); out[10] = (far + near) * nf; out[14] = 2 * far * near * nf }
    else { out[10] = -1; out[14] = -2 * near }
    return fromArray(out)
  }
  /** Orthographic projection (WebGL/OpenGL clip, NDC z ∈ [−1, 1]). */
  static ortho(left: number, right: number, bottom: number, top: number, near: number, far: number): Mat4 {
    const lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far)
    return fromArray([
      -2 * lr, 0, 0, 0, 0, -2 * bt, 0, 0, 0, 0, 2 * nf, 0,
      (left + right) * lr, (top + bottom) * bt, (far + near) * nf, 1,
    ])
  }
}

// fast path: wrap an already-built length-16 array as a Mat4 without re-copying it.
const fromArray = (m: number[]): Mat4 => { const r = Object.create(Mat4.prototype) as Mat4; r.m = m; return r }

/** The 3×3 rotation part with scale divided out, as a column-major length-≥11 array (for quat/euler). */
const rotationOnly = (a: ArrayLike<number>): number[] => {
  const sx = Math.hypot(a[0], a[1], a[2]) || 1, sy = Math.hypot(a[4], a[5], a[6]) || 1, sz = Math.hypot(a[8], a[9], a[10]) || 1
  const i1 = 1 / sx, i2 = 1 / sy, i3 = 1 / sz
  return [ a[0] * i1, a[1] * i1, a[2] * i1, 0, a[4] * i2, a[5] * i2, a[6] * i2, 0, a[8] * i3, a[9] * i3, a[10] * i3 ]
}

const ax = (v: Vec3Like): number => (v as { x?: number }).x ?? (v as ArrayLike<number>)[0]
const ay = (v: Vec3Like): number => (v as { y?: number }).y ?? (v as ArrayLike<number>)[1]
const az = (v: Vec3Like): number => (v as { z?: number }).z ?? (v as ArrayLike<number>)[2]
const qx = (q: QuatLike): number => (q as { x?: number }).x ?? (q as ArrayLike<number>)[0]
const qy = (q: QuatLike): number => (q as { y?: number }).y ?? (q as ArrayLike<number>)[1]
const qz = (q: QuatLike): number => (q as { z?: number }).z ?? (q as ArrayLike<number>)[2]
const qw = (q: QuatLike): number => (q as { w?: number }).w ?? (q as ArrayLike<number>)[3]

const AXIS_X: Vec3Like = [ 1, 0, 0 ]
const AXIS_Y: Vec3Like = [ 0, 1, 0 ]
const AXIS_Z: Vec3Like = [ 0, 0, 1 ]
const ORIGIN: Vec3Like = [ 0, 0, 0 ]
