local ADDON_NAME, NS = ...
local L = LibStub("AceLocale-3.0"):GetLocale("MDungeonTeleports")

local addonName = "MDungeonTeleports"
local version = C_AddOns.GetAddOnMetadata(addonName, "Version") or "Unknown"

local function GetCurrentDate()
    return date("%Y%m%d")
end

-- MARK: Default Settings
local defaultSettings = {
    isSeason1PortalsShown = true,
    isSeason2PortalsShown = true,
    isSeason3PortalsShown = true,
    isPortalLibraryShown = true,
    isPortalLibraryRaidShown = true,
    isKeyFrameShown = true,
    selectedFramePack = FramePackCategories[1].items[1].value
}

-- Load Variables
if MDungeonTeleports == nil then
    MDungeonTeleports = {}
end

-- Assign Defaults
MDungeonTeleports.isSeason1PortalsShown =
    MDungeonTeleports.isSeason1PortalsShown ~= nil and MDungeonTeleports.isSeason1PortalsShown or
    defaultSettings.isSeason1PortalsShown
MDungeonTeleports.isSeason2PortalsShown =
    MDungeonTeleports.isSeason2PortalsShown ~= nil and MDungeonTeleports.isSeason2PortalsShown or
    defaultSettings.isSeason2PortalsShown
MDungeonTeleports.isSeason3PortalsShown =
    MDungeonTeleports.isSeason3PortalsShown ~= nil and MDungeonTeleports.isSeason3PortalsShown or
    defaultSettings.isSeason3PortalsShown
MDungeonTeleports.isPortalLibraryShown =
    MDungeonTeleports.isPortalLibraryShown ~= nil and MDungeonTeleports.isPortalLibraryShown or
    defaultSettings.isPortalLibraryShown
MDungeonTeleports.isPortalLibraryRaidShown =
    MDungeonTeleports.isPortalLibraryRaidShown ~= nil and MDungeonTeleports.isPortalLibraryRaidShown or
    defaultSettings.isPortalLibraryRaidShown
MDungeonTeleports.isKeyFrameShown =
    MDungeonTeleports.isKeyFrameShown ~= nil and MDungeonTeleports.isKeyFrameShown or defaultSettings.isKeyFrameShown
MDungeonTeleports.selectedFramePack = MDungeonTeleports.selectedFramePack or FramePackCategories[1].items[1].value

local function SaveSettings()
    if
        Season1CheckBox and Season2CheckBox and Season3CheckBox and PortalLibraryCheckBox and PortalLibraryRaidCheckBox and
            ToggleKeyFrameCheckBox
     then
        MDungeonTeleports.isSeason1PortalsShown = Season1CheckBox:GetChecked()
        MDungeonTeleports.isSeason2PortalsShown = Season2CheckBox:GetChecked()
        MDungeonTeleports.isSeason3PortalsShown = Season3CheckBox:GetChecked()
        MDungeonTeleports.isPortalLibraryShown = PortalLibraryCheckBox:GetChecked()
        MDungeonTeleports.isPortalLibraryRaidShown = PortalLibraryRaidCheckBox:GetChecked()
        MDungeonTeleports.isKeyFrameShown = ToggleKeyFrameCheckBox:GetChecked()
    end

    if selectedFramePackValue then
        MDungeonTeleports.selectedFramePack = selectedFramePackValue
    end
    MDungeonTeleports.frameScale = uiScaleSlider:GetValue()
end

-- MARK: Visibility Toggles
local function ToggleSeason1Portals(show)
    if Season1_UpdateVisibility then
        Season1_UpdateVisibility(show)
    end
    SaveSettings()
end

local function ToggleSeason2Portals(show)
    if Season2_UpdateVisibility then
        Season2_UpdateVisibility(show)
    end
    SaveSettings()
end

local function ToggleSeason3Portals(show)
    if Season3_UpdateVisibility then
        Season3_UpdateVisibility(show)
    end
    SaveSettings()
end

-- toggle portal library
local function TogglePortalLibrary(show)
    if PortalLibrary_UpdateVisibility then
        PortalLibrary_UpdateVisibility(show)
    end
    SaveSettings()
end

-- toggle raid portal library
local function TogglePortalLibraryRaid(show)
    if PortalLibraryRaid_UpdateVisibility then
        PortalLibraryRaid_UpdateVisibility(show)
    end
    SaveSettings()
end

-- toggle key frame
local function ToggleKeyFrame(show)
    if KeyFrame_UpdateVisibility then
        KeyFrame_UpdateVisibility(show)
    end
    SaveSettings()
end

-- MARK: Scale Update
function UpdateFrameScale(scale)
    if Season1 then
        Season1:SetScale(scale)
    end
    if Season2 then
        Season2:SetScale(scale)
    end
    if Season3 then
        Season3:SetScale(scale)
    end
    if PortalLibrary then
        PortalLibrary:SetScale(scale)
    end
    if PortalLibraryRaid then
        PortalLibraryRaid:SetScale(scale)
    end
    MDungeonTeleports.frameScale = scale
end

-- Font Check and Change
local UserFont = "Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf"

local function LocaleFontCheck()
    if GetLocale() == "zhCN" then 
        UserFont = "Interface/AddOns/MDungeonTeleports/media/fonts/sarasa.ttf"
    elseif GetLocale() == "koKR" then 
        UserFont = "Interface/AddOns/MDungeonTeleports/media/fonts/wanted.ttf"
    else 
        UserFont = "Interface/AddOns/MDungeonTeleports/media/fonts/expressway.ttf"
    end
end

LocaleFontCheck()

-- MARK: Settings Frame
local Settings = CreateFrame("Frame", "Settings", UIParent)
Settings:SetSize(420, 400)
Settings:SetPoint("CENTER")
Settings:SetMovable(true)
Settings:EnableMouse(true)
Settings:RegisterForDrag("LeftButton")
Settings:SetScript("OnDragStart", Settings.StartMoving)
Settings:SetScript("OnDragStop", Settings.StopMovingOrSizing)
Settings:Hide()
Settings:SetFrameStrata("DIALOG")
Settings:EnableKeyboard(true)
Settings:SetClampedToScreen(true)
Settings:SetScript(
    "OnKeyDown",
    function(self, key)
        if key == "ESCAPE" then
            self:Hide()
        else
            self:SetPropagateKeyboardInput(true)
        end
    end
)

-- backgroundSettings
local backgroundSettings = Settings:CreateTexture(nil, "BACKGROUND")
backgroundSettings:SetAllPoints(Settings)
backgroundSettings:SetTexture("Interface/AddOns/MDungeonTeleports/media/ui/ui_frames/ui_frames.blp")
backgroundSettings:SetTexCoord(0.589843, 1, 0, 0.78125)

-- title
local SettingsTitle = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
SettingsTitle:SetPoint("TOP", Settings, "TOP", 0, -7)
SettingsTitle:SetFont(UserFont, 12, flags)
SettingsTitle:SetText(L["SETTINGS"])

