// Platform info + the host resize event. The resize listener registers with the host lazily on the
// first subscription (no top-level side effect, so tree-shaking can drop this entirely if unused).

type ResizeCallback = (width: number, height: number) => void

const resizeListeners: ResizeCallback[] = []
let resizeRegistered = false

const onResize = (width: number, height: number): void => {
  for (const cb of resizeListeners.slice()) cb(width, height)
}

export const device = {
  get platform(): "web" | "android" | "ios" | string {
    return _creatorUtils.platform
  },
  get language(): string {
    return _creatorUtils.language
  },
  /** Display device-pixel ratio (physical px per logical/CSS px): 1 on standard displays, 2–3 on
   *  retina / iOS. Bake a Canvas at this ratio for crisp output without hardcoding, e.g.
   *  `new Canvas(w, h, { pixelRatio: device.pixelRatio })`. NOTE: the web 2D/GL surface currently
   *  renders at logical resolution, so on web this only helps UI canvases / is forward-looking for
   *  2D; on iOS (physical surface) it makes 2D canvases crisp. Falls back to 1 if the host omits it. */
  get pixelRatio(): number {
    return _creatorUtils.pixelRatio || 1
  },
  /** Current display width in logical px — the same value the "resize" event delivers, but readable at
   *  any time (not only inside the listener). 0 until the host has reported a size. */
  get width(): number {
    return _creatorUI.getDisplaySize?.()?.[0] ?? 0
  },
  /** Current display height in logical px — the same value the "resize" event delivers, readable at any
   *  time. 0 until the host has reported a size. */
  get height(): number {
    return _creatorUI.getDisplaySize?.()?.[1] ?? 0
  },
  /** Opt into the precise-touch system where the platform supports it. OFF by default. When on, fast
   *  strokes are sampled at the touch digitizer's full rate (iOS coalesced touches, ≈120–240 Hz) instead
   *  of once per display frame (~60 Hz), so a pointer-heavy app (drawing, handwriting, dragging) gets more
   *  points and smoother lines. Leave it off for tap/button UIs. No-op on hosts without a coalesced-input
   *  concept (web already coalesces pointermove; headless). */
  setPreciseTouch(enabled: boolean): void {
    _creatorUtils.setPreciseTouch?.(enabled)
  },
  addEventListener(channel: "resize", callback: ResizeCallback): void {
    if (channel !== "resize") return
    resizeListeners.push(callback)
    if (!resizeRegistered) {
      resizeRegistered = true
      _creatorUI.registerResizeEvent(onResize)
    }
  },
  removeEventListener(channel: "resize", callback: ResizeCallback): void {
    if (channel !== "resize") return
    const i = resizeListeners.indexOf(callback)
    if (i >= 0) resizeListeners.splice(i, 1)
  },
}
