import * as THREE from 'three'

// Linear interpolation
export const lerp = (start, end, amt) => {
  return (1 - amt) * start + amt * end
}

// Map a number from [inMin, inMax] to [outMin, outMax]
export const mapRange = (value, inMin, inMax, outMin, outMax) => {
  const result = ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin
  return isNaN(result) ? outMin : result
}

// Clamp a number between min and max
export const clamp = (value, min, max) => {
  return Math.min(Math.max(value, min), max)
}

// Vector3 interpolation helper
export const lerpVectors = (v1, v2, alpha, outVector = new THREE.Vector3()) => {
  outVector.x = lerp(v1.x, v2.x, alpha)
  outVector.y = lerp(v1.y, v2.y, alpha)
  outVector.z = lerp(v1.z, v2.z, alpha)
  return outVector
}

// Convert a normalized scroll progress (0..1) within the experience into an
// absolute document scrollY, relative to the 900vh ScrollRig spacer. Because the
// experience now sits below the page hero (not at document top), jump-to-section
// targets must be measured from the spacer's offset rather than the document top.
// The spacer (#scroll-trigger-trigger) maps progress over the scroll span
// [spacerTop, spacerTop + (spacerHeight - viewportHeight)] — matching the
// ScrollTrigger start:'top top' / end:'bottom bottom' on the same element.
export const progressToScrollY = (progress) => {
  if (typeof document === 'undefined') return 0
  const rig = document.getElementById('scroll-trigger-trigger')
  if (!rig) return 0
  const top = rig.getBoundingClientRect().top + window.scrollY
  const scrollable = rig.offsetHeight - window.innerHeight
  return top + clamp(progress, 0, 1) * scrollable
}

// Smoothly scroll to an absolute document Y. Uses Lenis when available
// (desktop), and falls back to native smooth scroll on touch devices where Lenis
// is intentionally not instantiated — so the in-experience nav still works there.
export const smoothScrollToY = (lenis, y) => {
  if (lenis) {
    lenis.scrollTo(y, { duration: 1.5 })
  } else if (typeof window !== 'undefined') {
    window.scrollTo({ top: y, behavior: 'smooth' })
  }
}