-- MARK: Section Titles
local SeasonTitle = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
SeasonTitle:SetPoint("CENTER", Settings, "TOPLEFT", 92, -35)
SeasonTitle:SetFont(UserFont, 10, flags)
SeasonTitle:SetTextColor(0.2, 0.8, 0.9)
SeasonTitle:SetText(L["SEASONS"])

local LibrariesTitle = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
LibrariesTitle:SetPoint("CENTER", Settings, "TOPLEFT", 92, -127)
LibrariesTitle:SetFont(UserFont, 10, flags)
LibrariesTitle:SetTextColor(0.2, 0.8, 0.9)
LibrariesTitle:SetText(L["LIBRARIES"])

local KeyTrackerTitle = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
KeyTrackerTitle:SetPoint("CENTER", Settings, "TOPLEFT", 92, -200)
KeyTrackerTitle:SetFont(UserFont, 10, flags)
KeyTrackerTitle:SetTextColor(0.2, 0.8, 0.9)
KeyTrackerTitle:SetText(L["KEYTRACKER"])

local RaidPortalTitle = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
RaidPortalTitle:SetPoint("CENTER", Settings, "TOPLEFT", 92, -272)
RaidPortalTitle:SetFont(UserFont, 10, flags)
RaidPortalTitle:SetTextColor(0.2, 0.8, 0.9)
RaidPortalTitle:SetText("Optional Raid Portal")
RaidPortalTitle:Hide() -- hidden

local FramePacksTitle = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
FramePacksTitle:SetPoint("CENTER", Settings, "TOPRIGHT", -92, -35)
FramePacksTitle:SetFont(UserFont, 10, flags)
FramePacksTitle:SetTextColor(0.2, 0.8, 0.9)
FramePacksTitle:SetText(L["FRAMEPACKS"])

local UIScaleTitle = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
UIScaleTitle:SetPoint("CENTER", Settings, "TOPRIGHT", -92, -107)
UIScaleTitle:SetFont(UserFont, 10, flags)
UIScaleTitle:SetTextColor(0.2, 0.8, 0.9)
UIScaleTitle:SetText(L["WINDOW_UI"])

local ExtraTitle = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
ExtraTitle:SetPoint("CENTER", Settings, "TOPRIGHT", -92, -185)
ExtraTitle:SetFont(UserFont, 10, flags)
ExtraTitle:SetTextColor(0.2, 0.8, 0.9)
ExtraTitle:SetText(L["EXTRA_FEATURES"])

-- addon data and information
local AddonInfo = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
AddonInfo:SetPoint("BOTTOM", Settings, "BOTTOM", 0, 13)
AddonInfo:SetFont(UserFont, 8, flags)
AddonInfo:SetText("M+ Dungeon Teleports by peepoStudy // " .. version .. "")
AddonInfo:SetTextColor(0.5, 0.5, 0.5)

-- MARK: Addon Usage
local AddonUsage1 = Settings:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
AddonUsage1:SetPoint("CENTER", Settings, "CENTER", 0, -154)
AddonUsage1:SetJustifyH("CENTER")
AddonUsage1:SetFont(UserFont, 10, flags)
AddonUsage1:SetText(L["ADDON_USAGE"])

-- MARK: Checkboxes
local textureCheckNormal = "Interface/AddOns/MDungeonTeleports/media/ui/ui_elements/checkbox.blp"
local textureCheckPushed = "Interface/AddOns/MDungeonTeleports/media/ui/ui_elements/checkbox_pushed.blp"
local textureCheckHighlight = "Interface/AddOns/MDungeonTeleports/media/ui/ui_elements/checkbox_highlight.blp"
local textureCheckChecked = "Interface/AddOns/MDungeonTeleports/media/ui/ui_elements/checkbox_checked.blp"

