-- ============================================================================
--  CLEAN CLUSTER — ONLY BACKGROUND + TEXT + G-FORCE
--  (RPM bars, Oil/Boost bars, Torque/Power, Overlay removed)
--  + Fuel/Water boxes with individual Start/Size
-- ============================================================================

local car = ac.getCar(0)

-- BACKGROUND IMAGE
local CLUSTER_BACKGROUND_IMAGE = "cluster/Speedometer.dds"
local CLUSTER_SIZE = vec2(2048, 2048)

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)

-- Helper functions
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 ema(prev, target, hz, dt)
  dt = dt or 0.016
  local k = math.exp(-hz * dt)
  return target + (prev - target) * k
end

-- ============================================================================
--  G-FORCE METER
-- ============================================================================

local DOT_TEXTURE = "cluster/g_force_dot.png"
local DOT_SIZE    = vec2(55, 55)
local GF_CENTER   = vec2(1636, 1102)
local G_RADIUS    = 115
local MAX_G       = 1.0
local EMA_HZ_G    = 7.5

local GF_SmoothedAccel = { x = 0, z = 0 }

-- 🔧 UNIVERSAL DECIMAL/CHAR SPACING FOR ALL G-FORCE TEXTS
local GF_DECIMAL_SPACING = -10     -- tweak this to taste
local GF_TEXT_LETTER     = vec2(30, 60)
local GF_TEXT_FONT       = "fonts/audi_vln_hd"

local function gforce_update(dt)
  local gx = ema(GF_SmoothedAccel.x, car.acceleration.x or 0, EMA_HZ_G, dt)
  local gz = ema(GF_SmoothedAccel.z, car.acceleration.z or 0, EMA_HZ_G, dt)
  GF_SmoothedAccel.x, GF_SmoothedAccel.z = gx, gz

  local ang = math.atan2(gz, gx)
  local mag = clamp(math.sqrt(gx*gx + gz*gz) / math.max(0.001, MAX_G), 0, 1)
  local pos = GF_CENTER + vec2(math.cos(ang), math.sin(ang)) * (G_RADIUS * mag)

  display.image({
    image = DOT_TEXTURE,
    pos = vec2(pos.x - DOT_SIZE.x * 0.5, pos.y - DOT_SIZE.y * 0.5),
    size = DOT_SIZE,
    color = rgb (1,1,0)
  })

  local col = rgbm(1,1,1,1)

  -- Right (positive X)
  display.text({
    text   = string.format("%.1f", math.max(gx, 0)),
    pos    = vec2(1773.1, 1082),
    letter = GF_TEXT_LETTER,
    font   = GF_TEXT_FONT,
    color  = col,
    spacing = GF_DECIMAL_SPACING
  })

  -- Left (negative X)
  display.text({
    text   = string.format("%.1f", math.max(-gx, 0)),
    pos    = vec2(1437, 1082),
    letter = GF_TEXT_LETTER,
    font   = GF_TEXT_FONT,
    color  = col,
    spacing = GF_DECIMAL_SPACING
  })

  -- Top (negative Z / braking)
  display.text({
    text   = string.format("%.1f", math.max(-gz, 0)),
    pos    = vec2(1603, 932),
    letter = GF_TEXT_LETTER,
    font   = GF_TEXT_FONT,
    color  = col,
    spacing = GF_DECIMAL_SPACING
  })

  -- Bottom (positive Z / accel)
  display.text({
    text   = string.format("%.1f", math.max(gz, 0)),
    pos    = vec2(1602, 1235),
    letter = GF_TEXT_LETTER,
    font   = GF_TEXT_FONT,
    color  = col,
    spacing = GF_DECIMAL_SPACING
  })
end
-- ============================================================================
--  BOXES: FUEL + WATER (INDIVIDUAL POS / SIZE) — *HIDE OFF BOXES ONLY*
-- ============================================================================

-- Color used to hide a box (completely transparent black mask)
local BOX_HIDE = rgbm(0, 0, 0, 1)   -- change alpha if needed

-- 🔧 FUEL – individual boxes (edit Start/Size per box)
local FuelBoxes = {
  { Start = "1072.8, 1827.7", Size = "56.1, 21.1" },
  { Start = "1130.1, 1811", Size = "50.1, 32.7" },
  { Start = "1173.8, 1768.5", Size = "33.5, 46.1" },
  { Start = "1195.4, 1720.2", Size = "33.3, 48" },
  { Start = "1209.2, 1677.7", Size = "29.8, 44.1" },
  { Start = "1222.1, 1632.2", Size = "34.5, 46.3" },
  { Start = "1237.4, 1584.9", Size = "33.7, 47.2" },
  { Start = "1250.8, 1533.6", Size = "44.1, 51.3" },
  { Start = "1266.5, 1493.9", Size = "38.1, 45.1" },
  { Start = "1280.1, 1445.3", Size = "37.4, 47" },
}

-- The fuel level at which ALL boxes are still visible
local FUEL_LAST_BOX_LIT_AT_L = 45.0


-- 🔧 WATER – individual boxes
local WaterBoxes = {
  { Start = "885.9, 1832", Size = "56.9, 24.6" },
  { Start = "836.4, 1816.9", Size = "46.5, 35.8" },
  { Start = "808.7, 1773.9", Size = "32.3, 47.4"},
  { Start = "786.6, 1725.7", Size = "36.4, 49.2" },
  { Start = "772.5, 1682.9", Size = "35, 46.1" },
  { Start = "758.5, 1637.8", Size = "33.7, 45.7"},
  { Start = "743.2, 1590", Size = "33.9, 48.4" },
  {Start = "725.6, 1544.3", Size = "33.9, 46.1" },
  { Start = "714.3, 1496", Size = "33.3, 48.8"},
  { Start = "691.2, 1451.5", Size = "42.3, 48" },
}

