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

if not MDungeonTeleports.PortalLibraryRaidPos then
    MDungeonTeleports.PortalLibraryRaidPos = {x = 970, y = -195}
end

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

-- Save
local function SavePortalLibraryRaidPosition()
    local DungeonFrame = PVEFrame
    if DungeonFrame then
        local frameScale = PortalLibraryRaid:GetScale()
        local parentScale = DungeonFrame:GetScale()

        local PortalLibraryRaidRight = PortalLibraryRaid:GetRight() * frameScale
        local PortalLibraryRaidBottom = PortalLibraryRaid:GetBottom() * frameScale
        local dungeonRight = DungeonFrame:GetRight() * parentScale
        local dungeonBottom = DungeonFrame:GetBottom() * parentScale

        local offsetX = (PortalLibraryRaidRight - dungeonRight) / parentScale
        local offsetY = (PortalLibraryRaidBottom - dungeonBottom) / parentScale

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


-- Load
local function LoadPortalLibraryRaidPosition()
    local DungeonFrame = PVEFrame
    if DungeonFrame and MDungeonTeleports.PortalLibraryRaidPos then
        local pos = MDungeonTeleports.PortalLibraryRaidPos

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

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

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


local function ReattachPortalLibraryRaid()
    local DungeonFrame = PVEFrame
    if DungeonFrame and MDungeonTeleports.PortalLibraryRaidPos then
        local pos = MDungeonTeleports.PortalLibraryRaidPos

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

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

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

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

-- load on login
local function OnPlayerLogin()
    UpdatePortalLibRaidBackground()
    LoadPortalLibraryRaidPosition()
    UpdatePortalLibraryRaidUI()
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 PortalLibraryRaid_UpdateVisibility(show)
    local portalLibraryRaidFrame = _G["PortalLibraryRaid"]
    if portalLibraryRaidFrame then
        portalLibraryRaidFrame:SetShown(show)
    end
end

-- data for buttons
local row1Data = {
    {icon = "Interface\\Icons\\achievement_raid_revendrethraid_castlenathria", spellID = 373190, name = "CN"},
    {icon = "Interface\\Icons\\achievement_raid_torghastraid", spellID = 373191, name = "SOD"},
    {icon = "Interface\\Icons\\inv_achievement_raid_progenitorraid", spellID = 373192, name = "STFO"}
}
local row2Data = {
    {icon = "Interface\\Icons\\achievement_raidprimalist_raid", spellID = 432254, name = "VOTI"},
    {icon = "Interface\\Icons\\inv_achievement_raiddragon_raid", spellID = 432257, name = "ATSC"},
    {icon = "Interface\\Icons\\inv_achievement_raidemeralddream_raid", spellID = 432258, name = "ATDH"}
}
-- frame
local PortalLibraryRaid = CreateFrame("Frame", "PortalLibraryRaid", PVEFrame)
PortalLibraryRaid:SetSize(348, 90)
PortalLibraryRaid:SetPoint("CENTER", PVEFrame, "CENTER", 860, -270)
PortalLibraryRaid:SetMovable(true)
PortalLibraryRaid:EnableMouse(true)
PortalLibraryRaid:RegisterForDrag("LeftButton")
PortalLibraryRaid:SetClampedToScreen(true)

-- track flag
PortalLibraryRaid.isBeingDragged = false

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

PortalLibraryRaid:SetScript(
    "OnDragStop",
    function(self)
        if self.isBeingDragged then
            self:StopMovingOrSizing()
            SavePortalLibraryRaidPosition()
            self.isBeingDragged = false
            ReattachPortalLibraryRaid()
        end
    end
)

-- backgroundPortalLibRaid
local backgroundPortalLibRaid = PortalLibraryRaid:CreateTexture(nil, "Background")
backgroundPortalLibRaid:SetAllPoints(PortalLibraryRaid)
backgroundPortalLibRaid:SetTexture("Interface/AddOns/MDungeonTeleports/media/frames/default_frames.blp")
backgroundPortalLibRaid:SetTexCoord(0.160156, 0.5, 0.439453, 0.527343)
backgroundPortalLibRaid:SetVertexColor(1, 1, 1, 1)

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

-- titles
local PortalLibraryRaidTitle = PortalLibraryRaid:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
PortalLibraryRaidTitle:SetPoint("TOP", PortalLibraryRaid, "TOP", 0, -10)
PortalLibraryRaidTitle:SetFont("Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf", 13, flags)
PortalLibraryRaidTitle:SetText("Portal Library [Raid]")
-- expansion titles
-- shadowlands
local titleShadowlands = PortalLibraryRaid:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
titleShadowlands:SetPoint("TOP", PortalLibraryRaid, "TOPLEFT", 75, -27)
local font, _, flags = titleShadowlands:GetFont()
titleShadowlands:SetFont("Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf", 11, flags)
titleShadowlands:SetTextColor(0.2, 0.8, 0.9)
titleShadowlands:SetText("--Shadowlands--")
-- dragonflight
local titleDragonflight = PortalLibraryRaid:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
titleDragonflight:SetPoint("TOP", PortalLibraryRaid, "TOPRIGHT", -75, -27)
local font, _, flags = titleDragonflight:GetFont()
titleDragonflight:SetFont("Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf", 11, flags)
titleDragonflight:SetTextColor(0.2, 0.8, 0.9)
titleDragonflight:SetText("--Dragonflight--")

-- buttons settings
local buttonSize = 32
local buttonSpacing = 5
local rowOffset = -40

-- 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())

            -- Hide text and overlay if remaining time is 5 seconds or less
            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 buttons
local function CreateSpellButton(parent, data, rowOffset, horizontalOffset)
    local button = CreateFrame("Button", nil, parent, "SecureActionButtonTemplate")
    button:SetSize(buttonSize, buttonSize)
    button:SetPoint(
        "TOPLEFT",
        parent,
        "TOPLEFT",
        (data.index - 1) * (buttonSize + buttonSpacing) + 10 + (horizontalOffset or 0),
        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 UpdatePortalLibraryRaidUI()
    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

-- row1 --shadowlands
local row1HorizontalOffset = 13
for i, data in ipairs(row1Data) do
    data.index = i
    CreateSpellButton(PortalLibraryRaid, data, rowOffset, row1HorizontalOffset)
end
-- row2 --dragonflight
local row2Offset = -40
local row2HorizontalOffset = 210
for i, data in ipairs(row2Data) do
    data.index = i
    CreateSpellButton(PortalLibraryRaid, data, row2Offset, row2HorizontalOffset)
end

UpdatePortalLibraryRaidUI()