local function CreateCheckboxes()
    Season1CheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    Season1CheckBox:SetPoint("CENTER", Settings, "TOPLEFT", 29, -60)
    local font, _, flags = Season1CheckBox.Text:GetFont()
    Season1CheckBox.Text:SetFont(UserFont, 10, flags)
    Season1CheckBox.Text:SetPoint("LEFT", Season1CheckBox, "RIGHT", 0, 0)
    Season1CheckBox.Text:SetText(L["SEASON_1"])
    Season1CheckBox:SetChecked(MDungeonTeleports.isSeason1PortalsShown)
    Season1CheckBox:SetScript(
        "OnClick",
        function(self)
            ToggleSeason1Portals(self:GetChecked())
        end
    )

    Season1CheckBox:SetNormalTexture(textureCheckNormal)
    Season1CheckBox:SetPushedTexture(textureCheckPushed)
    Season1CheckBox:SetHighlightTexture(textureCheckHighlight)
    Season1CheckBox:SetCheckedTexture(textureCheckChecked)

    -- season2 checkbox
    Season2CheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    Season2CheckBox:SetPoint("CENTER", Settings, "TOPLEFT", 29, -80)
    local font, _, flags = Season2CheckBox.Text:GetFont()
    Season2CheckBox.Text:SetFont(UserFont, 10, flags)
    Season2CheckBox.Text:SetPoint("LEFT", Season2CheckBox, "RIGHT", 0, 0)
    Season2CheckBox.Text:SetText(L["SEASON_2"])
    Season2CheckBox:SetChecked(MDungeonTeleports.isSeason2PortalsShown)
    Season2CheckBox:SetScript(
        "OnClick",
        function(self)
            ToggleSeason2Portals(self:GetChecked())
        end
    )

    Season2CheckBox:SetNormalTexture(textureCheckNormal)
    Season2CheckBox:SetPushedTexture(textureCheckPushed)
    Season2CheckBox:SetHighlightTexture(textureCheckHighlight)
    Season2CheckBox:SetCheckedTexture(textureCheckChecked)

    Season3CheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    Season3CheckBox:SetPoint("CENTER", Settings, "TOPLEFT", 29, -100)
    local font, _, flags = Season3CheckBox.Text:GetFont()
    Season3CheckBox.Text:SetFont(UserFont, 10, flags)
    Season3CheckBox.Text:SetPoint("LEFT", Season3CheckBox, "RIGHT", 0, 0)
    Season3CheckBox.Text:SetText(L["SEASON_3"])
    Season3CheckBox:SetChecked(MDungeonTeleports.isSeason3PortalsShown)
    Season3CheckBox:SetScript(
        "OnClick",
        function(self)
            ToggleSeason3Portals(self:GetChecked())
        end
    )

    Season3CheckBox:SetNormalTexture(textureCheckNormal)
    Season3CheckBox:SetPushedTexture(textureCheckPushed)
    Season3CheckBox:SetHighlightTexture(textureCheckHighlight)
    Season3CheckBox:SetCheckedTexture(textureCheckChecked)

    PortalLibraryCheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    PortalLibraryCheckBox:SetPoint("CENTER", Settings, "TOPLEFT", 29, -154)
    local font, _, flags = PortalLibraryCheckBox.Text:GetFont()
    PortalLibraryCheckBox.Text:SetFont(UserFont, 10, flags)
    PortalLibraryCheckBox.Text:SetPoint("LEFT", PortalLibraryCheckBox, "RIGHT", 0, 0)
    PortalLibraryCheckBox.Text:SetText(L["DUNGEON_LIBRARY"])
    PortalLibraryCheckBox:SetChecked(MDungeonTeleports.isPortalLibraryShown)
    PortalLibraryCheckBox:SetScript(
        "OnClick",
        function(self)
            TogglePortalLibrary(self:GetChecked())
        end
    )

    PortalLibraryCheckBox:SetNormalTexture(textureCheckNormal)
    PortalLibraryCheckBox:SetPushedTexture(textureCheckPushed)
    PortalLibraryCheckBox:SetHighlightTexture(textureCheckHighlight)
    PortalLibraryCheckBox:SetCheckedTexture(textureCheckChecked)

    PortalLibraryRaidCheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    PortalLibraryRaidCheckBox:SetPoint("CENTER", Settings, "TOPLEFT", 29, -174)
    local font, _, flags = PortalLibraryRaidCheckBox.Text:GetFont()
    PortalLibraryRaidCheckBox.Text:SetFont(UserFont, 10, flags)
    PortalLibraryRaidCheckBox.Text:SetPoint("LEFT", PortalLibraryRaidCheckBox, "RIGHT", 0, 0)
    PortalLibraryRaidCheckBox.Text:SetText(L["RAID_LIBRARY"])
    PortalLibraryRaidCheckBox:SetChecked(MDungeonTeleports.isPortalLibraryRaidShown)
    PortalLibraryRaidCheckBox:SetScript(
        "OnClick",
        function(self)
            TogglePortalLibraryRaid(self:GetChecked())
        end
    )

    PortalLibraryRaidCheckBox:SetNormalTexture(textureCheckNormal)
    PortalLibraryRaidCheckBox:SetPushedTexture(textureCheckPushed)
    PortalLibraryRaidCheckBox:SetHighlightTexture(textureCheckHighlight)
    PortalLibraryRaidCheckBox:SetCheckedTexture(textureCheckChecked)

    -- keyframe
    ToggleKeyFrameCheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    ToggleKeyFrameCheckBox:SetPoint("CENTER", Settings, "TOPLEFT", 29, -226)
    local font, _, flags = ToggleKeyFrameCheckBox.Text:GetFont()
    ToggleKeyFrameCheckBox.Text:SetFont(UserFont, 10, flags)
    ToggleKeyFrameCheckBox.Text:SetPoint("LEFT", ToggleKeyFrameCheckBox, "RIGHT", 0, 0)
    ToggleKeyFrameCheckBox.Text:SetText(L["KEYTRACKER"])
    ToggleKeyFrameCheckBox:SetChecked(MDungeonTeleports.isKeyFrameShown)
    ToggleKeyFrameCheckBox:SetScript(
        "OnClick",
        function(self)
            ToggleKeyFrame(self:GetChecked())
        end
    )

    ToggleKeyFrameCheckBox:SetNormalTexture(textureCheckNormal)
    ToggleKeyFrameCheckBox:SetPushedTexture(textureCheckPushed)
    ToggleKeyFrameCheckBox:SetHighlightTexture(textureCheckHighlight)
    ToggleKeyFrameCheckBox:SetCheckedTexture(textureCheckChecked)

    -- respond to keys
    RespondKeyCheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    RespondKeyCheckBox:SetPoint("CENTER", Settings, "TOPLEFT", 29, -246)
    local font, _, flags = RespondKeyCheckBox.Text:GetFont()
    RespondKeyCheckBox.Text:SetFont(UserFont, 10, flags)
    RespondKeyCheckBox.Text:SetPoint("LEFT", RespondKeyCheckBox, "RIGHT", 0, 0)
    RespondKeyCheckBox.Text:SetText(L["RESPOND_TO_KEYS"])
    RespondKeyCheckBox:SetChecked(MDungeonTeleports.isRespondChecked)
    RespondKeyCheckBox:SetScript(
        "OnClick",
        function(self)
            MDungeonTeleports.isRespondChecked = (self:GetChecked())
            SaveSettings()
        end
    )
    RespondKeyCheckBox:SetEnabled(true)

    RespondKeyCheckBox:SetNormalTexture(textureCheckNormal)
    RespondKeyCheckBox:SetPushedTexture(textureCheckPushed)
    RespondKeyCheckBox:SetHighlightTexture(textureCheckHighlight)
    RespondKeyCheckBox:SetCheckedTexture(textureCheckChecked)

    -- optraidport checkbox
    OptRaidPortalToggle = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    OptRaidPortalToggle:SetPoint("CENTER", Settings, "TOPLEFT", 29, -296)
    local font, _, flags = OptRaidPortalToggle.Text:GetFont()
    OptRaidPortalToggle.Text:SetFont(UserFont, 10, flags)
    OptRaidPortalToggle.Text:SetTextColor(0.5, 0.5, 0.5)
    OptRaidPortalToggle.Text:SetPoint("LEFT", OptRaidPortalToggle, "RIGHT", 0, 0)
    OptRaidPortalToggle.Text:SetText("Liberation Portal on S2")
    OptRaidPortalToggle:SetEnabled(false)
    OptRaidPortalToggle:Hide()

    OptRaidPortalToggle:SetNormalTexture(textureCheckNormal)
    OptRaidPortalToggle:SetPushedTexture(textureCheckPushed)
    OptRaidPortalToggle:SetHighlightTexture(textureCheckHighlight)
    OptRaidPortalToggle:SetCheckedTexture(textureCheckChecked)

    -- MARK: Check Boxes Row 2
    -- tooltips
    ToggleTooltips = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    ToggleTooltips:SetPoint("CENTER", Settings, "TOPRIGHT", -156, -210)
    local font, _, flags = ToggleTooltips.Text:GetFont()
    ToggleTooltips.Text:SetFont(UserFont, 10, flags)
    ToggleTooltips.Text:SetPoint("LEFT", ToggleTooltips, "RIGHT", 0, 0)
    ToggleTooltips.Text:SetText(L["TOOLTIPS"])
    ToggleTooltips:SetChecked(MDungeonTeleports.showTooltips)
    ToggleTooltips:SetScript(
        "OnClick",
        function(self)
            MDungeonTeleports.showTooltips = self:GetChecked()
        end
    )

    ToggleTooltips:SetNormalTexture(textureCheckNormal)
    ToggleTooltips:SetPushedTexture(textureCheckPushed)
    ToggleTooltips:SetHighlightTexture(textureCheckHighlight)
    ToggleTooltips:SetCheckedTexture(textureCheckChecked)

    -- compactmodebox
    CompactModeBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    CompactModeBox:SetPoint("CENTER", Settings, "TOPRIGHT", -156, -230)
    local font, _, flags = CompactModeBox.Text:GetFont()
    CompactModeBox.Text:SetFont(UserFont, 10, flags)
    CompactModeBox.Text:SetPoint("LEFT", CompactModeBox, "RIGHT", 0, 0)
    CompactModeBox.Text:SetText(L["COMPACT_MODE"])
    CompactModeBox:SetChecked(MDungeonTeleports.CompactMode)
    CompactModeBox:SetScript(
        "OnClick",
        function(self)
            MDungeonTeleports.CompactMode = self:GetChecked()
            if CompactModeBox then
                CompactModeSeason1()
                CompactModeSeason2()
                CompactModeSeason3()
                CompactModePortalLibrary()
                CompactModePortalLibraryRaid()
                if UpdateSeason1UI then
                    UpdateSeason1UI()
                end
                if UpdateSeason2UI then
                    UpdateSeason2UI()
                end
                if UpdateSeason3UI then
                    UpdateSeason3UI()
                end
                if UpdatePortalLibraryUI then
                    UpdatePortalLibraryUI()
                end
                if UpdatePortalLibraryRaidUI then
                    UpdatePortalLibraryRaidUI()
                end
                if UpdateSeason1Background then
                    UpdateSeason1Background()
                end
                if UpdateSeason2Background then
                    UpdateSeason2Background()
                end
                if UpdateSeason3Background then
                    UpdateSeason3Background()
                end
                if UpdatePortalLibraryBackground then
                    UpdatePortalLibraryBackground()
                end
                if UpdatePortalLibRaidBackground then
                    UpdatePortalLibRaidBackground()
                end
            end
        end
    )

    CompactModeBox:SetNormalTexture(textureCheckNormal)
    CompactModeBox:SetPushedTexture(textureCheckPushed)
    CompactModeBox:SetHighlightTexture(textureCheckHighlight)
    CompactModeBox:SetCheckedTexture(textureCheckChecked)

    -- Tooltip setup
    CompactModeBox:SetScript(
        "OnEnter",
        function(self)
            GameTooltip:SetOwner(self, "ANCHOR_CURSOR")
            GameTooltip:SetText(L["FRAMEPACK_TOOLTIP_WARNING"], 1, 1, 1) -- Text color is white (1, 1, 1)
            GameTooltip:Show()
        end
    )

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

    -- altlockbox
    AltLocksBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    AltLocksBox:SetPoint("CENTER", Settings, "TOPRIGHT", -156, -250)
    local font, _, flags = AltLocksBox.Text:GetFont()
    AltLocksBox.Text:SetFont(UserFont, 10, flags)
    AltLocksBox.Text:SetPoint("LEFT", AltLocksBox, "RIGHT", 0, 0)
    AltLocksBox.Text:SetText(L["ALT_LOCK_ICONS"])
    AltLocksBox:SetChecked(MDungeonTeleports.AltLocks)
    AltLocksBox:SetScript(
        "OnClick",
        function(self)
            MDungeonTeleports.AltLocks = self:GetChecked()
            if UpdateSeason1UI then
                UpdateSeason1UI()
            end
            if UpdateSeason2UI then
                UpdateSeason2UI()
            end
            if UpdateSeason3UI then
                UpdateSeason3UI()
            end
            if UpdatePortalLibraryUI then
                UpdatePortalLibraryUI()
            end
            if UpdatePortalLibraryRaidUI then
                UpdatePortalLibraryRaidUI()
            end
        end
    )

    AltLocksBox:SetNormalTexture(textureCheckNormal)
    AltLocksBox:SetPushedTexture(textureCheckPushed)
    AltLocksBox:SetHighlightTexture(textureCheckHighlight)
    AltLocksBox:SetCheckedTexture(textureCheckChecked)

    --TrayModeToggle
    TrayModeToggleBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    TrayModeToggleBox:SetPoint("CENTER", Settings, "TOPRIGHT", -156, -270)
    local font, _, flags = TrayModeToggleBox.Text:GetFont()
    TrayModeToggleBox.Text:SetFont(UserFont, 10, flags)
    TrayModeToggleBox.Text:SetPoint("LEFT", TrayModeToggleBox, "RIGHT", 0, 0)
    TrayModeToggleBox.Text:SetText(L["TRAY_MODE"])
    TrayModeToggleBox:SetChecked(MDungeonTeleports.TrayMode)
    TrayModeToggleBox:SetScript(
        "OnClick",
        function(self)
            MDungeonTeleports.TrayMode = self:GetChecked()
            if TrayModeToggleSeason1 then
                TrayModeToggleSeason1()
            end
            if TrayModeToggleSeason2 then
                TrayModeToggleSeason2()
            end
            if TrayModeToggleSeason3 then
                TrayModeToggleSeason3()
            end
        end
    )

    TrayModeToggleBox:SetNormalTexture(textureCheckNormal)
    TrayModeToggleBox:SetPushedTexture(textureCheckPushed)
    TrayModeToggleBox:SetHighlightTexture(textureCheckHighlight)
    TrayModeToggleBox:SetCheckedTexture(textureCheckChecked)

    -- Shift Movement Toggle
    ShiftMoveCheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    ShiftMoveCheckBox:SetPoint("CENTER", Settings, "TOPRIGHT", -156, -290)
    local font, _, flags = ShiftMoveCheckBox.Text:GetFont()
    ShiftMoveCheckBox.Text:SetFont(UserFont, 10, flags)
    ShiftMoveCheckBox.Text:SetPoint("LEFT", ShiftMoveCheckBox, "RIGHT", 0, 0)
    ShiftMoveCheckBox.Text:SetText(L["LOCK_FRAMES"])
    ShiftMoveCheckBox:SetChecked(MDungeonTeleports.ShiftDragToggle)
    ShiftMoveCheckBox:SetScript(
        "OnClick",
        function(self)
            MDungeonTeleports.ShiftDragToggle = self:GetChecked()
            if ShiftMoveCheckBox then
                if ShiftDragToggleS1 then
                    ShiftDragToggleS1()
                end
                if ShiftDragToggleS2 then
                    ShiftDragToggleS2()
                end
                if ShiftDragToggleS3 then
                    ShiftDragToggleS3()
                end
                if ShiftDragToggleDL then
                    ShiftDragToggleDL()
                end
                if ShiftDragToggleRL then
                    ShiftDragToggleRL()
                end
                if ShiftDragToggleKT then
                    ShiftDragToggleKT()
                end
            end
        end
    )

    -- Tooltip setup
    ShiftMoveCheckBox:SetScript(
        "OnEnter",
        function(self)
            GameTooltip:SetOwner(self, "ANCHOR_CURSOR")
            GameTooltip:SetText(L["LOCK_FRAME_USE"], 1, 1, 1) -- Text color is white (1, 1, 1)
            GameTooltip:Show()
        end
    )

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

    ShiftMoveCheckBox:SetNormalTexture(textureCheckNormal)
    ShiftMoveCheckBox:SetPushedTexture(textureCheckPushed)
    ShiftMoveCheckBox:SetHighlightTexture(textureCheckHighlight)
    ShiftMoveCheckBox:SetCheckedTexture(textureCheckChecked)

    -- Login Message Toggle
    LoginMessageCheckBox = CreateFrame("CheckButton", nil, Settings, "ChatConfigCheckButtonTemplate")
    LoginMessageCheckBox:SetPoint("CENTER", Settings, "TOPRIGHT", -156, -310)
    local font, _, flags = LoginMessageCheckBox.Text:GetFont()
    LoginMessageCheckBox.Text:SetFont(UserFont, 10, flags)
    LoginMessageCheckBox.Text:SetPoint("LEFT", LoginMessageCheckBox, "RIGHT", 0, 0)
    LoginMessageCheckBox.Text:SetText(L["LOGIN_MESSAGE"])
    LoginMessageCheckBox:SetChecked(MDungeonTeleports.LoginMessageToggle)
    LoginMessageCheckBox:SetScript(
        "OnClick",
        function(self)
            MDungeonTeleports.LoginMessageToggle = self:GetChecked()
        end
    )

    LoginMessageCheckBox:SetNormalTexture(textureCheckNormal)
    LoginMessageCheckBox:SetPushedTexture(textureCheckPushed)
    LoginMessageCheckBox:SetHighlightTexture(textureCheckHighlight)
    LoginMessageCheckBox:SetCheckedTexture(textureCheckChecked)
