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

export const ENTER_THRESHOLD = 0.6   // distance / shoulder-width ratio to activate
export const EXIT_THRESHOLD = 1.0    // ratio to deactivate
export const HOLD_MS = 500           // must hold for this long before triggering

export interface CrossedArmsState {
  active: boolean
  holdingSince: number | null  // timestamp when gesture first detected, null if not holding
  lDist: number   // left index → right shoulder (normalized)
  rDist: number   // right index → left shoulder (normalized)
  shoulderWidth: number
}

export function createCrossedArmsState(): CrossedArmsState {
  return { active: false, holdingSince: null, lDist: 0, rDist: 0, shoulderWidth: 0 }
}

function dist2D(a: Landmark2D, b: Landmark2D): number {
  const dx = a.x - b.x, dy = a.y - b.y
  return Math.sqrt(dx * dx + dy * dy)
}

/**
 * Detect either hand on opposite shoulder (2D, normalized by shoulder width).
 * Must hold for HOLD_MS before triggering.
 * Returns 'start' on activation, 'end' on deactivation, null otherwise.
 */
export function detectCrossedArms(
  state: CrossedArmsState,
  landmarks2D: Landmark2D[],
  now: number,
): 'start' | 'end' | null {
  if (!landmarks2D || landmarks2D.length < 33) return null

  const lShoulder = landmarks2D[11], rShoulder = landmarks2D[12]
  const lIndex = landmarks2D[19], rIndex = landmarks2D[20]

  const shoulderWidth = dist2D(lShoulder, rShoulder)
  if (shoulderWidth < 0.01) return null

  const lDist = dist2D(lIndex, rShoulder) / shoulderWidth
  const rDist = dist2D(rIndex, lShoulder) / shoulderWidth

  state.lDist = lDist
  state.rDist = rDist
  state.shoulderWidth = shoulderWidth

  const threshold = state.active ? EXIT_THRESHOLD : ENTER_THRESHOLD
  const eitherClose = lDist < threshold || rDist < threshold

  if (!state.active) {
    if (eitherClose) {
      if (state.holdingSince === null) state.holdingSince = now
      if (now - state.holdingSince >= HOLD_MS) {
        state.active = true
        state.holdingSince = null
        return 'start'
      }
    } else {
      state.holdingSince = null
    }
  } else {
    if (!eitherClose) {
      state.active = false
      state.holdingSince = null
      return 'end'
    }
  }

  return null
}
