local HORDE_ICON_TEXTURE = "Interface\\AddOns\\HomeBound\\Assets\\horde"
local ALLIANCE_ICON_TEXTURE = "Interface\\AddOns\\HomeBound\\Assets\\alliance"

local collections = {
  {
    name = "Eastern Kingdoms",
    achievements = {
      { id = 940, texture = "7423955" },
      { id = 5442, texture = "7423907" },
    }
  },
  {
    name = "Wrath of the Lich King",
    achievements = {
      { id = 4405, texture = "7421869" },
      { id = 938, texture = "7423951" },
    }
  },
  {
    name = "Mists of Pandaria",
    achievements = {
      { id = 7322, texture = "7423251" },
      { id = 8316, texture = "3879" },
    }
  },
  {
    name = "Legion",
    achievements = {
      { id = 10698, texture = "7422137" },
      { id = 11124, texture = "7416149" },
      { id = 11257, texture = "7417009" },
      { id = 11258, texture = "7422161" },
    }
  },
  {
    name = "Battle for Azeroth",
    achievements = {
      { id = 10996, texture = "7425959" },
      { id = 13723, texture = "7422601" },
      { id = 13018, texture = "7417181" },
      { id = 13473, texture = "7422617" },
      { id = 13475, texture = "7422717" },
      { id = 13477, texture = "7422697" },
      { id = 12582, texture = "7421917", icon = ALLIANCE_ICON_TEXTURE },
      { id = 12997, texture = "7424987", icon = ALLIANCE_ICON_TEXTURE },
      { id = 13049, texture = "7424983", icon = ALLIANCE_ICON_TEXTURE },
      { id = 12479, texture = "7416677", icon = HORDE_ICON_TEXTURE },
      { id = 12509, texture = "7416415", icon = HORDE_ICON_TEXTURE },
      { id = 12614, texture = "7416697", icon = HORDE_ICON_TEXTURE },
      { id = 13038, texture = "7416653", icon = HORDE_ICON_TEXTURE },
      { id = 13039, texture = "7416679", icon = HORDE_ICON_TEXTURE },
      { id = 13284, texture = "7416385", icon = HORDE_ICON_TEXTURE },
      { id = 12867, texture = "7416261", icon = HORDE_ICON_TEXTURE },
      { id = 12869, texture = "7416257", icon = HORDE_ICON_TEXTURE },
      { id = 12870, texture = "7416369", icon = HORDE_ICON_TEXTURE },
    }
  },
  {
    name = "Dragonflight",
    achievements = {
      { id = 17529, texture = "7423851" },
      { id = 17773, texture = "7423543" },
      { id = 19507, texture = "7423547" },
      { id = 19719, texture = "7416285" },
    }
  },
  {
    name = "The War Within",
    achievements = {
      { id = 20595, texture = "7425035" },
      { id = 40504, texture = "7425063" },
      { id = 40859, texture = "7425079" },
      { id = 40894, texture = "7416925" },
      { id = 41186, texture = "7422986" },
      { id = 40542, texture = "7422981" },
      { id = 41119, texture = "7416497" },
    }
  },
  {
    name = "PvP",
    achievements = {
      { id = 221, texture = "7423315" },
      { id = 222, texture = "7423323" },
      { id = 158, texture = "7423311" },
      { id = 1153, texture = "7423319" },
      { id = 5245, texture = "7425943" },
      { id = 40210, texture = "7425127" },
      { id = 40612, texture = "7423295" },
      { id = 212, texture = "7423327" },
      { id = 213, texture = "7423331" },
      { id = 229, texture = "7423275" },
      { id = 231, texture = "7423271" },
      { id = 1157, texture = "7423307" },
      { id = 6981, texture = "7423255" },
      { id = 5223, texture = "7423202" },
      { id = 167, texture = "7423283" },
      { id = 200, texture = "7423279" },
    }
  },
  {
    name = "Meta Achievements",
    achievements = {
      { id = 40953, texture = "7423186" },
      { id = 20501, texture = "7423627" },
      { id = 19458, texture = "7423623" },
    }
  },
  {
    name = "Lorewalking",
    achievements = {
      { id = 42187, texture = "7426150" },
      { id = 42188, texture = "7426154" },
      { id = 42189, texture = "7426140" },
    }
  },
  {
    name = "Professions",
    achievements = {
      { id = 4859, texture = "7416771" },
      { id = 19408, texture = "7425099" },
      { id = 12746, texture = "7417177", icon = HORDE_ICON_TEXTURE },
      { id = 12733, texture = "7416699", icon = HORDE_ICON_TEXTURE },
    }
  },
}

