-- ============================================================================
-- File: ArenaCore/Core/Pages/MoreGoodies.lua (v1.0)
-- Purpose: Settings page for More Goodies features including Absorbs.
-- ============================================================================

local AC = _G.ArenaCore
if not AC then return end

local V = AC.Vanity

local PERF_DB_PATH = "performance"

local PVP_FPS_CVARS = {
  vsync = "0",
  LowLatencyMode = "2",
  MSAAQuality = "0",
  ffxAntiAliasingMode = "4",
  graphicsQuality = "0",
  graphicsShadowQuality = "0",
  graphicsLiquidDetail = "0",
  graphicsSSAO = "0",
  graphicsDepthEffects = "3",
  graphicsComputeEffects = "0",
  graphicsOutlineMode = "1",
  graphicsTextureResolution = "2",
  graphicsSpellDensity = "2",
  graphicsProjectedTextures = "1",
  graphicsViewDistance = "1",
  graphicsEnvironmentDetail = "0",
  graphicsGroundClutter = "0",
  gxMaxFrameLatency = "3",
  textureFilteringMode = "5",
  shadowrt = "0",
  ResampleQuality = "3",
  vrsValar = "0",
  gxapi = "d3d12",
  physicsLevel = "1",
  useMaxFPSBk = "1",
  maxFPSBk = "40",
  ResampleSharpness = "0.2",
}

local function EnsurePerfDB()
  if not AC.DB then AC.DB = {} end
  if not AC.DB.profile then AC.DB.profile = {} end
  AC.DB.profile[PERF_DB_PATH] = AC.DB.profile[PERF_DB_PATH] or {}
  AC.DB.profile[PERF_DB_PATH].fpsPreset = AC.DB.profile[PERF_DB_PATH].fpsPreset or {}
  return AC.DB.profile[PERF_DB_PATH].fpsPreset
end

local function CreateModalBase(frameName, width, height)
  local f = CreateFrame("Frame", frameName, UIParent, "BackdropTemplate")
  f:SetSize(width, height)
  f:SetPoint("CENTER")
  f:SetFrameStrata("FULLSCREEN_DIALOG")
  f:SetFrameLevel(9999)

  f:SetBackdrop({
    bgFile = "Interface/Tooltips/UI-Tooltip-Background",
    edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
    edgeSize = 14,
    insets = { left = 3, right = 3, top = 3, bottom = 3 }
  })
  f:SetBackdropColor(0, 0, 0, 0.9)

  local overlay = f:CreateTexture(nil, "BORDER")
  overlay:SetAllPoints()
  overlay:SetColorTexture(0, 0, 0, 0.35)

  return f
end

local function ShowPerformanceReloadConfirmation()
  local popup = CreateModalBase("ArenaCorePerformanceReloadPopup", 420, 160)

  local title = popup:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
  title:SetPoint("TOP", 0, -16)
  title:SetText("Reload Required")
  title:SetTextColor(1, 1, 1, 1)

  local msg = popup:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  msg:SetPoint("TOP", title, "BOTTOM", 0, -12)
  msg:SetWidth(380)
  msg:SetJustifyH("CENTER")
  msg:SetText("Performance preset applied.\nReload your UI to fully apply it.")
  msg:SetTextColor(1, 1, 1, 1)

  local reloadBtn
  local laterBtn
  if AC and AC.CreateTexturedButton then
    reloadBtn = AC:CreateTexturedButton(popup, 140, 26, "Reload", "button-hide")
    reloadBtn:SetPoint("BOTTOM", -75, 14)
    reloadBtn:SetScript("OnClick", function()
      popup:Hide()
      ReloadUI()
    end)

    laterBtn = AC:CreateTexturedButton(popup, 140, 26, "Later", "button-hide")
    laterBtn:SetPoint("BOTTOM", 75, 14)
    laterBtn:SetScript("OnClick", function() popup:Hide() end)
  else
    reloadBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    reloadBtn:SetSize(140, 26)
    reloadBtn:SetPoint("BOTTOM", -75, 14)
    reloadBtn:SetText("Reload")
    reloadBtn:SetScript("OnClick", function()
      popup:Hide()
      ReloadUI()
    end)

    laterBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    laterBtn:SetSize(140, 26)
    laterBtn:SetPoint("BOTTOM", 75, 14)
    laterBtn:SetText("Later")
    laterBtn:SetScript("OnClick", function() popup:Hide() end)
  end

  popup:Show()