end

CreateCheckboxes()

-- MARK: Dropdown Framepack
local FramePackDropdown = CreateFrame("Frame", "FramePackDropdown", Settings, "UIDropDownMenuTemplate")
FramePackDropdown:SetPoint("CENTER", Settings, "TOPRIGHT", -93, -79)

local FramePackDropdownLabel = FramePackDropdown:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
local font, _, flags = FramePackDropdownLabel:GetFont()
FramePackDropdownLabel:SetFont(UserFont, 10, flags)
FramePackDropdownLabel:SetPoint("TOP", FramePackDropdown, "TOP", 0, 10)
FramePackDropdownLabel:SetText(L["SELECT_FRAMEPACK"])

local selectedFramePackValue = MDungeonTeleports.selectedFramePack
local selectedUIPack = MDungeonTeleports.selectedUIPack

-- Function to update the dropdown text based on the selected frame pack
local function UpdateDropdownText(value)
    -- Find the corresponding text for the selected value
    for _, category in pairs(FramePackCategories) do
        for _, option in pairs(category.items) do
            if option.value == value then
                -- Update the text shown inside the dropdown
                UIDropDownMenu_SetText(FramePackDropdown, option.text) -- Update dropdown display text
                return
            end
        end
    end
    -- Fallback
    UIDropDownMenu_SetText(FramePackDropdown, L["SELECT_FRAMEPACK"])
