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

local white = rgb(1, 1, 1)

------------------------------------------------------------
--  RANGE-CALC SETTINGS
------------------------------------------------------------
local fuelKmsPerLitre = 9

-- Settings
local debugMode = false
local debugDistance = false
local useMph = false
local simulatedSpeedKmh = 0

-- Refresh settings
local REFRESH = 0.2
local refreshTimer = 0

-- Distance tracking for debug
local simulatedSessionKm = 0
local simulatedTotalKm = 0

-- Driving mode params 
local SuspMode = 1
local prev_extraB = car.extraB

-- Cache for display values
local cached = {}

-- Helper: convert "X, Y" → vec2
local function v(str)
  local x, y = str:match("([^,]+),%s*([^,]+)")
  return vec2(tonumber(x), tonumber(y))
end

-- Small utils (also used by torque/power sim)
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 or 8) * dt)
  return target + (prev - target) * k
end

----------------------------------------------------------------------
-- Smooth bar configs (positions, sizes, colors)
----------------------------------------------------------------------
local FUEL_BAR = {
  pos   = v("948, 1293"),
  size  = v("181, 14"),
  bg    = rgbm(0, 0, 0, 0),
  fill  = rgb(1, 0.6, 0)
}

local TURBO_BAR = {
  pos   = v("411.3, 919"),
  size  = v("301, 18"),
  bg    = rgbm(0, 0, 0, 0),
  fill  = rgb(1.00, 0.6, 0)
}

-- NEW: torque & power bars (adjust positions if you like)
local TORQUE_BAR = {
  pos   = v("475, 1047"),
  size  = v("188, 20"),
  bg    = rgbm(0, 0, 0, 0),
  fill  = rgb(1.00, 0.1, 0) -- orange-red
}
local POWER_BAR = {
  pos   = v("475, 1000"),
  size  = v("188, 20"),
  bg    = rgbm(0, 0, 0, 0),
  fill  = rgb(1.00, 0.1, 0) -- orange-red
}

-- Optional numeric readouts for torque/power:
local SHOW_TQPW_TEXT = true
local TORQUE_TXT_POS = vec2(TORQUE_BAR.pos.x + TORQUE_BAR.size.x + 12, TORQUE_BAR.pos.y - 6)
local POWER_TXT_POS  = vec2(POWER_BAR.pos.x  + POWER_BAR.size.x  + 12, POWER_BAR.pos.y  - 6)

-- Draw a smooth left→right bar (no outline)
local function drawSmoothBar(bar, fraction)
  local frac = clamp(fraction or 0, 0, 1)
  display.rect({ pos = bar.pos, size = bar.size, color = bar.bg, opacity = 1 })
  local w = math.floor(bar.size.x * frac + 0.5)
  if w > 0 then
    display.rect({ pos = bar.pos, size = vec2(w, bar.size.y), color = bar.fill, opacity = 1 })
  end
end

-- Robust fuel % reader
local function fuelPercent()
  local st = (ac and ac.getCarState) and ac.getCarState(0) or nil
  local fuel = (st and st.fuel) or (car and car.fuel) or 0
  local cap  = (st and st.fuelCapacity) or (car and car.maxFuel) or 0
  if cap and cap > 0 and fuel >= 0 and fuel <= cap * 1.5 then
    return clamp(fuel / cap, 0, 1)
  end
  if fuel <= 1.05 then
    return clamp(fuel, 0, 1)
  end
  return 0
end

-- Robust turbo % reader
local function turboPercent()
  if not car then return 0 end
  if car.turboBoost ~= nil then
    return clamp(car.turboBoost, 0, 1)
  elseif car.boostRatio ~= nil then
    return clamp(car.boostRatio, 0, 1)
  elseif car.boostPressure ~= nil and car.maxBoostPressure ~= nil and car.maxBoostPressure > 0 then
    return clamp(car.boostPressure / car.maxBoostPressure, 0, 1)
  end
  local st = (ac and ac.getCarState) and ac.getCarState(0) or nil
  if st and st.turboBoost then return clamp(st.turboBoost, 0, 1) end
  return 0
end

----------------------------------------------------------------------
-- Simulated torque/power
----------------------------------------------------------------------