end

local function GetCVarSafe(cvar)
  local ok, val = pcall(function()
    return C_CVar.GetCVar(cvar)
  end)
  if ok then
    return val
  end
  return nil
end

local function SetCVarSafe(cvar, value)
  local ok = pcall(function()
    C_CVar.SetCVar(cvar, value)
  end)
  return ok
end

local function BackupCurrentPerfCVars(db)
  if db.backup then
    return false
  end

  local backup = {}
  for cvar in pairs(PVP_FPS_CVARS) do
    backup[cvar] = GetCVarSafe(cvar)
  end
  db.backup = backup
  return true
end

local function ApplyPvpFpsPreset(db)
  if InCombatLockdown() then
    return false, "Blocked in combat."
  end

  BackupCurrentPerfCVars(db)

  local okCount, failCount = 0, 0
  for cvar, value in pairs(PVP_FPS_CVARS) do
    if SetCVarSafe(cvar, value) then
      okCount = okCount + 1
    else
      failCount = failCount + 1
    end
  end

  db.applied = true
  ShowPerformanceReloadConfirmation()
  return true, string.format("Applied %d settings (%d failed).", okCount, failCount)
end

local function RestorePvpFpsBackup(db)
  if InCombatLockdown() then
    return false, "Blocked in combat."
  end

  if not db.backup then
    return false, "No backup found."
  end

  local okCount, failCount = 0, 0
  for cvar, value in pairs(db.backup) do
    if value ~= nil then
      if SetCVarSafe(cvar, value) then
        okCount = okCount + 1
      else
        failCount = failCount + 1
      end
    end
  end

  db.backup = nil
  db.applied = false
  ShowPerformanceReloadConfirmation()
  return true, string.format("Restored %d settings (%d failed).", okCount, failCount)
end

