--ini
if not MDungeonTeleports then
    MDungeonTeleports = {}
end

if not MDungeonTeleports.Season1Pos then
    MDungeonTeleports.Season1Pos = {x = 620, y = 220}
end

if MDungeonTeleports.showTooltips == nil then
    MDungeonTeleports.showTooltips = false
end

-- Save
local function SaveSeason1Position()
    local DungeonFrame = PVEFrame
    if DungeonFrame then
        local frameScale = Season1:GetScale()
        local parentScale = DungeonFrame:GetScale()

        local season1Right = Season1:GetRight() * frameScale
        local season1Bottom = Season1:GetBottom() * frameScale
        local dungeonRight = DungeonFrame:GetRight() * parentScale
        local dungeonBottom = DungeonFrame:GetBottom() * parentScale

        local offsetX = (season1Right - dungeonRight) / parentScale
        local offsetY = (season1Bottom - dungeonBottom) / parentScale

        MDungeonTeleports.Season1Pos = {x = offsetX, y = offsetY}
    end
end


-- Load
local function LoadSeason1Position()
    local DungeonFrame = PVEFrame
    if DungeonFrame and MDungeonTeleports.Season1Pos then
        local pos = MDungeonTeleports.Season1Pos

        local frameScale = Season1:GetScale()
        local parentScale = DungeonFrame:GetScale()

        local adjustedX = pos.x * parentScale / frameScale
        local adjustedY = pos.y * parentScale / frameScale

        Season1:ClearAllPoints()
        Season1:SetPoint("BOTTOMRIGHT", DungeonFrame, "BOTTOMRIGHT", adjustedX, adjustedY)
    end
end


-- Reattach
local function ReattachSeason1()
    local DungeonFrame = PVEFrame
    if DungeonFrame and MDungeonTeleports.Season1Pos then
        local pos = MDungeonTeleports.Season1Pos

        local frameScale = Season1:GetScale()
        local parentScale = DungeonFrame:GetScale()

        -- Adjust based on saved right-side offset
        local adjustedX = pos.x * parentScale / frameScale
        local adjustedY = pos.y * parentScale / frameScale

        Season1:ClearAllPoints()
        Season1:SetPoint("BOTTOMRIGHT", DungeonFrame, "BOTTOMRIGHT", adjustedX, adjustedY)
    end
end


-- save on close
local function OnPVEFrameClose()
    SaveSeason1Position()
end

-- load on login
local function OnPlayerLogin()
    LoadSeason1Position()
    UpdateSeason1Background()
    UpdateSeason1UI()
    showTooltips = MDungeonTeleports.showTooltips
end

local loginFrame = CreateFrame("Frame")
loginFrame:RegisterEvent("PLAYER_LOGIN")
loginFrame:SetScript(
    "OnEvent",
    function(self, event)
        if event == "PLAYER_LOGIN" then
            OnPlayerLogin()
        end
    end
)

-- tooltip toggle
function ToggleTooltips()
    MDungeonTeleports.showTooltips = not MDungeonTeleports.showTooltips
end

-- visibility
function Season_UpdateVisibility(show)
    local seasonFrame = _G["Season1"]
    if seasonFrame then
        seasonFrame:SetShown(show)
    end
end

local factionGroup = UnitFactionGroup("player")

local siegeID
if factionGroup == "Horde" then
    siegeID = 464256
elseif factionGroup == "Alliance" then
    siegeID = 445418
end

-- season 1 row 1 data
local row1Data = {
    {icon = "Interface\\Icons\\inv_achievement_dungeon_arak-ara", spellID = 445417, name = "ARAK"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_cityofthreads", spellID = 445416, name = "COT"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_dawnbreaker", spellID = 445414, name = "DAWN"},
    {icon = "Interface\\Icons\\inv_achievement_dungeon_stonevault", spellID = 445269, name = "SV"}
}