end

local function InitializeDropdown(self, level, menulist)
    local info = UIDropDownMenu_CreateInfo()

    -- Level 1: Show main categories
    if level == 1 then
        -- Level 2: Show the frame packs within each category
        for _, category in pairs(FramePackCategories) do
            info.text = category.category
            info.hasArrow = true
            info.notCheckable = true
            info.menuList = category.items
            UIDropDownMenu_AddButton(info, level)
        end
    elseif level == 2 and menulist then
        for _, option in pairs(menulist) do
            info.text = option.text
            info.func = function(self)
                -- Set the selected frame pack and UI pack
                selectedFramePackValue = option.value
                selectedUIPack = option.value2

                -- Update the saved variables
                MDungeonTeleports.selectedFramePack = selectedFramePackValue
                MDungeonTeleports.selectedUIPack = selectedUIPack

                -- Set the dropdown to show the selected value
                UIDropDownMenu_SetSelectedValue(FramePackDropdown, selectedFramePackValue)

                -- Update the dropdown text to reflect the selected option
                UpdateDropdownText(selectedFramePackValue)

                -- Call update functions for UI
                if UpdateSeason1Background then
                    UpdateSeason1Background()
                end
                if UpdateSeason2Background then
                    UpdateSeason2Background()
                end
                if UpdateSeason3Background then
                    UpdateSeason3Background()
                end
                if UpdatePortalLibraryBackground then
                    UpdatePortalLibraryBackground()
                end
                if UpdatePortalLibRaidBackground then
                    UpdatePortalLibRaidBackground()
                end

                -- Update UI packs
                if UpdateSeason1UI then
                    UpdateSeason1UI()
                end
                if UpdateSeason2UI then
                    UpdateSeason2UI()
                end
                if UpdateSeason3UI then
                    UpdateSeason3UI()
                end
                if UpdatePortalLibraryUI then
                    UpdatePortalLibraryUI()
                end
                if UpdatePortalLibraryRaidUI then
                    UpdatePortalLibraryRaidUI()
                end
                -- Save settings
                SaveSettings()
            end
            info.notCheckable = true
            UIDropDownMenu_AddButton(info, level)
        end
    end
end

-- Initialize the dropdown
UIDropDownMenu_Initialize(FramePackDropdown, InitializeDropdown)
UIDropDownMenu_SetWidth(FramePackDropdown, 120)
UIDropDownMenu_SetButtonWidth(FramePackDropdown, 164)
UIDropDownMenu_SetSelectedValue(FramePackDropdown, selectedFramePackValue)
UIDropDownMenu_JustifyText(FramePackDropdown, "LEFT")

UpdateDropdownText(selectedFramePackValue)

-- MARK: UI Slider
local uiScaleSlider = CreateFrame("Slider", "uiScaleSlider", Settings, "OptionsSliderTemplate")
uiScaleSlider:SetPoint("CENTER", Settings, "TOPRIGHT", -92, -145)
uiScaleSlider:SetMinMaxValues(0.8, 1.2)
uiScaleSlider:SetValue(MDungeonTeleports.scaleSliderValue or 50)
uiScaleSlider:SetValueStep(0.1)
uiScaleSlider:SetWidth(135)

-- minimum label
local minLabel = _G[uiScaleSlider:GetName() .. "Low"]
minLabel:SetText("-20%")
minLabel:SetFont(UserFont, 10, flags)
-- maximum label
local maxLabel = _G[uiScaleSlider:GetName() .. "High"]
maxLabel:SetText("+20%")
maxLabel:SetFont(UserFont, 10, flags)
-- text label for the slider
local textLabel = _G[uiScaleSlider:GetName() .. "Text"]
textLabel:SetText(L["SCALE_SLIDER"])
textLabel:SetFont(UserFont, 10, flags)
-- OnValueChanged handler for the slider
uiScaleSlider:SetScript(
    "OnValueChanged",
    function(self, value)
        -- Round to one decimal place
        local scale = math.floor(value * 10 + 0.5) / 10
        -- Update the scale globally
        UpdateFrameScale(scale)
    end
)