-- Main page builder function
local function CreatePerformancePage(parent)
  if V and V.EnsureMottoStrip then V:EnsureMottoStrip(parent) end

  local movedFrame = CreateFrame("Frame", nil, parent, "BackdropTemplate")
  movedFrame:SetHeight(295)
  if parent._mottoStrip then
    movedFrame:SetPoint("TOPLEFT", parent._mottoStrip, "BOTTOMLEFT", 10, -10)
    movedFrame:SetPoint("TOPRIGHT", parent._mottoStrip, "BOTTOMRIGHT", -10, -10)
  else
    movedFrame:SetPoint("TOPLEFT", 10, -10)
    movedFrame:SetPoint("TOPRIGHT", -10, -10)
  end
  movedFrame:SetBackdrop({
    bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
    edgeFile = "Interface\\ChatFrame\\ChatFrameBackground",
    tile = true, tileSize = 16, edgeSize = 1,
  })
  movedFrame:SetBackdropColor(0.1, 0.1, 0.1, 0.8)
  movedFrame:SetBackdropBorderColor(0.4, 0.4, 0.4, 1)

  local movedText = movedFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  movedText:SetPoint("TOPLEFT", 15, -14)
  movedText:SetPoint("BOTTOMRIGHT", -15, 14)
  movedText:SetJustifyH("LEFT")
  movedText:SetJustifyV("TOP")
  movedText:SetWordWrap(true)
  movedText:SetText(
    "|cff00BFFFBelow is a performance mod for increased FPS and stability while playing PvP such as |cff00FFFFArenas|r, |cff00FFFFBattlegrounds|r and even |cff00FFFFWorld PvP|r.\n\n\n" ..
    "|cffFF6347These settings were fully created with the sole idea of competitive gameplay at the highest level|r, please keep that in mind. |cffDC143CThis is NOT a setting for people who love the graphics of the game or want things to look pretty|r. |cff32CD32This is for players at their peak of competitive gameplay|r or those looking to take their PvP to the next level.\n\n\n" ..
    "|cff9370DBNote that these settings were explicitly crafted by one of the highest rated players on the planet|r, specifically designed to give players the edge they may be missing when it comes to game performance and |cffFF8C00optimization|r. They are also held in high regard within the community. |cff00BFFFEnjoy their knowledge into crafting the best outcome for pvp gameplay|r."
  )
  movedText:SetTextColor(1, 1, 1, 1)
  movedText:SetFont(movedText:GetFont(), 13, "OUTLINE")

  local enableBtn = CreateFrame("Button", nil, parent)
  enableBtn:SetSize(200, 40)
  enableBtn:SetPoint("TOP", movedFrame, "BOTTOM", 0, -18)
  
  -- Normal state texture
  local normalTex = enableBtn:CreateTexture(nil, "BACKGROUND")
  normalTex:SetAtlas("common-button-tertiary-normal-small")
  normalTex:SetAllPoints()
  enableBtn:SetNormalTexture(normalTex)
  
  -- Pressed state texture
  local pressedTex = enableBtn:CreateTexture(nil, "BACKGROUND")
  pressedTex:SetAtlas("common-button-tertiary-pressed-small")
  pressedTex:SetAllPoints()
  enableBtn:SetPushedTexture(pressedTex)
  
  -- Hover effect
  local hoverTex = enableBtn:CreateTexture(nil, "HIGHLIGHT")
  hoverTex:SetAtlas("common-button-tertiary-normal-small")
  hoverTex:SetAllPoints()
  hoverTex:SetVertexColor(1, 1, 1, 0.3)
  enableBtn:SetHighlightTexture(hoverTex)

  local enableText = enableBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  enableText:SetPoint("CENTER")
  enableText:SetText("Apply PvP FPS Preset")
  enableText:SetTextColor(1, 1, 1, 1)
  enableText:SetFont(enableText:GetFont(), 14, "")

  local enableNote = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  enableNote:SetPoint("TOP", enableBtn, "BOTTOM", 0, -10)
  enableNote:SetText("This will change and adjust your in game graphics settings")
  enableNote:SetTextColor(0.85, 0.85, 0.85, 1)
  enableNote:SetFont(enableNote:GetFont(), 12, "OUTLINE")

  local restoreBtn = CreateFrame("Button", nil, parent)
  restoreBtn:SetSize(200, 40)
  restoreBtn:SetPoint("TOP", enableNote, "BOTTOM", 0, -8)

  local rNormalTex = restoreBtn:CreateTexture(nil, "BACKGROUND")
  rNormalTex:SetAtlas("common-button-tertiary-normal-small")
  rNormalTex:SetAllPoints()
  restoreBtn:SetNormalTexture(rNormalTex)

  local rPressedTex = restoreBtn:CreateTexture(nil, "BACKGROUND")
  rPressedTex:SetAtlas("common-button-tertiary-pressed-small")
  rPressedTex:SetAllPoints()
  restoreBtn:SetPushedTexture(rPressedTex)

  local rHoverTex = restoreBtn:CreateTexture(nil, "HIGHLIGHT")
  rHoverTex:SetAtlas("common-button-tertiary-normal-small")
  rHoverTex:SetAllPoints()
  rHoverTex:SetVertexColor(1, 1, 1, 0.3)
  restoreBtn:SetHighlightTexture(rHoverTex)

  local restoreText = restoreBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  restoreText:SetPoint("CENTER")
  restoreText:SetText("Restore Previous Settings")
  restoreText:SetTextColor(1, 1, 1, 1)
  restoreText:SetFont(restoreText:GetFont(), 13, "")

  local statusText = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  statusText:SetPoint("TOP", restoreBtn, "BOTTOM", 0, -10)
  statusText:SetText(" ")
  statusText:SetTextColor(0.85, 0.85, 0.85, 1)
  statusText:SetFont(statusText:GetFont(), 12, "OUTLINE")

  local perfDb = EnsurePerfDB()

  local function UpdateButtons()
    local hasBackup = perfDb and perfDb.backup ~= nil
    if hasBackup then
      restoreBtn:Enable()
      restoreBtn:SetAlpha(1)
    else
      restoreBtn:Disable()
      restoreBtn:SetAlpha(0.4)
    end
  end

  enableBtn:SetScript("OnClick", function()
    local ok, msg = ApplyPvpFpsPreset(perfDb)
    statusText:SetText(msg or (ok and "Done." or "Failed."))
    UpdateButtons()
  end)

  restoreBtn:SetScript("OnClick", function()
    local ok, msg = RestorePvpFpsBackup(perfDb)
    statusText:SetText(msg or (ok and "Done." or "Failed."))
    UpdateButtons()
  end)

  UpdateButtons()

  return parent
  
end

AC:RegisterPage("Performance", CreatePerformancePage)