-- season 1 row 2 data
local row2Data = {
    {icon = "Interface\\Icons\\achievement_dungeon_mistsoftirnascithe", spellID = 354464, name = "MISTS"},
    {icon = "Interface\\Icons\\achievement_dungeon_theneroticwake", spellID = 354462, name = "NW"},
    {icon = "Interface\\Icons\\achievement_dungeon_siegeofboralus", spellID = siegeID, name = "SIEGE"},
    {icon = "Interface\\Icons\\achievement_dungeon_grimbatol", spellID = 445424, name = "GB"}
}

-- frame
local Season1 = CreateFrame("Frame", "Season1", PVEFrame)
Season1:SetSize(164, 130)
Season1:SetMovable(true)
Season1:EnableMouse(true)
Season1:RegisterForDrag("LeftButton")
Season1:SetClampedToScreen(true)

-- track flag
Season1.isBeingDragged = false

-- drag
Season1:SetScript(
    "OnDragStart",
    function(self)
        if IsShiftKeyDown() then
            self.isBeingDragged = true
            self:StartMoving()
        end
    end
)

Season1:SetScript(
    "OnDragStop",
    function(self)
        if self.isBeingDragged then
            self:StopMovingOrSizing()
            SaveSeason1Position()
            self.isBeingDragged = false
            ReattachSeason1()
        end
    end
)

-- backgroundSeason1
local backgroundSeason1 = Season1:CreateTexture(nil, "BACKGROUND")
backgroundSeason1:SetAllPoints(Season1)
backgroundSeason1:SetTexture("Interface/AddOns/MDungeonTeleports/media/frames/default_frames.blp")
backgroundSeason1:SetTexCoord(0, 0.160156, 0, 0.126953)
backgroundSeason1:SetVertexColor(1, 1, 1, 1)

function UpdateSeason1Background()
    local selectedTexture =
        MDungeonTeleports.selectedFramePack or "Interface/Addons/MDungeonTeleports/media/frames/default_frames.blp"
    backgroundSeason1:SetTexture(selectedTexture)
end

-- title
local Season1Title = Season1:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
Season1Title:SetPoint("TOP", Season1, "TOP", 0, -10)
Season1Title:SetFont("Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf", 13, flags)
Season1Title:SetText("The War Within [S1]")

-- button settings
local buttonSize = 32
local buttonSpacing = 5
local rowOffset = -30

-- time formatting
local function FormatCooldownTime(seconds)
    if seconds >= 3600 then
        local hours = math.floor(seconds / 3600)
        return string.format("%dh", hours)
    elseif seconds >= 60 then
        local minutes = math.floor(seconds / 60)
        return string.format("%dm", minutes)
    else
        return string.format("%ds", math.floor(seconds))
    end
end

-- cooldown text
local function UpdateCooldownText(button, spellID)
    local cooldownFrame = button.cooldownText
    local cooldownOverlay = button.cooldownOverlay
    local spellCooldownInfo = C_Spell.GetSpellCooldown(spellID)

    if spellCooldownInfo then
        local startTime = spellCooldownInfo.startTime
        local duration = spellCooldownInfo.duration
        local isEnabled = spellCooldownInfo.isEnabled

        if startTime > 0 and duration > 0 and isEnabled then
            local remaining = max(0, (startTime + duration) - GetTime())

            if remaining > 5 then
                cooldownFrame:SetText(FormatCooldownTime(remaining))
                cooldownOverlay:Show()
            else
                cooldownFrame:SetText("")
                cooldownOverlay:Hide()
            end
        else
            cooldownFrame:SetText("")
            cooldownOverlay:Hide()
        end
    else
        cooldownFrame:SetText("")
        cooldownOverlay:Hide()
    end
end

local spellButtons = {}