uiScaleSlider:SetValue(MDungeonTeleports.frameScale or 1.0)

-- Update the UI with the current settings
local function UpdateUI()
    if
        Season1CheckBox and Season2CheckBox and Season3CheckBox and PortalLibraryRaidCheckBox and PortalLibraryCheckBox and
            ToggleKeyFrameCheckBox
     then
        Season1CheckBox:SetChecked(MDungeonTeleports.isSeason1PortalsShown)
        Season2CheckBox:SetChecked(MDungeonTeleports.isSeason2PortalsShown)
        Season3CheckBox:SetChecked(MDungeonTeleports.isSeason3PortalsShown)
        PortalLibraryCheckBox:SetChecked(MDungeonTeleports.isPortalLibraryShown)
        PortalLibraryRaidCheckBox:SetChecked(MDungeonTeleports.isPortalLibraryRaidShown)
        ToggleKeyFrameCheckBox:SetChecked(MDungeonTeleports.isKeyFrameShown)
        UIDropDownMenu_SetSelectedValue(FramePackDropdown, MDungeonTeleports.selectedFramePack)
        UpdateDropdownText(selectedFramePackValue)

        ToggleSeason1Portals(MDungeonTeleports.isSeason1PortalsShown)
        ToggleSeason2Portals(MDungeonTeleports.isSeason2PortalsShown)
        ToggleSeason3Portals(MDungeonTeleports.isSeason3PortalsShown)
        TogglePortalLibrary(MDungeonTeleports.isPortalLibraryShown)
        TogglePortalLibraryRaid(MDungeonTeleports.isPortalLibraryRaidShown)
        ToggleKeyFrame(MDungeonTeleports.isKeyFrameShown)
    end
    if RespondKeyCheckBox then
        RespondKeyCheckBox:SetChecked(MDungeonTeleports.isRespondChecked)
    end
    if ToggleTooltips then
        ToggleTooltips:SetChecked(MDungeonTeleports.showTooltips)
    end
    if CompactModeBox then
        CompactModeBox:SetChecked(MDungeonTeleports.CompactMode)
    end
    if AltLocksBox then
        AltLocksBox:SetChecked(MDungeonTeleports.AltLocks)
    end
    if TrayModeToggleBox then
        TrayModeToggleBox:SetChecked(MDungeonTeleports.TrayMode)
    end
    if ShiftMoveCheckBox then 
        ShiftMoveCheckBox:SetChecked(MDungeonTeleports.ShiftDragToggle)
    end
end

-- MARK: Reset Button
local resetButton = CreateFrame("Button", "ResetButton", Settings)
resetButton:SetSize(24, 24)
resetButton:SetPoint("BOTTOMLEFT", Settings, "BOTTOMLEFT", 4, 4)
resetButton:SetFrameStrata("DIALOG")

local resetButtonTexture = resetButton:CreateTexture(nil, "BACKGROUND")
resetButtonTexture:SetAllPoints(resetButton)
resetButtonTexture:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_reset.blp")

local resetButtonHighlight = resetButton:CreateTexture(nil, "HIGHLIGHT")
resetButtonHighlight:SetAllPoints(resetButton)
resetButtonHighlight:SetTexture(
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_reset_highlight.blp"
)
resetButtonHighlight:Hide()

resetButton.resetButtonHighlight = resetButtonHighlight
resetButton.resetButtonTexture = resetButtonTexture

resetButton:SetScript(
    "OnEnter",
    function(self)
        self.resetButtonHighlight:Show()
        self.resetButtonTexture:Hide()
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetText(L["RESET_ADDON"], 1, 1, 1)
        GameTooltip:AddLine(L["RESET_ADDON_TIP"], nil, nil, nil, true)
        GameTooltip:Show()
    end
)

resetButton:SetScript(
    "OnLeave",
    function(self)
        self.resetButtonHighlight:Hide()
        self.resetButtonTexture:Show()
        GameTooltip:Hide()
    end
)

-- MARK: Reset Script

resetButton:SetScript(
    "OnClick",
    function(self)
        MDungeonTeleports.PortalLibraryRaidPos = {x = 1110, y = 198}
        MDungeonTeleports.PortalLibraryPos = {x = 970, y = -100}
        MDungeonTeleports.Season1Pos = {x = 1005, y = -19}
        MDungeonTeleports.Season2Pos = {x = 1005, y = -152}
        MDungeonTeleports.Season3Pos = {x = 1005, y = -285}
        MDungeonTeleports.KeyTrackerPos = {x = 442, y = -429}
        MDungeonTeleports.frameScale = 1
        MDungeonTeleports.isPortalLibraryRaidShown = true
        MDungeonTeleports.isSeason1PortalsShown = true
        MDungeonTeleports.isSeason2PortalsShown = true
        MDungeonTeleports.isSeason3PortalsShown = true
        MDungeonTeleports.isPortalLibraryShown = true
        MDungeonTeleports.isKeyFrameShown = true
        MDungeonTeleports.showTooltips = false
        MDungeonTeleports.CompactMode = false
        MDungeonTeleports.AltLocks = false
        MDungeonTeleports.TrayMode = false
        MDungeonTeleports.ShiftDragToggle = false
        MDungeonTeleports.isRespondChecked = false
        MDungeonTeleports.selectedFramePack = FramePackCategories[1].items[1].value
        MDungeonTeleports.selectedUIPack = "Interface/AddOns/MDungeonTeleports/media/ui/ui_default/"
        ReloadUI()
    end
)

-- MARK: Settings Exit Button
local settingsExitButton = CreateFrame("Button", "SettingsOpenButton", Settings)
settingsExitButton:SetSize(14, 14)
settingsExitButton:SetPoint("TOPRIGHT", Settings, "TOPRIGHT", -5, -5)
settingsExitButton:SetFrameStrata("DIALOG")

local settingExitButtonTexture = settingsExitButton:CreateTexture(nil, "BACKGROUND")
settingExitButtonTexture:SetAllPoints(settingsExitButton)
settingExitButtonTexture:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_close.blp")

local settingsExitButtonHighlight = settingsExitButton:CreateTexture(nil, "HIGHLIGHT")
settingsExitButtonHighlight:SetAllPoints(settingsExitButton)
settingsExitButtonHighlight:SetTexture(
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_close_highlight.blp"
)
settingsExitButtonHighlight:Hide()

settingsExitButton.settingsExitButtonHighlight = settingsExitButtonHighlight
settingsExitButton.settingExitButtonTexture = settingExitButtonTexture

settingsExitButton:SetScript(
    "OnEnter",
    function(self)
        self.settingsExitButtonHighlight:Show()
        self.settingExitButtonTexture:Hide()
    end
)

settingsExitButton:SetScript(
    "OnLeave",
    function(self)
        self.settingsExitButtonHighlight:Hide()
        self.settingExitButtonTexture:Show()
    end
)

settingsExitButton:SetScript(
    "OnClick",
    function()
        PlaySound(SOUNDKIT.IG_CHARACTER_INFO_CLOSE)
        Settings:Hide()
    end
)

