import type { Landmark3D } from '../types'

const ARMS_Y_TOLERANCE = 0.15
const ARMS_DOWN_COOLDOWN = 2000

export interface ArmsOutState {
  wasArmsOut: boolean
  armsDownSince: number | null
}

export function createArmsOutState(): ArmsOutState {
  return { wasArmsOut: false, armsDownSince: null }
}

/** Check if arms are currently extended at shoulder height. */
export function armsAreOut(worldLandmarks: Landmark3D[]): boolean {
  if (!worldLandmarks || worldLandmarks.length < 33) return false
  const ls = worldLandmarks[11], rs = worldLandmarks[12]
  const lw = worldLandmarks[15], rw = worldLandmarks[16]
  const shoulderY = (ls.y + rs.y) / 2
  return Math.abs(lw.y - shoulderY) < ARMS_Y_TOLERANCE
      && Math.abs(rw.y - shoulderY) < ARMS_Y_TOLERANCE
}

/**
 * Detect arms-out with cooldown hysteresis.
 * Arms must be down for ARMS_DOWN_COOLDOWN ms before re-triggering.
 * Returns true on rising edge (arms just raised after cooldown).
 */
export function detectArmsOut(state: ArmsOutState, worldLandmarks: Landmark3D[], now: number): boolean {
  const armsUp = armsAreOut(worldLandmarks)

  if (!armsUp) {
    if (!state.armsDownSince) state.armsDownSince = now
    state.wasArmsOut = false
    return false
  }

  const armsReady = state.armsDownSince !== null && (now - state.armsDownSince) >= ARMS_DOWN_COOLDOWN
  if (armsReady && !state.wasArmsOut) {
    state.wasArmsOut = true
    state.armsDownSince = null
    return true
  }
  return false
}
