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 = rgbm(1, 1, 1, 1)

-- RANGE-CALC SETTINGS
local fuelKmsPerLitre = 9       -- km/L for range calculation

-- NEEDLE SETTINGS (unchanged)
local needleTex    = "./cluster/needle_centered_reworked.png"
local needleSize   = vec2(900, 900)
local needlePivot  = vec2(399, 1000)
local needleMinDeg = 133
local needleMaxDeg = -133
local needleMaxVal = 360

-- RPM NEEDLE SETTINGS (unchanged)
local rpmNeedleTex    = "./cluster/needle_centered_reworked.png"
local rpmNeedleSize   = vec2(900, 900)
local rpmNeedlePivot  = vec2(1655, 1000)
local rpmNeedleMinDeg = -0
local rpmNeedleMaxDeg = -170
local rpmNeedleMaxVal = 8000

-- BAR AREAS
-- RPM bar uses “reveal” mode: we draw a dark overlay then erase it left→right
local BAR_RPM  = { pos = vec2(259.6, 715),  size = vec2(1295, 71) }
-- Oil & Fuel are standard smooth color bars
local BAR_OIL  = { pos = vec2(424.5, 1364),   size = vec2(260, 10), bg = rgbm(0,0,0,0), fill = rgb(1,1,1) }
local BAR_FUEL = { pos = vec2(1374, 1363),   size = vec2(260, 10), bg = rgbm(0,0,0,0), fill = rgb(1,1,1) }

-- 🔹 Moving-edge styling per bar (width in px, color as rgbm)
local RPM_EDGE  = { width = 6, color = rgbm(1.0, 1.0, 1.0, 0.95) }
local OIL_EDGE  = { width = 6, color = rgbm(1, 0, 0, 0.95) }
local FUEL_EDGE = { width = 4, color = rgbm(1.0, 0., 0, 0.95) }

-- Value ranges for bars
local OIL_MIN_C = 50     -- 0% at 50°C
local OIL_MAX_C = 130    -- 100% at 130°C

-- Smoothing
local SMOOTH_HZ = 10
local smoothRPM, smoothOil, smoothFuel = 0, 0, 0

-- AVERAGE SPEED (moving-time only)
local movingTimeSec = 0.0

-- SETTINGS (existing)
local debugMode       = false
local debugDistance   = false
local useMph          = true
local simulatedSpeedKmh = 0

local REFRESH = 0.2
local refreshTimer = 0

local simulatedSessionKm = 0
local simulatedTotalKm   = 0
local cached = {}

-- HELPERS
local function v(str) local x,y=str:match("([^,]+),%s*([^,]+)"); return vec2(tonumber(x), tonumber(y)) end
local function clamp(x,a,b) return (x<a) and a or (x>b) and b or x end
local function lerp(a,b,t) return a + (b - a) * t end
local function ema(prev, target, hz, dt) dt = dt or 0.016; local k = math.exp(-hz * dt); return target + (prev - target) * k end
local function rect(x,y,w,h,c,o) display.rect{ pos=vec2(x,y), size=vec2(w,h), color=c, opacity=o or 1 } end

-- Robust max-RPM getter
local function getMaxRPM()
  local v =  car.rpmLimiter
         or car.rpmLimit
         or car.limiter
         or car.redlineRPM
         or car.maxRPM
         or car.engineMaxRPM
         or car.revLimiterRPM
         or car.revLimit
         or rpmNeedleMaxVal
         or 8000
  if v and v < 1000 then v = 8000 end
  return v
end

-- 🔰 RPM “reveal” bar (dark overlay removed as RPM increases)
local function drawRpmRevealBar(pos, size, fraction)
  fraction = clamp(fraction or 0, 0, 1)
  -- Darken only the UNFILLED part to keep filled side as original texture
  local unfilledX = pos.x + size.x * fraction
  local unfilledW = size.x * (1 - fraction)
  if unfilledW > 0.5 then
    display.rect{ pos = vec2(unfilledX, pos.y), size = vec2(unfilledW, size.y), color = rgbm(0, 0, 0, 0.60) }
  end
end

-- Generic moving-edge drawer (used by all bars)
local function drawEdge(pos, size, fraction, edge)
  if not edge or (edge.width or 0) <= 0 then return end
  local f = clamp(fraction or 0, 0, 1)
  if f <= 0 or f >= 1 then return end
  local x = pos.x + size.x * f - (edge.width * 0.5)
  display.rect{ pos = vec2(math.floor(x + 0.5), pos.y), size = vec2(edge.width, size.y), color = edge.color, opacity = 1 }
end

-- Standard color bar draw (Oil/Fuel) + moving edge
local function drawBar(bar, fraction, edge)
  local f = clamp(fraction or 0, 0, 1)
  display.rect{ pos = bar.pos, size = bar.size, color = bar.bg,  opacity = 1 }
  if f > 0 then
    display.rect{
      pos  = bar.pos,
      size = vec2(math.floor(bar.size.x * f + 0.5), bar.size.y),
      color = bar.fill, opacity = 1
    }
  end
  drawEdge(bar.pos, bar.size, f, edge)
end

-- NEEDLE HELPERS (existing)
local function needleAngle(val) local t = math.min(math.max(val / needleMaxVal, 0), 1); return lerp(needleMinDeg, needleMaxDeg, t) end
local function rpmNeedleAngle(val) local t = math.min(math.max(val / rpmNeedleMaxVal, 0), 1); return lerp(rpmNeedleMinDeg, rpmNeedleMaxDeg, t) end