hb_settings = hb_settings or { scale = 1.0, hideCompleted = false }
local activeWidgets = {}
local collapsedHeaders = {}

-- Check if achievement is complete
local function IsAchievementComplete(achievementID)
  if not achievementID then return false end

  if type(achievementID) == "table" then
    for _, id in ipairs(achievementID) do
      if IsAchievementComplete(id) then return true end
    end
    return false
  end

  local _, _, _, completed = GetAchievementInfo(achievementID)
  return completed or false
end

local function GetFullTexturePath(texturePath)
  if texturePath and not string.match(texturePath, "[\\/]") then
    return "Interface\\AddOns\\HomeBound\\Assets\\" .. texturePath
  end
  return texturePath
end

local frame = CreateFrame("Frame", "HB_MainFrame", UIParent, "BackdropTemplate")
frame:SetSize(650, 500)
frame:SetPoint("CENTER")
frame:SetBackdrop({
  bgFile = "Interface\\Buttons\\WHITE8x8",
  edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
  tile = false,
  edgeSize = 16,
  insets = { left = 4, right = 4, top = 4, bottom = 4 }
})
frame:SetBackdropColor(0.02, 0.02, 0.02, 0.95)
frame:SetBackdropBorderColor(0.3, 0.3, 0.3, 1)
frame:SetMovable(true)
frame:EnableMouse(true)
frame:Hide()

frame:SetScript("OnMouseDown", function(self, button)
  if button == "LeftButton" then
    self:StartMoving()
  end
end)
frame:SetScript("OnMouseUp", function(self, button)
  if button == "LeftButton" then
    self:StopMovingOrSizing()
  end
end)

-- Create reusable frame for the texture
local previewFrame = CreateFrame("Frame", "HB_RewardFrame", UIParent, "BackdropTemplate")
previewFrame:SetSize(300, 330)
previewFrame:SetFrameStrata("TOOLTIP")
previewFrame:SetBackdrop({
  bgFile = "Interface\\Buttons\\WHITE8x8",
  edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
  tile = false, edgeSize = 16,
  insets = { left = 4, right = 4, top = 4, bottom = 4 }
})
previewFrame:SetBackdropColor(0.05, 0.05, 0.05, 0.98)
previewFrame:SetBackdropBorderColor(0.5, 0.5, 0.5, 1)
previewFrame:Hide()

local previewTitle = previewFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
previewTitle:SetPoint("TOP", 0, -12)
previewTitle:SetText("Decor Reward")
previewTitle:SetTextColor(1, 0.82, 0)

local previewTexture = previewFrame:CreateTexture(nil, "ARTWORK")
previewTexture:SetSize(288, 288)
previewTexture:SetPoint("TOP", previewTitle, "BOTTOM", 0, -8)
previewTexture:SetTexCoord(0.08, 0.92, 0.08, 0.92)
previewFrame.texture = previewTexture

local titleBg = frame:CreateTexture(nil, "BACKGROUND")
titleBg:SetTexture("Interface\\Buttons\\WHITE8x8")
titleBg:SetPoint("TOPLEFT", 4, -4)
titleBg:SetPoint("TOPRIGHT", -4, -4)
titleBg:SetHeight(50)
titleBg:SetGradient("VERTICAL", CreateColor(0.15, 0.15, 0.15, 1), CreateColor(0.08, 0.08, 0.08, 1))

local title = frame:CreateFontString(nil, "OVERLAY")
title:SetFont("Fonts\\FRIZQT__.TTF", 16, "OUTLINE")
title:SetPoint("TOP", 0, -14)
title:SetText("Home Bound")
title:SetTextColor(1, 0.85, 0, 1)