-- Tune these to your car:
local IDLE_RPM        = 850
local PEAK_TORQUE_NM  =705     -- plateau peak torque
local PEAK_TORQUE_RPM = 4850    -- start of plateau
local PLATEAU_END_RPM = 5050    -- end of plateau
local REDLINE_RPM     = 7000
local TORQUE_AT_REDLINE_FRACTION = 0.75  -- torque falloff at redline vs peak
local THROTTLE_EFFECT = 1.0              -- 0=ignore throttle, 1=linear

-- smoothing for visuals
local SMOOTH_HZ = 10

-- curve
local function simulatedTorqueNm(rpm, throttle)
  rpm = clamp(rpm or 0, IDLE_RPM, REDLINE_RPM)
  local tIdle    = PEAK_TORQUE_NM * 0.35
  local tPeak    = PEAK_TORQUE_NM
  local tRedline = PEAK_TORQUE_NM * TORQUE_AT_REDLINE_FRACTION
  local base
  if rpm <= PEAK_TORQUE_RPM then
    local t = (rpm - IDLE_RPM) / math.max(1, (PEAK_TORQUE_RPM - IDLE_RPM))
    base = lerp(tIdle, tPeak, clamp(t,0,1))
  elseif rpm <= PLATEAU_END_RPM then
    base = tPeak
  else
    local t = (rpm - PLATEAU_END_RPM) / math.max(1, (REDLINE_RPM - PLATEAU_END_RPM))
    base = lerp(tPeak, tRedline, clamp(t,0,1))
  end
  local gas = clamp(throttle or (car and car.gas) or 0, 0, 1)
  if THROTTLE_EFFECT > 0 then
    local minFrac = 0.15
    base = base * lerp(minFrac, 1.0, gas ^ THROTTLE_EFFECT)
  end
  return math.max(0, base)
end

local function powerKWfromNm(torqueNm, rpm)
  return (torqueNm or 0) * (rpm or 0) / 9549.0
end

-- precompute max power from the curve (WOT sweep)
local PRECOMP_MAX_TORQUE = PEAK_TORQUE_NM
local PRECOMP_MAX_POWER_KW = (function()
  local best = 0
  for r = IDLE_RPM, REDLINE_RPM, 50 do
    local tNm = simulatedTorqueNm(r, 1.0)
    local pKW = powerKWfromNm(tNm, r)
    if pKW > best then best = pKW end
  end
  return math.max(1, best)
end)()

-- state
local smoothTorqueNm, smoothPowerKW = 0, 0

------------------------------------------------------------