-- Ensure compatibility with both the new and old API versions
local IsAddOnLoaded = IsAddOnLoaded or C_AddOns.IsAddOnLoaded

-- MARK: PVE Settings Button
local settingsOpenButton = CreateFrame("Button", "SettingsOpenButton", PVEFrame)

-- Check if ElvUI is loaded
local isElvUILoaded = IsAddOnLoaded("ElvUI")

-- Set button size based on whether ElvUI is loaded
if isElvUILoaded then
    settingsOpenButton:SetSize(14, 14) -- Size for ElvUI
    settingsOpenButton:SetPoint("TOPRIGHT", PVEFrame, "TOPRIGHT", -22, -5)
else
    settingsOpenButton:SetSize(21, 21) -- Default size if ElvUI is not loaded
    settingsOpenButton:SetPoint("TOPRIGHT", PVEFrame, "TOPRIGHT", -22, -1)
end

settingsOpenButton:SetFrameStrata("DIALOG")

-- Define textures
local defaultTexture = "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_elements\\settings_buttons.blp"
local elvuiTexture = "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_settings.blp"

-- Non-ElvUI texture coordinates provided
local defaultNormalCoords = {0.054687, 0.304687, 0.046875, 0.296875} -- Normal state
local defaultHighlightCoords = {0.351562, 0.601562, 0.046875, 0.296875} -- Highlight state
local defaultPressedCoords = {0.054687, 0.304687, 0.3828125, 0.632812} -- Pressed state

-- ElvUI texture paths (these will use the full texture for each state)
local elvuiHighlightTexture =
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_settings_highlight.blp"
local elvuiPressedTexture = "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_settings_pressed.blp"

-- Set main texture
local settingsOpenButtonTexture = settingsOpenButton:CreateTexture(nil, "BACKGROUND")
settingsOpenButtonTexture:SetAllPoints(settingsOpenButton)
settingsOpenButtonTexture:SetTexture(isElvUILoaded and elvuiTexture or defaultTexture)

-- Apply texture coordinates based on ElvUI status
if not isElvUILoaded then
    settingsOpenButtonTexture:SetTexCoord(unpack(defaultNormalCoords))
end

-- Set up highlight texture
local settingsButtonHoverOverlay = settingsOpenButton:CreateTexture(nil, "HIGHLIGHT")
settingsButtonHoverOverlay:SetAllPoints(settingsOpenButton)
settingsButtonHoverOverlay:SetTexture(isElvUILoaded and elvuiHighlightTexture or defaultTexture)
settingsButtonHoverOverlay:Hide()

if not isElvUILoaded then
    settingsButtonHoverOverlay:SetTexCoord(unpack(defaultHighlightCoords))
end

-- Define the pressed texture
local settingsButtonPressedOverlay = settingsOpenButton:CreateTexture(nil, "BACKGROUND")
settingsButtonPressedOverlay:SetAllPoints(settingsOpenButton)
settingsButtonPressedOverlay:SetTexture(isElvUILoaded and elvuiPressedTexture or defaultTexture)
settingsButtonPressedOverlay:Hide()

if not isElvUILoaded then
    settingsButtonPressedOverlay:SetTexCoord(unpack(defaultPressedCoords))
end

settingsOpenButton.settingsOpenButtonTexture = settingsOpenButtonTexture
settingsOpenButton.settingsButtonHoverOverlay = settingsButtonHoverOverlay
settingsOpenButton.settingsButtonPressedOverlay = settingsButtonPressedOverlay

-- Tooltip and interaction scripts
settingsOpenButton:SetScript(
    "OnEnter",
    function(self)
        self.settingsButtonHoverOverlay:Show()
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetText(L["MDT_FULL"], 1, 1, 1)
        GameTooltip:AddLine(L["OPEN_SETTINGS"], nil, nil, nil, true)
        if InCombatLockdown() then
            GameTooltip:AddLine("|cFFFF0000" .. L["COMBAT_WARNING"] .. "|r", nil, nil, nil, true)
        end
        GameTooltip:Show()
    end
)

settingsOpenButton:SetScript(
    "OnLeave",
    function(self)
        self.settingsButtonHoverOverlay:Hide()
        self.settingsButtonPressedOverlay:Hide()
        self.settingsOpenButtonTexture:Show()
        GameTooltip:Hide()
    end
)
settingsOpenButton:SetScript(
    "OnMouseDown",
    function(self)
        self.settingsButtonPressedOverlay:Show()
        self.settingsOpenButtonTexture:Hide()
    end
)

settingsOpenButton:SetScript(
    "OnMouseUp",
    function(self)
        self.settingsButtonPressedOverlay:Hide()
        self.settingsOpenButtonTexture:Show()
    end
)

settingsOpenButton:SetScript(
    "OnClick",
    function(self)
        if InCombatLockdown() then
            print("|cFFFF0000Settings cannot be opened during combat!|r")
            return
        end
        PlaySound(SOUNDKIT.IG_CHARACTER_INFO_OPEN)
        if Settings:IsShown() then
            Settings:Hide()
        else
            Settings:Show()
        end
    end
)

-- Disable the button during combat
local function UpdateButtonStatus()
    if InCombatLockdown() then
        settingsOpenButton:Disable()
    else
        settingsOpenButton:Enable()
    end
end

settingsOpenButton:RegisterEvent("PLAYER_REGEN_ENABLED")
settingsOpenButton:RegisterEvent("PLAYER_REGEN_DISABLED")

settingsOpenButton:SetScript("OnEvent", UpdateButtonStatus)
UpdateButtonStatus()

--------------

function ToggleSettingsPanel()
    if InCombatLockdown() then
        print("|cFFFF0000Settings cannot be opened during combat!|r")
        return
    end

    if Settings:IsShown() then
        Settings:Hide()
    else
        Settings:Show()
    end
end

-- MARK: Slash Command '/dp'
SLASH_DPTOGGLE1 = "/dp"
SlashCmdList["DPTOGGLE"] = function()
    ToggleSettingsPanel()
end

local discordURL = "https://discord.gg/5AtcdZ9t7Q"
local curseforgeURL = "https://www.curseforge.com/wow/addons/dungeonports"
local wagoURL = "https://addons.wago.io/addons/dungeonports"

local CopyFrame