function getSpeedKmh() return debugMode and simulatedSpeedKmh or car.speedKmh end

function update(dt)
  local speedKmh = getSpeedKmh()
  local speed = useMph and (speedKmh / 1.609344) or speedKmh

  -- Average speed (moving time only)
  if speedKmh > 0.5 then movingTimeSec = movingTimeSec + dt end

  if debugDistance then
    local distKm = (speedKmh / 3600) * dt
    simulatedSessionKm = simulatedSessionKm + distKm
    simulatedTotalKm   = simulatedTotalKm + distKm
  end

  -- Cached UI values
  refreshTimer = refreshTimer - dt
  if refreshTimer <= 0 then
    refreshTimer = REFRESH
    cached.time     = math.floor(car.oilTemperature / 0.8)
    cached.speed    = math.floor(speed)
    cached.temp     = math.floor(car.waterTemperature / 0.337)
    cached.fuel     = math.floor(car.fuel)
    cached.gear     = gearT[car.gear]
    cached.oilPress = math.floor(car.oilPressure / 0.14504)
    cached.rangeKm  = math.floor(car.fuel * fuelKmsPerLitre / 1.609344)
    if debugDistance then
      cached.totalKm   = string.format("%1d", simulatedTotalKm)
      cached.sessionKm = string.format("%.1f", simulatedSessionKm)
    else
      cached.totalKm   = string.format("%1d", car.distanceDrivenTotalKm)
      cached.sessionKm = string.format("%.1f", car.distanceDrivenSessionKm)
    end
  end

  -- ───── existing texts (unchanged) ─────
  display.text({ text=cached.time,      pos=v("70, 1190"),      letter=v("55, 110"), font='c7_big', color=white, alignment=1,   width=250, spacing=-10 })
  display.text({ text=cached.speed,     pos=v("900, 1110"),     letter=v("100, 200"),font='c7_big', color=white, alignment=0.5, width=265, spacing=-20 })
  display.text({ text=cached.totalKm,   pos=v("1650, 1065"),    letter=v("30, 60"),  font='c7_big', color=white, alignment=0.5, width=250, spacing=0 })
  display.text({ text=cached.sessionKm, pos=v("-227.1, 910.2"), letter=v("30, 60"),  font='sls',    color=white, alignment=0.5, width=250, spacing=0 })
  display.text({ text=cached.temp,      pos=v("105, 1335"),     letter=v("30, 60"),  font='c7_big', color=white, alignment=1,   width=250, spacing=-1 })
  display.text({ text=cached.oilPress,  pos=v("40, 955"),       letter=v("60, 120"), font='c7_big', color=white, alignment=1,   width=250, spacing=-10 })
  display.text({ text=cached.rangeKm,   pos=v("1666, 1335"),    letter=v("30, 60"),  font='c7_big', color=white, alignment=1,   width=55,  spacing=-1 })
  display.text({ text=cached.gear,      pos=v("940, 790"),      letter=v("200, 400"),font='599_big',color=white, alignment=0.5, width=0,   spacing=1 })

  if car.handbrake < 0.1 then rect(12894.2, 1306.6, 85, 85, rgb(0,0,0), 1) end
  if car.headlightsActive then rect(22250.3, 668.3, 65, 45, rgb(0,0,0), 1) end

  -- ───── NEW BARS (RPM reveal / OIL / FUEL) ─────
  -- Fractions
  local rpmFrac  = clamp((car.rpm or 0) / getMaxRPM(), 0, 1)
  local oilC     = car.oilTemperature or 0
  local oilFrac  = clamp((oilC - OIL_MIN_C) / math.max(1, (OIL_MAX_C - OIL_MIN_C)), 0, 1)
  local fuelFrac = (car.maxFuel and car.maxFuel > 0) and clamp((car.fuel or 0) / car.maxFuel, 0, 1) or clamp(car.fuel or 0, 0, 1)

  -- Smooth
  smoothRPM  = ema(smoothRPM,  rpmFrac,  SMOOTH_HZ, dt)
  smoothOil  = ema(smoothOil,  oilFrac,  SMOOTH_HZ, dt)
  smoothFuel = ema(smoothFuel, fuelFrac, SMOOTH_HZ, dt)

  -- RPM as texture reveal (draw dark unfilled, then edge)
  drawRpmRevealBar(BAR_RPM.pos, BAR_RPM.size, smoothRPM)
  drawEdge(BAR_RPM.pos, BAR_RPM.size, smoothRPM, RPM_EDGE)

  -- Oil & Fuel as regular smooth color bars (with edges)
  drawBar(BAR_OIL,  smoothOil,  OIL_EDGE)
  drawBar(BAR_FUEL, smoothFuel, FUEL_EDGE)

  -- Average speed (session, moving-time only)
  local sessionKm = debugDistance and simulatedSessionKm or (car.distanceDrivenSessionKm or 0)
  local avgKmh = (movingTimeSec > 0.01) and (sessionKm / (movingTimeSec / 3600.0)) or 0
  local avgDisplay = useMph and (avgKmh / 1.609344) or avgKmh
  display.text({
    text      = string.format("%d", math.floor(avgDisplay + 0.5)),
    pos       = v("12724.7, 1157.7"),
    letter    = v("60, 120"),
    font      = "c7_big",
    color     = white,
    alignment = 0.5,
    width     = 0,
    spacing   = -10
  })
end