local subtitle = frame:CreateFontString(nil, "OVERLAY")
subtitle:SetFont("Fonts\\FRIZQT__.TTF", 11)
subtitle:SetPoint("TOP", title, "BOTTOM", 0, -2)
subtitle:SetText("Track your Player Housing rewards")
subtitle:SetTextColor(0.7, 0.7, 0.7, 1)

local closeBtn = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
closeBtn:SetPoint("TOPRIGHT", -2, -2)
closeBtn:SetSize(28, 28)

local toggleBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
toggleBtn:SetSize(140, 24)
toggleBtn:SetPoint("TOPLEFT", 10, -60)
toggleBtn:SetText("Hide Completed")

toggleBtn:SetScript("OnClick", function(self)
  hb_settings.hideCompleted = not hb_settings.hideCompleted
  if hb_settings.hideCompleted then
    self:SetText("Show Completed")
  else
    self:SetText("Hide Completed")
  end
  BuildUI()
end)

local scaleSlider = CreateFrame("Slider", "HB_ScaleSlider", frame, "UISliderTemplate")
scaleSlider:SetPropagateMouseMotion(true)
scaleSlider:SetWidth(150)
scaleSlider:SetHeight(22)
scaleSlider:SetMinMaxValues(0.5, 1.5)
scaleSlider:SetValueStep(0.05)
scaleSlider:SetPoint("TOPRIGHT", -120, -60)
scaleSlider:SetValue(hb_settings.scale or 1.0)

local scaleValueText = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
scaleValueText:SetFont(STANDARD_TEXT_FONT, 14)
scaleValueText:SetPoint("TOPLEFT", scaleSlider, "TOPRIGHT", 8, -3)

scaleSlider:SetScript("OnValueChanged", function(_, value)
  local roundedValue = tonumber(string.format("%.2f", value))
  scaleValueText:SetText(string.format("UI Scale: %.2f", roundedValue))
end)

scaleSlider:SetScript("OnMouseUp", function(self)
  local value = self:GetValue()
  local roundedValue = tonumber(string.format("%.2f", value))
  hb_settings.scale = roundedValue
  frame:SetScale(roundedValue)
end)

scaleValueText:SetText(string.format("UI Scale: %.2f", hb_settings.scale or 1.0))
local scrollFrame = CreateFrame("ScrollFrame", nil, frame, "ScrollFrameTemplate")
scrollFrame:SetPoint("TOPLEFT", 12, -90)
scrollFrame:SetPoint("BOTTOMRIGHT", -32, 12)

local scrollChild = CreateFrame("Frame", nil, scrollFrame)
scrollChild:SetSize(620, 1)
scrollFrame:SetScrollChild(scrollChild)
scrollFrame.ScrollBar:ClearAllPoints()
scrollFrame.ScrollBar:SetPoint("TOPRIGHT", scrollFrame, "TOPRIGHT", 15, -8)
scrollFrame.ScrollBar:SetHeight(385)

local function ClearWidgets()
  for _, widget in ipairs(activeWidgets) do
    widget:Hide()
  end
  wipe(activeWidgets)
end