local function ShowPopup(linkURL, linkName)
    if CopyFrame then
        CopyFrame:Hide()
    end

    if Settings and Settings:IsShown() then
        Settings:Hide()
    end

    -- Create new frame
    CopyFrame = CreateFrame("Frame", "CopyFrame", UIParent, "BackdropTemplate")
    CopyFrame:SetSize(350, 80)
    CopyFrame:SetBackdrop({bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background"})
    CopyFrame:SetPoint("CENTER")
    CopyFrame:EnableMouse(true)
    CopyFrame:SetMovable(true)
    CopyFrame:RegisterForDrag("LeftButton")
    CopyFrame:SetScript(
        "OnDragStart",
        function(self)
            self:StartMoving()
        end
    )
    CopyFrame:SetScript(
        "OnDragStop",
        function(self)
            self:StopMovingOrSizing()
        end
    )
    CopyFrame:EnableKeyboard(true)
    CopyFrame:SetClampedToScreen(true)
    CopyFrame:SetScript(
        "OnKeyDown",
        function(self, key)
            if key == "ESCAPE" then
                self:Hide()
            else
                self:SetPropagateKeyboardInput(true)
            end
        end
    )

    local poptitle = CopyFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    poptitle:SetPoint("TOP", CopyFrame, "TOP", 0, -10)
    poptitle:SetFont(UserFont, 12, flags)
    poptitle:SetTextColor(0.2, 0.8, 0.9)
    poptitle:SetText(linkName)

    local editBox = CreateFrame("EditBox", nil, CopyFrame, "InputBoxTemplate")
    editBox:SetSize(310, 20)
    editBox:SetPoint("TOP", CopyFrame, "TOP", 0, -40)
    editBox:SetAutoFocus(false)
    editBox:SetText(linkURL)
    editBox:HighlightText()

    editBox:SetScript(
        "OnEscapePressed",
        function()
            CopyFrame:Hide()
        end
    )
    editBox:SetScript(
        "OnEnterPressed",
        function()
            editBox:ClearFocus()
        end
    )
    editBox:SetScript(
        "OnEditFocusGained",
        function(self)
            self:HighlightText()
        end
    )

    -- MARK: CopyFrame Exit Button
    local copyframeexitbutton = CreateFrame("Button", "SettingsOpenButton", CopyFrame)
    copyframeexitbutton:SetSize(14, 14)
    copyframeexitbutton:SetPoint("TOPRIGHT", CopyFrame, "TOPRIGHT", -5, -5)
    copyframeexitbutton:SetFrameStrata("DIALOG")

    local copyframeexit = copyframeexitbutton:CreateTexture(nil, "BACKGROUND")
    copyframeexit:SetAllPoints(copyframeexitbutton)
    copyframeexit:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_close.blp")

    local copyframeexithighlight = copyframeexitbutton:CreateTexture(nil, "HIGHLIGHT")
    copyframeexithighlight:SetAllPoints(copyframeexitbutton)
    copyframeexithighlight:SetTexture("Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_default\\button_close_highlight.blp")
    copyframeexithighlight:Hide()

    copyframeexitbutton.copyframeexithighlight = copyframeexithighlight
    copyframeexitbutton.copyframeexit = copyframeexit

    copyframeexitbutton:SetScript(
        "OnEnter",
        function(self)
            self.copyframeexithighlight:Show()
            self.copyframeexit:Hide()
        end
    )

    copyframeexitbutton:SetScript(
        "OnLeave",
        function(self)
            self.copyframeexithighlight:Hide()
            self.copyframeexit:Show()
        end
    )

    copyframeexitbutton:SetScript(
        "OnClick",
        function()
            PlaySound(SOUNDKIT.IG_CHARACTER_INFO_CLOSE)
            CopyFrame:Hide()
        end
    )

    CopyFrame:Show()
end

-- Setup Button
local function CreateButton(name, texturePath, highlightTexturePath, linkURL, x, y)
    local button = CreateFrame("Button", name, Settings)
    button:SetSize(24, 24)
    button:SetPoint("BOTTOMRIGHT", Settings, "BOTTOMRIGHT", x, y)
    button:SetFrameStrata("DIALOG")

    local buttonIcon = button:CreateTexture(nil, "BACKGROUND")
    buttonIcon:SetAllPoints(button)
    buttonIcon:SetTexture(texturePath)

    local buttonIconHighlight = button:CreateTexture(nil, "HIGHLIGHT")
    buttonIconHighlight:SetAllPoints(button)
    buttonIconHighlight:SetTexture(highlightTexturePath)
    buttonIconHighlight:Hide()

    button:SetScript(
        "OnEnter",
        function(self)
            buttonIconHighlight:Show()
            buttonIcon:Hide()
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:SetText(name, 1, 1, 1)
            GameTooltip:Show()
        end
    )

    button:SetScript(
        "OnLeave",
        function(self)
            buttonIconHighlight:Hide()
            buttonIcon:Show()
            GameTooltip:Hide()
        end
    )

    button:SetScript(
        "OnClick",
        function()
            ShowPopup(linkURL, name)
        end
    )

    return button
end

-- Create Buttons
local DiscordButton =
    CreateButton(
    "Discord",
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_external\\button_discord.blp",
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_external\\button_discord_highlight.blp",
    discordURL,
    -4,
    4
)
local CurseForgeButton =
    CreateButton(
    "CurseForge",
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_external\\button_curseforge.blp",
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_external\\button_curseforge_highlight.blp",
    curseforgeURL,
    -30,
    4
)
local WagoButton =
    CreateButton(
    "Wago",
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_external\\button_wago.blp",
    "Interface\\AddOns\\MDungeonTeleports\\media\\ui\\ui_external\\button_wago_highlight.blp",
    wagoURL,
    -56,
    4
)

-- MARK: End of Settings.

--//////////////////////////////////////////////////////////////////////--

-- MARK: AddOn Load Event
local function OnEvent(self, event, arg1)
    if event == "ADDON_LOADED" and arg1 == "MDungeonTeleports" then
        selectedFramePackValue = MDungeonTeleports.selectedFramePack or FramePackCategories[1].items[1].value
        local VarVersionScale = 1
        if MDungeonTeleports.VarVersionScale == nil or MDungeonTeleports.VarVersionScale < VarVersionScale then
            MDungeonTeleports.VarVersionScale = VarVersionScale
            MDungeonTeleports.frameScale = 1
        end
        local savedScale = MDungeonTeleports.frameScale or 1.0
        UIDropDownMenu_SetSelectedValue(FramePackDropdown, selectedFramePackValue)
        uiScaleSlider:SetValue(savedScale)
        UpdateFrameScale(savedScale)
        UpdateUI()
        UpdateDropdownText(selectedFramePackValue)
    end
end

local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:SetScript("OnEvent", OnEvent)

-- MARK: Login Message
local loginmessage = CreateFrame("Frame")
loginmessage:RegisterEvent("PLAYER_LOGIN")
loginmessage:SetScript(
    "OnEvent",
    function(self, event)
        if event == "PLAYER_LOGIN" then
            if not MDungeonTeleports then
                MDungeonTeleports = {}
            end
            local today = GetCurrentDate()
            if MDungeonTeleports.lastLoginMessageDate ~= today and MDungeonTeleports.LoginMessageToggle == true then
                DEFAULT_CHAT_FRAME:AddMessage(
                    L["LOGIN_MESSAGE_CHAT"],
                    0.8,
                    0.6,
                    1
                )
                MDungeonTeleports.lastLoginMessageDate = today
            end
        end
    end
)