local 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

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

  -- Refresh cache
  refreshTimer = refreshTimer - dt
  if refreshTimer <= 0 then
    refreshTimer = REFRESH
    cached.time        = string.format("%02d:%02d", sim.timeHours, sim.timeMinutes)
    cached.speed       = math.floor(speed)
    cached.temp        = string.format("%.1d", sim.ambientTemperature)
    cached.fuel        = math.floor(car.fuel)
    cached.gear        = gearT[car.gear]
    cached.rangeKm     = math.floor(car.fuel * fuelKmsPerLitre)
    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

  -- 🕒 TIME
  display.text({ text=cached.time, pos=v("1424, 754"), letter=v("24, 48"),
    font='sls', color=white, alignment=0.9, width=0, spacing=-5 })

  -- 🚗 SPEED
  display.text({ text=cached.speed, pos=v("900, 980"), letter=v("60, 120"),
    font='c7_big', color=white, alignment=0.5, width=255, spacing=-10 })

  -- 🌡 AMBIENT TEMP
  display.text({ text=cached.temp, pos=v("2543, 758"), letter=v("24, 48"),
    font='sls', color=white, alignment=0.0, width=0, spacing=-3 })

  -- 🌡 AMBIENT TEMP
  display.text({ text="c", pos=v("2593, 745"), letter=v("24, 48"),
    font='sls', color=white, alignment=0.0, width=0, spacing=-3 })

  -- ⚙️ GEAR
  display.text({ text=cached.gear, pos=v("21545.9, 712.8"), letter=v("10, 10"),
    font='digital_big', color=white, alignment=0.5, width=0, spacing=1 })

  -- 🗓 DATE
  local dtbl = (ac and ac.getDateTime and ac.getDateTime()) or os.date("*t")
  display.text({ text=string.format("%02d/%02d/%04d", dtbl.month,dtbl.day,dtbl.year),
    pos=v("1320, 1050"), letter=v("20, 40"), font="amg", color=white,
    alignment=1, width=350, spacing=-2.5 })

  -- 🗓 DAY
  local dayText
  if type(dtbl)=="table" then
    if dtbl.wday then
      local days={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
      dayText = days[dtbl.wday]
    elseif dtbl.weekday then
      local daysMon0={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"}
      dayText = daysMon0[(dtbl.weekday % 7) + 1]
    end
    if not dayText and dtbl.year and dtbl.month and dtbl.day then
      local w=os.date("*t", os.time{year=dtbl.year,month=dtbl.month,day=dtbl.day,hour=12}).wday
      local days={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
      dayText = days[w]
    end
  end
  dayText = dayText or os.date("%A")
  display.text({ text=dayText, pos=v("1420, 965"), letter=v("25, 50"),
    font="amg", color=white, alignment=0.5, width=350, spacing=-3 })

-- drs active


  ------------------------------------------------------------------
  -- Smooth bars: Fuel & Turbo
  ------------------------------------------------------------------
  drawSmoothBar(FUEL_BAR,  fuelPercent())
  drawSmoothBar(TURBO_BAR, turboPercent())

  ------------------------------------------------------------------
  -- NEW: Simulated torque/power
  ------------------------------------------------------------------
local rpm = (car and car.rpm) or 0
local gas = (car and (car.gas or car.throttle)) or 0

-- Only update if above idle
local tNm, pKW = 0, 0
if rpm > (IDLE_RPM + 200) then  -- 200 RPM buffer to avoid flicker
    tNm = simulatedTorqueNm(rpm, gas)
    pKW = powerKWfromNm(tNm, rpm)

    smoothTorqueNm = ema(smoothTorqueNm, tNm, SMOOTH_HZ, dt)
    smoothPowerKW  = ema(smoothPowerKW,  pKW, SMOOTH_HZ, dt)
else
    -- Force zero visuals at idle
    smoothTorqueNm = ema(smoothTorqueNm, 0, SMOOTH_HZ, dt)
    smoothPowerKW  = ema(smoothPowerKW,  0, SMOOTH_HZ, dt)
end

local tqFrac = clamp(smoothTorqueNm / PRECOMP_MAX_TORQUE, 0, 1)
local pwFrac = clamp(smoothPowerKW  / PRECOMP_MAX_POWER_KW, 0, 1)

drawSmoothBar(TORQUE_BAR, tqFrac)
drawSmoothBar(POWER_BAR,  pwFrac)

  -- Driving mode symbol 

  if car.extraB ~= prev_extraB then 
    SuspMode = SuspMode + 0.5 
    prev_extraB = car.extraB
    SuspModeTime = 0
  end

  if SuspMode >= 5 then
    SuspMode = 0
  end

    if SuspMode == 1 or SuspMode == 1.5 then
        local pos = vec2(953, 1080)
        ui.drawImage("./cluster/sport.png", pos,vec2(pos.x+60, pos.y+60), rgbm(1,1,1,1) )
    end

    if SuspMode == 2 or SuspMode == 2.5 then
        local pos = vec2(953, 1079)
        ui.drawImage("./cluster/sport_plus.png", pos,vec2(pos.x+60, pos.y+62), rgbm(1,1,1,1) )
    end

    if SuspMode >= 3 then
        local pos = vec2(953, 1080)
        ui.drawImage("./cluster/race.png", pos,vec2(pos.x+60, pos.y+60), rgbm(1,1,1,1) )
    end

  if SuspMode >= 4 then display.text({ text = "DR", pos = v("1261.3, 1280"), letter = v("25, 50"),
    font ='amg2', color = rgbm (1,0.9,0,1), alignment = 1, width = 0, spacing = -6 })
end
  if SuspMode >= 4 then display.text({ text = "IFT", pos = v("1295, 1280"), letter = v("25, 50"),
    font ='amg2', color = rgbm (1,0.9,0,1), alignment = 1, width = 0, spacing = -8 })
end

ac.debug("SuspMode", SuspMode)


end