local function CreateHeader(parent, group, y)
  local total, completed = 0, 0
  for _, ach in ipairs(group.achievements) do
    total = total + 1
    if IsAchievementComplete(ach.id) then
      completed = completed + 1
    end
  end

  if collapsedHeaders[group.name] == nil then
    collapsedHeaders[group.name] = true
  end

  local collapsed = collapsedHeaders[group.name]
  local percent = total > 0 and math.floor((completed / total) * 100) or 0

  local header = CreateFrame("Button", nil, parent)
  header:SetPoint("TOPLEFT", 0, y)
  header:SetSize(600, 32)

  local bg = header:CreateTexture(nil, "BACKGROUND")
  bg:SetAllPoints()
  bg:SetTexture("Interface\\Buttons\\WHITE8x8")
  bg:SetGradient("HORIZONTAL", CreateColor(0.12, 0.12, 0.12, 0.8), CreateColor(0.08, 0.08, 0.08, 0.8))

  local icon = header:CreateFontString(nil, "OVERLAY")
  icon:SetFont("Fonts\\FRIZQT__.TTF", 14, "OUTLINE")
  icon:SetPoint("LEFT", 8, 0)
  icon:SetText(collapsed and "+" or "−")
  icon:SetTextColor(0.8, 0.8, 0.8, 1)

  local text = header:CreateFontString(nil, "OVERLAY")
  text:SetFont("Fonts\\FRIZQT__.TTF", 13, "OUTLINE")
  text:SetPoint("LEFT", 28, 0)
  text:SetText(group.name)
  text:SetTextColor(1, 1, 1, 1)

  local progress = header:CreateFontString(nil, "OVERLAY")
  progress:SetFont("Fonts\\FRIZQT__.TTF", 11)
  progress:SetPoint("RIGHT", -8, 0)

  local color
  if percent == 100 then
    color = CreateColor(0.2, 1, 0.2, 1)
  elseif percent >= 50 then
    color = CreateColor(1, 0.82, 0, 1)
  else
    color = CreateColor(0.9, 0.9, 0.9, 1)
  end

  progress:SetText(string.format("%d/%d (%d%%)", completed, total, percent))
  progress:SetTextColor(color:GetRGBA())

  header:SetScript("OnClick", function()
    collapsedHeaders[group.name] = not collapsed
    BuildUI()
  end)

  header:SetScript("OnEnter", function(self)
    bg:SetGradient("HORIZONTAL", CreateColor(0.18, 0.18, 0.18, 1), CreateColor(0.12, 0.12, 0.12, 1))
  end)

  header:SetScript("OnLeave", function(self)
    bg:SetGradient("HORIZONTAL", CreateColor(0.12, 0.12, 0.12, 0.8), CreateColor(0.08, 0.08, 0.08, 0.8))
  end)

  table.insert(activeWidgets, header)

  return header, collapsed, y - 36, (completed == total)
end

-- Create achievement line
local function CreateAchievementLine(parent, ach, y)
  local primaryID = type(ach.id) == "table" and ach.id[1] or ach.id
  local _, name = GetAchievementInfo(primaryID)
  local displayName = name or "Unknown Achievement"
  local isComplete = IsAchievementComplete(ach.id)

  if hb_settings.hideCompleted and isComplete then return y end

  local line = CreateFrame("Button", nil, parent)
  line:SetPoint("TOPLEFT", 10, y)
  line:SetSize(590, 22)

  local bullet = line:CreateFontString(nil, "OVERLAY")
  bullet:SetFont("Fonts\\FRIZQT__.TTF", 14)
  bullet:SetPoint("LEFT", 0, 0)

  if isComplete then
    bullet:SetText("•")
    bullet:SetTextColor(0.2, 1, 0.2, 1)
  else
    bullet:SetText("•")
    bullet:SetTextColor(1, 0.6, 0.2, 1)
  end

  local text = line:CreateFontString(nil, "OVERLAY")
  text:SetFont("Fonts\\FRIZQT__.TTF", 12)
  text:SetPoint("LEFT", 20, 0)
  --text:SetPoint("RIGHT", -5, 0)
  text:SetJustifyH("LEFT")
  text:SetText(displayName)

  if isComplete then
    text:SetTextColor(0.5, 0.5, 0.5, 1)
  else
    text:SetTextColor(0.9, 0.9, 0.9, 1)
  end

  --Create icon if needed
  if ach.icon then
    local specialIcon = line:CreateTexture(nil, "OVERLAY")
    specialIcon:SetSize(22, 22)
    specialIcon:SetPoint("LEFT", text, "RIGHT", 16, 0)
    specialIcon:SetTexture(ach.icon)
  end

  line:SetHighlightTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")

  line:SetScript("OnClick", function()
    if not AchievementFrame then AchievementFrame_LoadUI() end
    if not AchievementFrame:IsShown() then AchievementFrame_ToggleAchievementFrame() end
    AchievementFrame_SelectAchievement(primaryID)
  end)

  line:SetScript("OnEnter", function(self)
    if not isComplete then
      text:SetTextColor(1, 0.82, 0, 1)
    end
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    local achievementLink = GetAchievementLink(primaryID)
    GameTooltip:SetHyperlink(achievementLink)
    GameTooltip:Show()

    if ach.texture and ach.texture ~= "" then
      local fullTexturePath = GetFullTexturePath(ach.texture)
      if fullTexturePath then
        previewFrame.texture:SetTexture(fullTexturePath)
        previewFrame:ClearAllPoints()
        
        local tooltipBottomY = GameTooltip:GetBottom()
        local previewScaledHeight = previewFrame:GetHeight() * previewFrame:GetEffectiveScale()
        
        if tooltipBottomY and (tooltipBottomY - previewScaledHeight - 30 < 0) then
          previewFrame:SetPoint("BOTTOMLEFT", GameTooltip, "TOPLEFT", 0, 5)
        else
          previewFrame:SetPoint("TOPLEFT", GameTooltip, "BOTTOMLEFT", 0, -5)
        end
        
        previewFrame:Show()
      end
    end
  end)

  line:SetScript("OnLeave", function(self)
    if isComplete then
      text:SetTextColor(0.5, 0.5, 0.5, 1)
    else
      text:SetTextColor(0.9, 0.9, 0.9, 1)
    end
    GameTooltip:Hide()
    previewFrame:Hide()
  end)

  table.insert(activeWidgets, line)

  return y - 24
