-- headsup_led.lua  — heads-up display with refresh/caching

local gearT = {
  [-1] = "R",
  [0]  = "N",
  [1]  = "1",
  [2]  = "2",
  [3]  = "3",
  [4]  = "4",
  [5]  = "5",
  [6]  = "6",
  [7]  = "7",
  [8]  = "8",
  [9]  = "9"
}

local white = rgb(1, 1, 1)

-- ── refresh setup (borrowed from cluster script) ─────────────────────────────
local REFRESH      = 0.20            -- seconds between data updates
local refreshTimer = 0
local cached       = {}

local function refreshCache()
  cached.speed     = math.floor(car.speedKmh)                                  -- km/h
  cached.sessionMi = string.format("%02.1f", car.distanceDrivenSessionKm / 1.609344)
  cached.gear      = gearT[car.gear]
end

-- prime cache immediately so first frame has values
refreshCache()

function update(dt)
  -- tick refresh timer and update cache when it elapses
  refreshTimer = refreshTimer - dt
  if refreshTimer <= 0 then
    refreshTimer = REFRESH
    refreshCache()
  end

  -- draw using cached values (positions/sizes unchanged)
  display.text({
    text = cached.speed,
    pos = vec2(622.5, 500.8),
    letter = vec2(75, 150),
    font = 'c7_big',
    color = white,
    alignment = 1,
    width = 251,
    spacing = 1
  })

  display.text({
    text = cached.sessionMi,
    pos = vec2(0, 0),
    letter = vec2(25, 50),
    font = 'e92_big',
    color = white,
    alignment = 1,
    width = 0,
    spacing = 0.01
  })

  display.text({
    text = cached.gear,
    pos = vec2(462.2, 497.9),
    letter = vec2(75, 150),
    font = 'c7_big',
    color = white,
    alignment = 0.5,
    width = 0,
    spacing = 1
  })
end
