import { useMemo } from 'react'
import * as THREE from 'three'
import { truckPath } from '../curves/truckPath'

/**
 * Piecewise mapping of page scroll → position along the truck spline.
 * Pure, allocation-free, and safe to call every frame from inside useFrame.
 *
 *   0%–14%  : parked at First Mile      (0.0)
 *   14%–38% : drive First → Mid Mile    (0.0 → 0.5)
 *   38%–50% : parked at Mid Mile        (0.5)
 *   50%–76% : drive Mid → Last Mile     (0.5 → 1.0)
 *   76%–100%: parked at Last Mile       (1.0)
 *
 * Extracted from the old useMemo so the per-frame loop can read scroll progress
 * transiently (store.getState) and compute the mapping without triggering a
 * React re-render on every scroll tick.
 */
export function computeTruckProgress(scrollProgress) {
  if (scrollProgress < 0.14) return 0.0
  if (scrollProgress < 0.38) return (0.5 * (scrollProgress - 0.14)) / 0.24
  if (scrollProgress < 0.50) return 0.5
  if (scrollProgress < 0.76) return 0.5 + (0.5 * (scrollProgress - 0.50)) / 0.26
  return 1.0
}

/**
 * Legacy React hook kept for any external caller. The live experience no longer
 * uses it on the render path (TruckAnimation reads computeTruckProgress inside
 * useFrame), so it no longer drives per-frame re-renders.
 */
export const useTruckMovement = (scrollProgress) => {
  const truckProgress = useMemo(() => computeTruckProgress(scrollProgress), [scrollProgress])
  const position = useMemo(() => truckPath.getPoint(truckProgress), [truckProgress])
  const lookAtTarget = useMemo(() => {
    if (truckProgress >= 0.99) {
      const tangent = truckPath.getTangent(1.0)
      const endPoint = truckPath.getPoint(1.0)
      return new THREE.Vector3().copy(endPoint).addScaledVector(tangent, 1.0)
    }
    const ahead = Math.min(truckProgress + 0.01, 1.0)
    return truckPath.getPoint(ahead)
  }, [truckProgress])

  return { truckProgress, position, lookAtTarget }
}

export default useTruckMovement
