-- =============================================================
-- HELPER FUNCTIONS FOR TIMING & FUEL (Added for new components)
-- =============================================================
local function formatTime(timeMs)
    if timeMs <= 0 then return "-:--.---" end
    local m = math.floor(timeMs / 60000)
    local s = math.floor((timeMs % 60000) / 1000)
    local ms = math.floor((timeMs % 1000) / 10) 
    return string.format("%d:%02d.%02d", m, s, ms)
end

local startLapFuel = 0
local currentLap = -1
local odometerMeters = 0

-- =============================================================
-- PART 2: THE LOGIC 
-- (Heavily based on "lua aero gt.txt")
-- =============================================================

local function nightOrDay()
    local night = rgbm(1, 1, 1, 1) -- Orange/Gold for night
    local day = rgbm(1, 1, 1, 1)     -- Black for day (if background is white)
    
    -- Since our background is black, let's just force Orange always for now
    -- so you can see it.
    return rgbm(1, 1, 1, 1)
end

local function displaySetup()

    -- 1. GEAR
    gearReadout = car.gear

    if gearReadout == -1 then
        gearReadout = "R"
    elseif gearReadout == 0 then
        gearReadout = "N"
    end

    speed = string.format("%.0f", car.speedKmh)
	  rpm = string.format("%.0f", car.rpm)
    perf = string.format("%.02f",math.abs(car.performanceMeter))
    oilTemp =  string.format("%.0f",car.oilTemperature)
    watTemp =  string.format("%.0f",car.waterTemperature)
    
    local tpFL = string.format("%.1f", car.wheels[0].tyrePressure)
    local tpFR = string.format("%.1f", car.wheels[1].tyrePressure)
    local tpRL = string.format("%.1f", car.wheels[2].tyrePressure)
    local tpRR = string.format("%.1f", car.wheels[3].tyrePressure)

        -- Electronics (MAP / ALS / TC / ABS)
    local map = "1" -- Placeholder
    local als = "OFF" -- Placeholder

    local tcMode = car.tractionControlMode or 0
    local absMode = car.absMode or 0
    
    local tcStr = "OFF"
    if tcMode > 0 then
        if car.tractionControlInAction then
            tcStr = "ACT"
        else
            tcStr = string.format("%d", tcMode)
        end
    end

    local absStr = "OFF"
    if absMode > 0 then
        if car.absInAction then
            absStr = "ACT"
        else
            absStr = string.format("%d", absMode)
        end
    end

    if car.lapCount ~= currentLap then
      currentLap = car.lapCount
      startLapFuel = car.fuel
    end
    local lapFuelUsed = startLapFuel - car.fuel
    if lapFuelUsed < 0 then lapFuelUsed = 0 end 

    local lapCountStr = string.format("%d", car.lapCount)
    local bestLapStr  = string.format("%s", formatTime(car.bestLapTimeMs))
    local lastLapStr  = string.format("%s", formatTime(car.previousLapTimeMs))

    local fuelRemainStr = string.format("%.1f", car.fuel * 0.75)
    local fuelLapStr = string.format("%.1f", lapFuelUsed * 0.75)

    -- Temperatures (TMOT/TOIL uses your vars above, TGEAR is placeholder)
    local tmotStr  = string.format("%s", watTemp)
    local toilStr  = string.format("%s", oilTemp)
    local tgearStr = "---" 
    
    -- Delta (Gain / Loss) - using your perf var but adding the + / - sign
    local deltaSign = car.performanceMeter > 0 and "+" or "-"
    local deltaStr  = string.format("%s%s", deltaSign, perf)

    -- Brakes (BRKP & BRKB)
    local brkpStr = string.format("%.0f", car.brake * 80)
    local brkbStr = string.format("%.1f", car.brakeBias * 100)

    -- 3. DISPLAY CALLS
    -- Coordinates adjusted for 4096 width (Center X = 2048)
    

    display.text{
        text = gearReadout,
        pos = vec2(15, 0),    -- X, Y
        letter = vec2(125, 170),  -- Smaller Size
        font = "ks_ruf12r",
        color = nightOrDay(), 
        width = 150, 
        alignment = 0.5
    }    

    display.text{
        text = speed,
        pos = vec2(415, 10),    -- X, Y
        letter = vec2(75, 100),  -- Smaller Size
        font = "ks_ruf12r",
        color = nightOrDay(), 
        width = 150, 
        alignment = 1
    }    
    
    display.text{
        text = rpm,
        pos = vec2(715, 10),    -- X, Y
        letter = vec2(75, 100),  -- Smaller Size
        font = "ks_ruf12r",
        color = nightOrDay(), 
        width = 150, 
        alignment = 1
    }        

    local smallFont = vec2(30, 50)

    -- TIMING & DELTA (Far Right Stack)
    display.text{ text = lapCountStr, pos = vec2(270, 285), letter = smallFont, font = "ks_ruf12r", color = nightOrDay(), width = 300, alignment = 0 }
    display.text{ text = deltaStr, pos = vec2(450, 285), letter = smallFont, font = "ks_ruf12r", color = nightOrDay(), width = 300, alignment = 0 }
    display.text{ text = lastLapStr, pos = vec2(770, 285), letter = smallFont, font = "ks_ruf12r", color = nightOrDay(), width = 300, alignment = 0 }

    local clockStr = string.format("%02d:%02d", math.floor(sim.timeHours), math.floor(sim.timeMinutes))
    local airTempStr = string.format("%.0f C", sim.ambientTemperature or 0)
    local odoStr = string.format("%04d", math.floor(odometerMeters / 1000))
    local smallFont2 = vec2(30, 45)

    display.text{ text = clockStr, pos = vec2(25, 470), letter = smallFont2, font = "ks_ruf12r", color = nightOrDay(), width = 150, alignment = 0 }
    display.text{ text = odoStr, pos = vec2(825, 470), letter = smallFont2, font = "ks_ruf12r", color = nightOrDay(), width = 150, alignment = 0 }

    local fuelPct = car.fuel / car.maxFuel  -- Gets percentage of fuel (0.0 to 1.0)
    
    -- Configure your fuel bar appearance here:
    local barStartX = 890           -- X position of the first square
    local barStartY = 410          -- Y position of the fuel bar
    local squareWidth = 15         -- Width of each square
    local squareHeight = 45        -- Height of each square
    local squareSpacing = 18       -- Distance from the start of one square to the next

    -- Loop to draw 6 squares
    for i = 1, 7 do
        -- Calculate the threshold for this specific square (e.g., square 3 requires >33% fuel)
        local threshold = (i - 1) / 7 
        
        local squareColor
        if fuelPct > threshold then
            squareColor = nightOrDay()            -- Filled square (Red)
        else
            squareColor = rgbm(0.6, 0.6, 0.6, 0.2)  -- Empty square (Dim Dark Grey)
        end
        
        display.rect{
            pos = vec2(barStartX + ((i - 1) * squareSpacing), barStartY),
            size = vec2(squareWidth, squareHeight),
            color = squareColor
        }
    end


end

-- =============================================================
-- PART 3: MAIN LOOP
-- =============================================================

function script.update(dt)

    if car.speedKmh > 1 then
      odometerMeters = odometerMeters + ((car.speedKmh / 3.6) * dt)
    end    
    displaySetup()  

end