-- GUAP WET ROADS v1.0

local enabled = false
local wetPreset = 1
local floodOn = false
local currentPreset = 0
local roadMeshes = nil
local foundNames = {}
local statusMsg = "Ready"
local customInput = "mat_road"
local origValues = nil
local floodActive = false
local extConfigPath = nil

-- Road material search patterns
local searchPatterns = {
  'material:mat_road??',
  'material:mat_road_??',
  'material:mat_road_??_*',
  'material:road??',
  'material:road_??',
  'material:road*',
  'material:asphalt*',
  'material:tarmac*',
  'material:street*',
  'material:highway*',
  'material:pavement*',
  'material:pitlane*',
  'material:pit_road*',
  'material:racing*',
  'material:track_road*',
}

local function tryFind(pattern)
  local ok, result = pcall(ac.findMeshes, pattern)
  if ok and result and not result:empty() then
    return result
  end
  return nil
end

local function doSearch()
  statusMsg = "Searching..."
  roadMeshes = nil
  foundNames = {}
  origValues = nil

  for _, pattern in ipairs(searchPatterns) do
    local found = tryFind(pattern)
    if found then
      local count = found:size()
      foundNames[#foundNames + 1] = pattern:gsub('material:', '') .. ' (' .. count .. ')'
      if roadMeshes == nil then
        roadMeshes = found
      else
        roadMeshes = roadMeshes:makeUnionWith(found)
      end
    end
  end

  if customInput and #customInput > 0 then
    local customWild = tryFind('material:' .. customInput .. '*')
    if customWild then
      foundNames[#foundNames + 1] = customInput .. '* (' .. customWild:size() .. ')'
      if roadMeshes == nil then
        roadMeshes = customWild
      else
        roadMeshes = roadMeshes:makeUnionWith(customWild)
      end
    end
  end

  if roadMeshes and not roadMeshes:empty() then
    roadMeshes:ensureUniqueMaterials()
    statusMsg = "Found " .. roadMeshes:size() .. " meshes"
    origValues = {}
    local propsToSave = {
      'ksDiffuse', 'ksSpecular', 'ksSpecularEXP',
      'fresnelC', 'fresnelEXP', 'fresnelMaxLevel', 'extBounceBack'
    }
    for _, prop in ipairs(propsToSave) do
      local val = roadMeshes:getMaterialPropertyValue(prop)
      if val ~= nil then origValues[prop] = val end
    end
  else
    statusMsg = "No matching meshes"
    roadMeshes = nil
  end
end

local function setProps(props)
  if not roadMeshes then return end
  for k, v in pairs(props) do
    roadMeshes:setMaterialProperty(k, v)
  end
end

local function applyPreset(idx)
  if idx == 1 then
    setProps({ksDiffuse=0.4, ksSpecular=0.1, ksSpecularEXP=5000000, fresnelC=0, fresnelEXP=1, fresnelMaxLevel=0.5, extBounceBack=0})
  elseif idx == 2 then
    setProps({ksDiffuse=0.55, ksSpecular=0.5, ksSpecularEXP=500000000, fresnelC=10, fresnelEXP=0, fresnelMaxLevel=0.6, extBounceBack=0})
  elseif idx == 3 then
    setProps({ksDiffuse=0.7, ksSpecular=1.0, ksSpecularEXP=500000000, fresnelC=1, fresnelEXP=0, fresnelMaxLevel=0.7, extBounceBack=10})
  end
  currentPreset = idx
end

local function revertDry()
  if not roadMeshes then return end
  if origValues then setProps(origValues) end
  currentPreset = 0
end

local function getExtConfigPath()
  if extConfigPath then return extConfigPath end
  local tracksDir = ac.getFolder(ac.FolderID.ContentTracks)
  local trackId = ac.getTrackID()
  local rootDir = ac.getFolder(ac.FolderID.Root)
  if not trackId then return nil end
  local extDir
  if tracksDir and #tracksDir > 0 then
    extDir = tracksDir .. '/' .. trackId .. '/extension'
  elseif rootDir and #rootDir > 0 then
    extDir = rootDir .. '/content/tracks/' .. trackId .. '/extension'
  else
    return nil
  end
  io.createDir(extDir)
  extConfigPath = extDir .. '/ext_config.ini'
  return extConfigPath
end

local function checkFloodActive()
  local path = getExtConfigPath()
  if not path then return false end
  local content = io.load(path)
  if not content then return false end

  if (content:find('Type%s*=%s*POND', 1) or content:find('Type%s*=%s*SEA', 1)) and
     content:find('Materials%s*=%s*mat_road', 1) then
    floodActive = true
    floodOn = true
    return true
  end
  return false
end

local function enableFlood()
  local path = getExtConfigPath()
  if not path then
    statusMsg = "Cannot find ext_config path"
    return
  end

  local mats = customInput .. "??, road??, asphalt??, tarmac??, street??, highway??"

  local content = io.load(path) or ""
  if not content:find('common/materials_track.ini', 1, true) then
    content = "[INCLUDE: common/materials_track.ini]\n\n" .. content
    io.save(path, content)
  end

  local ini = ac.INIConfig.load(path)

  ini:setAndSave('Material_Water', 'Materials', mats)
  ini:setAndSave('Material_Water', 'Type', 'POND')
  ini:setAndSave('Material_Water', 'FirstNormalMap', 'water_nm.dds')
  ini:setAndSave('Material_Water', 'SecondNormalMap', 'water_nm.dds')

  ini:setAndSave('Material_Water_WET_ROADS_FLOOD', nil)

  floodActive = true
  statusMsg = "Flood enabled (POND)"
end

local function disableFlood()
  local path = getExtConfigPath()
  if not path then return end

  local ini = ac.INIConfig.load(path)

  ini:setAndSave('Material_Water', 'Materials', nil)
  ini:setAndSave('Material_Water', 'Type', nil)
  ini:setAndSave('Material_Water', 'FirstNormalMap', nil)
  ini:setAndSave('Material_Water', 'SecondNormalMap', nil)

  ini:setAndSave('Material_Water_WET_ROADS_FLOOD', nil)

  floodActive = false
  statusMsg = "Flood removed from config"
end

-- =====================
-- NEW MODERN UI SYSTEM
-- =====================

local startupChecked = false
local currentTab = 1
local labels = {'Damp (20%)', 'Wet (50%)', 'Soaked (100%)'}
local accentColor = rgbm(0.35, 0.65, 0.88, 0.9) -- Blue accent based on logo, slightly transparent

local tabs = {
  {name = "Surface Wetness"},
  {name = "Track Flooding"},
  {name = "Settings & Log"}
}

function script.windowMain(dt)
  if not startupChecked then
    startupChecked = true
    checkFloodActive()
  end

  -- Window Styling: Transparency & Rounded Corners
  ui.pushStyleVar(ui.StyleVar.WindowPadding, vec2(0, 0))
  ui.pushStyleVar(ui.StyleVar.FrameRounding, 6) -- Round all buttons and inputs
  ui.pushStyleVar(ui.StyleVar.ChildRounding, 8) -- Round inner child windows (like the log box)
  ui.pushStyleColor(ui.StyleColor.WindowBg, rgbm(0.08, 0.08, 0.10, 0.75)) -- Clean, transparent glass effect

  -- Constants for Layout
  local sidebarWidth = 180
  local headerHeight = 110

  -- 1. Draw Header / Logo
  ui.setCursor(vec2(15, 15))
  ui.image("guap wet roads logo trans.png", vec2(160, 160))

  -- 2. Draw Sidebar
  local startY = headerHeight + 50
  for i, tab in ipairs(tabs) do
    ui.setCursor(vec2(15, startY + (i - 1) * 45))
    
    if currentTab == i then
      ui.pushStyleColor(ui.StyleColor.Button, accentColor)
      ui.pushStyleColor(ui.StyleColor.ButtonHovered, accentColor)
      ui.pushStyleColor(ui.StyleColor.ButtonActive, accentColor)
      ui.pushStyleColor(ui.StyleColor.Text, rgbm(1, 1, 1, 1))
    else
      -- Transparent resting buttons for the sidebar
      ui.pushStyleColor(ui.StyleColor.Button, rgbm(0.2, 0.2, 0.22, 0.4))
      ui.pushStyleColor(ui.StyleColor.ButtonHovered, rgbm(0.25, 0.25, 0.28, 0.6))
      ui.pushStyleColor(ui.StyleColor.ButtonActive, rgbm(0.15, 0.15, 0.18, 0.7))
      ui.pushStyleColor(ui.StyleColor.Text, rgbm(0.7, 0.7, 0.7, 0.9))
    end

    -- Tab Button (Emojis removed for clean look)
    if ui.button(tab.name, vec2(sidebarWidth - 30, 36)) then
      currentTab = i
    end
    ui.popStyleColor(4)
  end

  -- 3. Draw Content Area
  ui.setCursor(vec2(sidebarWidth, headerHeight - 10))
  ui.beginChild("contentArea", vec2(ui.availableSpaceX() - 15, ui.availableSpaceY() - 15), false)
  ui.pushStyleColor(ui.StyleColor.Text, rgbm(0.9, 0.9, 0.9, 1))

  if currentTab == 1 then
    -- TAB 1: SURFACE WETNESS
    ui.pushFont(ui.Font.Title)
    ui.text("Surface Wetness Engine")
    ui.popFont()
    ui.offsetCursorY(4)
    ui.textColored("Real-time material adjustments for wet roads.", rgbm(0.6, 0.6, 0.6, 1))
    ui.offsetCursorY(20)

    -- Enable / Disable Toggle
    local btnColor = enabled and rgbm(0.85, 0.3, 0.35, 0.8) or accentColor
    local btnText = enabled and "Disable Wet Roads" or "Enable Wet Roads"
    
    ui.pushStyleColor(ui.StyleColor.Button, btnColor)
    if ui.button(btnText, vec2(180, 32)) then
      enabled = not enabled
      if enabled then
        if not roadMeshes then doSearch() end
        applyPreset(wetPreset)
      else
        revertDry()
      end
    end
    ui.popStyleColor()

    if enabled then
      ui.offsetCursorY(25)
      ui.text("Wetness Intensity:")
      ui.offsetCursorY(8)

      for i = 1, 3 do
        if i > 1 then ui.sameLine(0, 10) end
        if wetPreset == i then
          ui.pushStyleColor(ui.StyleColor.Button, accentColor)
          ui.pushStyleColor(ui.StyleColor.Text, rgbm(1, 1, 1, 1))
        else
          -- Transparent unselected state
          ui.pushStyleColor(ui.StyleColor.Button, rgbm(0.25, 0.25, 0.28, 0.4))
          ui.pushStyleColor(ui.StyleColor.Text, rgbm(0.6, 0.6, 0.6, 1))
        end

        if ui.button(labels[i], vec2(100, 30)) then
          wetPreset = i
          applyPreset(i)
        end
        ui.popStyleColor(2)
      end
    end

  elseif currentTab == 2 then
    -- TAB 2: TRACK FLOODING
    ui.pushFont(ui.Font.Title)
    ui.text("Track Flooding")
    ui.popFont()
    ui.offsetCursorY(4)
    ui.textColored("Overrides the track's ext_config.ini to create deep water.", rgbm(0.6, 0.6, 0.6, 1))
    ui.offsetCursorY(20)

    if floodActive then
      ui.textColored("System Status:  ACTIVE", accentColor)
      ui.offsetCursorY(15)
      
      ui.pushStyleColor(ui.StyleColor.Button, rgbm(0.85, 0.3, 0.35, 0.8))
      if ui.button('Disable Flood System', vec2(200, 32)) then
        floodActive = false -- Instant UI update
        floodOn = false
        disableFlood()
      end
      ui.popStyleColor()
      
      ui.offsetCursorY(15)
      ui.textColored("⚠ Restart session required to see dry track.", rgbm(0.9, 0.6, 0.2, 1))
    else
      ui.textColored("System Status:  STANDBY", rgbm(0.5, 0.5, 0.5, 1))
      ui.offsetCursorY(15)
      
      ui.pushStyleColor(ui.StyleColor.Button, accentColor)
      if ui.button('Enable Flood System', vec2(200, 32)) then
        floodActive = true -- Instant UI update
        floodOn = true
        enableFlood()
      end
      ui.popStyleColor()
    end

  elseif currentTab == 3 then
    -- TAB 3: SETTINGS & LOG
    ui.pushFont(ui.Font.Title)
    ui.text("Settings & Diagnostics")
    ui.popFont()
    ui.offsetCursorY(20)

    -- Search filter
    ui.text("Material Filter Input")
    ui.setNextItemWidth(180)
    local newInput = ui.inputText('##matInput', customInput, ui.InputTextFlags.None)
    if newInput then customInput = newInput end
    
    ui.sameLine(0, 10)
    ui.pushStyleColor(ui.StyleColor.Button, rgbm(0.3, 0.3, 0.35, 0.5))
    if ui.button('Force Search', vec2(120, 26)) then
      doSearch()
    end
    ui.popStyleColor()

    ui.offsetCursorY(20)
    ui.text("System Log:")
    ui.offsetCursorY(5)
    
    -- Log box (very transparent, letting the track show through cleanly)
    ui.pushStyleColor(ui.StyleColor.ChildBg, rgbm(0.0, 0.0, 0.0, 0.25))
    ui.beginChild("logBox", vec2(ui.availableSpaceX() - 10, 130), true)
    
    ui.textColored("Status: " .. statusMsg, accentColor)
    ui.offsetCursorY(5)
    
    if #foundNames > 0 then
      ui.textColored('Total meshes found: ' .. (roadMeshes and roadMeshes:size() or 0), rgbm(0.8, 0.8, 0.8, 1))
      for i = 1, math.min(5, #foundNames) do
        ui.textColored('  > ' .. foundNames[i], rgbm(0.6, 0.6, 0.6, 1))
      end
    end
    
    if extConfigPath then
      ui.offsetCursorY(10)
      ui.textColored('Target Config Path:', rgbm(0.5, 0.5, 0.5, 1))
      ui.textWrapped(extConfigPath)
    end
    
    ui.endChild()
    ui.popStyleColor()

  end

  ui.popStyleColor() -- Text color pop
  ui.endChild()

  ui.popStyleColor() -- WindowBg pop
  ui.popStyleVar(3)  -- Pop the 3 StyleVars (WindowPadding, FrameRounding, ChildRounding)
end