-- Create spell buttons
local function CreateSpellButton(parent, data, rowOffset)
    local button = CreateFrame("Button", nil, parent, "SecureActionButtonTemplate")
    button:SetSize(buttonSize, buttonSize)
    button:SetPoint("TOPLEFT", parent, "TOPLEFT", (data.index - 1) * (buttonSize + buttonSpacing) + 10, rowOffset)

    -- Texture for the button
    local buttonTexture = button:CreateTexture(nil, "ARTWORK")
    buttonTexture:SetAllPoints(button)
    buttonTexture:SetTexture(data.icon)

    -- Border texture
    local borderTexture = button:CreateTexture(nil, "OVERLAY")
    borderTexture:SetAllPoints(button)
    borderTexture:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\default_ui\\button_border.blp")
    borderTexture:SetDrawLayer("OVERLAY", 2)
    button.borderTexture = borderTexture

    -- Cooldown texture
    local cooldownOverlay = button:CreateTexture(nil, "OVERLAY")
    cooldownOverlay:SetAllPoints(button)
    cooldownOverlay:SetTexture("Interface\\Tooltips\\UI-Tooltip-Background")
    cooldownOverlay:SetVertexColor(0, 0, 0, 0.6)
    cooldownOverlay:Hide()
    button.cooldownOverlay = cooldownOverlay

    -- Button text
    local buttonText = button:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    buttonText:SetPoint("TOP", button, "BOTTOM", 1, -2)
    local font, _, flags = buttonText:GetFont()
    buttonText:SetFont("Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf", 11, flags)
    buttonText:SetTextColor(1, 1, 1)
    buttonText:SetText(data.name)

    -- Cooldown text
    local cooldownText = button:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    cooldownText:SetPoint("CENTER", button, "CENTER", -1, -1)
    cooldownText:SetTextColor(1, 1, 1)
    cooldownText:SetFont("Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf", 14, flags)
    button.cooldownText = cooldownText

    -- Spell ID
    button:SetAttribute("type", "spell")
    button:SetAttribute("spell", data.spellID)

   -- Hover overlay
   local hoverOverlay = button:CreateTexture(nil, "HIGHLIGHT")
   hoverOverlay:SetAllPoints(button)
   hoverOverlay:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\default_ui\\button_highlight.blp")
   hoverOverlay:Hide()
   button.hoverOverlay = hoverOverlay

   table.insert(spellButtons, button)

   -- Button texture update function
   local function UpdateButtonTexture()
       local UIPack = MDungeonTeleports.selectedUIPack or "Interface/Addons/MDungeonTeleports/media/ui/default_ui/"

       if IsSpellKnown(data.spellID) then
           buttonTexture:SetTexture(data.icon)
       else
           buttonTexture:SetTexture(UIPack .. "lock.blp")
       end
   end

   button.UpdateButtonTexture = UpdateButtonTexture

   UpdateButtonTexture()

   -- Event handler
   local function OnEvent(self, event)
       if event == "SPELL_UPDATE_COOLDOWN" or event == "SPELLS_CHANGED" then
           UpdateButtonTexture()
           UpdateCooldownText(self, data.spellID)
       end
   end

   -- Tooltips and hover
   button:SetScript(
       "OnEnter",
       function(self)
           if MDungeonTeleports.showTooltips then
               GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
               GameTooltip:SetSpellByID(data.spellID)
               GameTooltip:Show()
           end
           hoverOverlay:Show()
       end
   )

   button:SetScript(
       "OnLeave",
       function(self)
           GameTooltip:Hide()
           hoverOverlay:Hide()
       end
   )

   -- Register events
   button:RegisterEvent("SPELL_UPDATE_COOLDOWN")
   button:RegisterEvent("SPELLS_CHANGED")
   button:RegisterForClicks("AnyUp", "AnyDown")
   button:SetScript("OnEvent", OnEvent)

   return button
end

function UpdateSeason1UI()
    local UIPack = MDungeonTeleports.selectedUIPack or "Interface/Addons/MDungeonTeleports/media/ui/default_ui/"

    for _, btn in ipairs(spellButtons) do
        if btn.borderTexture then
            btn.borderTexture:SetTexture(UIPack .. "button_border.blp")
        end
        if btn.hoverOverlay then
            btn.hoverOverlay:SetTexture(UIPack .. "button_highlight.blp")
        end
        if btn.UpdateButtonTexture then
            btn.UpdateButtonTexture()
        end
    end
end

-- Button layout for first row
for i, data in ipairs(row1Data) do
    data.index = i
    CreateSpellButton(Season1, data, rowOffset)
end

-- Button layout for second row
local row2Offset = -79
for i, data in ipairs(row2Data) do
    data.index = i
    CreateSpellButton(Season1, data, row2Offset)
end

UpdateSeason1UI()
