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
------------------------------------------------------------
-- average distance you travel per litre of fuel (km / L)
local fuelKmsPerLitre = 9       --  ❮❮ tweak for your car

------------------------------------------------------------
--  NEEDLE (ARROW) SETTINGS ― ONLY NEW SECTION ADDED
------------------------------------------------------------
local needleTex    = "./cluster/needle_centered_reworked.png"   -- texture file
local needleSize   = vec2(900, 900)           -- w, h of PNG
local needlePivot  =  vec2(399, 1000)          -- screen coords of centre
local needleMinDeg = 133                     -- angle at 0 km/h
local needleMaxDeg =  -133                     -- angle at max
local needleMaxVal = 360                      -- value at needleMaxDeg

------------------------------------------------------------
--  SECOND NEEDLE (RPM) SETTINGS
------------------------------------------------------------
local rpmNeedleTex    = "./cluster/needle_centered_reworked.png"  -- can be same PNG or another
local rpmNeedleSize   = vec2(900, 900)

local rpmNeedlePivot  = vec2(1655, 1000)         -- where the tach needle spins
local rpmNeedleMinDeg = -0                    -- angle at 0 rpm
local rpmNeedleMaxDeg = -170                    -- angle at red-line
local rpmNeedleMaxVal =  8000                   -- rpm that maps to maxDeg

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


-- Settings
local debugMode = false         -- Simulated speed
local debugDistance = false     -- Simulated km from speed
local useMph = false            -- Toggle MPH vs KMH
local simulatedSpeedKmh = 0

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

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

-- Cache for display values
local cached = {}

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

------------------------------------------------------------
--  NEEDLE HELPERS ― ONLY NEW FUNCTIONS ADDED
------------------------------------------------------------
local function lerp(a, b, t) return a + (b - a) * t end

local function needleAngle(val)              -- maps value → angle
    local t = math.min(math.max(val / needleMaxVal, 0), 1)  -- clamp 0-1
    return lerp(needleMinDeg, needleMaxDeg, t)
end

local function rpmNeedleAngle(val)                     -- 0 … rpmNeedleMaxVal
    local t = math.min(math.max(val / rpmNeedleMaxVal, 0), 1)
    return lerp(rpmNeedleMinDeg, rpmNeedleMaxDeg, t)   -- maps to degrees
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

    -- 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
    display.text({
        text = cached.time,
        pos = v("1235.1, 686"),
        letter = v("30, 60"),
        font = 'sls',
        color = white,
        alignment = 0.9,
        width = 0,
        spacing = -5
    })

    -- 🚗 SPEED DISPLAY
    display.text({
        text = cached.speed,
        pos = v("810.5, 725.1"),
        letter = v("80, 160"),
        font = 'c7_big',
        color = white,
        alignment = 1,
        width = 255,
        spacing = -15
    })

    -- 📏 TOTAL DISTANCE DISPLAY
    display.text({
        text = cached.totalKm,
        pos = v("907.1, 1015.2"),
        letter = v("30, 60"),
        font = 'sls',
        color = white,
        alignment = 0.5,
        width = 250,
        spacing = 0
    })

    -- 📏 SESSION DISTANCE DISPLAY
    display.text({
        text = cached.sessionKm,
        pos = v("907.1, 910.2"),
        letter = v("30, 60"),
        font = 'sls',
        color = white,
        alignment = 0.5,
        width = 250,
        spacing = 0
    })

    -- 🌡️ TEMPERATURE DISPLAY
    display.text({
        text = cached.temp,
        pos = v("725.5, 680.4"),
        letter = v("30, 60"),
        font = 'sls',
        color = white,
        alignment = 0.0,
        width = 0,
        spacing = -3
    })

    -- 🛣 RANGE DISPLAY
    display.text({
        text      = cached.rangeKm,
        pos       = v("450.4, 1239.5"),
        letter    = v("19, 50"),
        font      = 'sls',
        color     = white,
        alignment = 1,
        width     = 55,
        spacing   = -1
    })

    -- ℉ UNIT LABEL
    display.text({
        text = "F",
        pos = v("1364.6, 1350.3"),
        letter = v("20, 60"),
        font = 'e92_big',
        color = white,
        alignment = 0.0,
        width = 0,
        spacing = 0
    })

    -- ⚙️ GEAR DISPLAY
    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
    })

    -- 🅿️ PARKING BRAKE SYMBOL COVER
    if car.handbrake < 0.1 then
        display.rect({
            pos = vec2(1894.2, 1306.6),
            size = vec2(85.0, 85.0),
            color = rgb(0, 0, 0),
            corner = 0,
            border = 0,
            opacity = 1
        })
    end

-- Hide Low-beam symbol when headlights are OFF
if not car.headlightsActive then
    display.rect({
        pos = vec2(144.3, 1316.1),
        size = vec2(70.0, 65.0),
        color = rgb(0, 0, 0),
        corner = 0,
        border = 0,
        opacity = 1
    })
end

------------------------------------------------------------------
--   TURNSIGNALS
------------------------------------------------------------------
local iconSize = 60
local turnL    = vec2(610, 680)

-- Auto-mirrored right-side position
local screenW  = (ui.windowSize and ui.windowSize().x) or 1920
local turnR    = vec2(screenW - turnL.x - iconSize, turnL.y)

-- Blink timer
if car.turningLeftLights or car.turningRightLights then
    setInterval(function() indicatorActive = not indicatorActive end, 0.334, "indicatorActive")
else
    clearInterval("indicatorActive")
    indicatorActive = false
end

-- LEFT
if car.turningLeftOnly and indicatorActive then
    ui.beginRotation()
    ui.drawImage("./cluster/turn_signal.png",
        turnL,
        vec2(turnL.x + iconSize, turnL.y + iconSize),
        rgbm(0.1, 1, 0.1, 1))
    ui.endRotation(-90)

-- RIGHT
elseif car.turningRightOnly and indicatorActive then
    ui.drawImage("./cluster/turn_signal.png",
        turnR,
        vec2(turnR.x + iconSize, turnR.y + iconSize),
        rgbm(0.1, 1, 0.1, 1))

-- HAZARDS
elseif car.hazardLights and indicatorActive then
    local pos1 = turnR
    ui.drawImage("./cluster/turn_signal.png", pos1, vec2(pos1.x + iconSize, pos1.y + iconSize), rgbm(0.1, 1, 0.1, 1))

    local pos2 = turnL
    ui.beginRotation()
    ui.drawImage("./cluster/turn_signal.png", pos2, vec2(pos2.x + iconSize, pos2.y + iconSize), rgbm(0.1, 1, 0.1, 1))
    ui.endRotation(-90)
end


end