end

--Create UI
function BuildUI()
  ClearWidgets()

  local y = 0
  local hasContent = false

  for _, group in ipairs(collections) do
    local total, completed = 0, 0
    for _, ach in ipairs(group.achievements) do
      total = total + 1
      if IsAchievementComplete(ach.id) then
        completed = completed + 1
      end
    end

    local isFullyComplete = (completed == total)

    if not (hb_settings.hideCompleted and isFullyComplete) then
      hasContent = true
      local header, collapsed, newY, fullComplete = CreateHeader(scrollChild, group, y)
      y = newY

      if not collapsed then
        local original_y = y
        for _, ach in ipairs(group.achievements) do
          y = CreateAchievementLine(scrollChild, ach, y)
        end
        if y < original_y then
            y = y - 10
        end
      end
    end
  end

  if not hasContent then
    local msg = scrollChild:CreateFontString(nil, "OVERLAY")
    msg:SetFont("Fonts\\FRIZQT__.TTF", 14)
    msg:SetPoint("TOP", 0, -50)
    msg:SetText("All decor achievements completed!\nCongratulations!")
    msg:SetTextColor(0.2, 1, 0.2, 1)
    table.insert(activeWidgets, msg)
  end

  scrollChild:SetHeight(math.abs(y) + 20)
end

-- Initialize
local init = CreateFrame("Frame")
init:RegisterEvent("ADDON_LOADED")
init:RegisterEvent("PLAYER_ENTERING_WORLD")
init:RegisterEvent("ACHIEVEMENT_EARNED")

init:SetScript("OnEvent", function(self, event, addon)
  if event == "ADDON_LOADED" and addon == "HomeBound" then
    hb_settings = hb_settings or { scale = 1.0, hideCompleted = false }
    if not AchievementFrame then
      AchievementFrame_LoadUI()
    end
  elseif event == "PLAYER_ENTERING_WORLD" then
    local scale = hb_settings.scale or 1.0
    frame:SetScale(scale)
    scaleSlider:SetValue(scale)
    scaleValueText:SetText(string.format("UI Scale: %.2f", scale))

    if hb_settings.hideCompleted then
      toggleBtn:SetText("Show Completed")
    else
      toggleBtn:SetText("Hide Completed")
    end
    BuildUI()
    self:UnregisterEvent("PLAYER_ENTERING_WORLD")
  elseif event == "ACHIEVEMENT_EARNED" then
    C_Timer.After(0.5, BuildUI)
  end
end)

-- Slash command
SLASH_HB1 = "/hb"
SLASH_HB2 = "/homebound"
SlashCmdList["HB"] = function()
  if not frame:IsShown() then
    BuildUI()
  end
  frame:SetShown(not frame:IsShown())
end