local WATER_TEMP_MIN_C           = 60.0
local WATER_TEMP_LAST_BOX_LIT_AT = 99.0


-- Helper
local function v2(str)
    local a,b = str:match("([^,]+),%s*([^,]+)")
    return vec2(tonumber(a), tonumber(b))
end

-- Draw mask over OFF boxes (ON boxes = do nothing)
local function maskOffBoxes(boxList, litCount)
    for i, box in ipairs(boxList) do
        if i > litCount then
            display.rect({
                pos  = v2(box.Start),
                size = v2(box.Size),
                color = BOX_HIDE   -- full opacity → hides the box in the texture
            })
        end
    end
end

-- Compute lit fuel boxes
local function updateFuelBoxes()
    local fuel = car.fuel or 0
    local fullAt = FUEL_LAST_BOX_LIT_AT_L

    local frac = clamp(fuel / fullAt, 0, 1)
    local lit  = math.ceil(frac * #FuelBoxes)

    maskOffBoxes(FuelBoxes, lit)
end

-- Compute lit water boxes (low → high)
local function updateWaterBoxes()
    local temp = car.waterTemperature or 0

    local frac = clamp((temp - WATER_TEMP_MIN_C) /
                      (WATER_TEMP_LAST_BOX_LIT_AT - WATER_TEMP_MIN_C), 0, 1)

    local lit = math.ceil(frac * #WaterBoxes)

    maskOffBoxes(WaterBoxes, lit)
end


-- ============================================================================
--  MAIN UPDATE (RPM/OIL/BOOST REMOVED — TEXTS KEPT)
-- ============================================================================

local fuelKmsPerLitre = 9
local movingTimeSec = 0

local TIME_LETTER  = vec2(30, 100) 

local function cluster_update(dt)

  -- Speed (MPH)
  local speedKmh = car.speedKmh
  local speed = speedKmh / 1.609344
  if speedKmh > 0.5 then movingTimeSec = movingTimeSec + dt end

  display.text({
    text     = math.floor(speed),
    pos      = v("1515, 760"),
    letter   = vec2(90, 160),
    font     = 'fonts/helvetica_narrow',
    color    = white,
    alignment= 1,
    width    = 285
  })

  -- Water Temperature (displayed)
  display.text({
    text     = math.floor(car.waterTemperature / 0.8),
    pos      = v("700.3, 1055"),
    letter   = vec2(32.5, 65),
    font     = 'fonts/m4_font',
    color    = rgb (1,1,1),
    alignment= 1,
    width    = 250
  })

  -- Oil Temperature
  display.text({
    text     = math.floor(car.oilTemperature / 0.8),
    pos      = v("700.3, 1140"),
    letter   = vec2(32.5, 65),
    font     = 'fonts/m4_font',
    color    = rgb (1,1,1),
    alignment= 1,
    width    = 250
  })

  -- Oil Pressure
  display.text({
    text     = math.floor(car.oilPressure/ 0.145038),
    pos      = v("700.3, 1220"),
    letter   = vec2(32.5, 65),
    font     = 'fonts/m4_font',
    color    = rgb (1,1,1),
    alignment= 1,
    width    = 250
  })

  -- Turbo
  display.text({
    text     = math.floor(car.turboBoost/ 0.145038),
    pos      = v("1002, 1220"),
    letter   = vec2(32.5, 65),
    font     = 'fonts/m4_font',
    color    = rgb (1,1,1),
    alignment= 1,
    width    = 250
  })

  -- IAT1 based on ambient + heat soak factor
  local amb   = sim.ambientTemperature or 20
  local water = car.waterTemperature or amb
  local speed2 = car.speedKmh or 0

  local slowFactor = math.max(0, math.min(1, 1 - speed2 / 80))
  local iat1_c = amb + 2 + (water - amb) * 0.15 * slowFactor
  iat1_c = math.max(amb, math.min(iat1_c, water))

  -- Convert to Fahrenheit
  local iat1_f = iat1_c * 9/5 + 32

  display.text({
      text      = string.format("%d", math.floor(iat1_f)),
      pos       = v("1002, 1055"),
      letter    = vec2(32.5, 65),
      font      = 'fonts/m4_font',
      color     = rgb(1,1,1),
      alignment = 1,
      width     = 250
  })

  -- charge air temp
  local boostBar = car.turboBoost or 0
  local charge_c = amb + 8 + boostBar * 25 + (water - amb) * 0.2
  charge_c = math.max(amb + 5, math.min(charge_c, water + 40))

  -- Convert to Fahrenheit
  local charge_f = charge_c * 9/5 + 32

  display.text({
      text      = string.format("%d", math.floor(charge_f)),
      pos       = v("1002, 1138"),
      letter    = vec2(32.5, 65),
      font      = 'fonts/m4_font',
      color     = rgb(1,1,1),
      alignment = 1,
      width     = 250
  })

  -- Gear
  display.text({
    text     = gearT[car.gear],
    pos      = v("970, 792"),
    letter   = vec2(125, 280),
    font     = 'fonts/eurostile_extd',
    color    = white,
    alignment= 0.5
  })

  -- 🔥 Boxes
  updateFuelBoxes()
  updateWaterBoxes()
end

-- FINAL UPDATE
function update(dt)
  cluster_update(dt)
  gforce_update(dt)
end
