-- ***********************************************************************
-- **** WoW Addon: DelveInfo                                             *
-- ***********************************************************************
-- Version: 12.0.5
-- Created by: [Matthew Rush]
-- Creation Date: [10/01/2024]
-- Last Updated: [05/09/2026]
-- 
-- Description:
-- This World of Warcraft addon provides an interface to display detailed
-- information about the player's characters, including currencies and items.
-- It allows you to dynamically generate buttons for each character (level 90+)
-- and display relevant data such as average item level, realm, and in-game currencies.
--
-- Latest Changes:
-- - Added functionality to display character info, including item and currency info.
-- - Added dynamic resizing of the frame based on the number of characters.
-- - Improved handling for characters below level 90 (excluded from the display).
--
-- Useful URLs and Documentation:
-- 1. WoW API Reference: https://wowpedia.fandom.com/wiki/World_of_Warcraft_API
--    - Provides a detailed overview of WoW API functions, methods, and useful utilities.
-- 2. WoW Font Documentation: https://wowpedia.fandom.com/wiki/API_FontString_SetFont
--    - Explains how to use fonts and font-related functions in WoW.
-- 3. WoW Slash Command Documentation: https://wowpedia.fandom.com/wiki/Creating_a_slash_command
--    - Guide on how to create and handle slash commands for your addon.
--
-- WoW Font, Font Size, Font Color, and Button Color:
-- - Fonts in WoW:
--   WoW provides default fonts that can be accessed via the `SetFont` method, and custom fonts can be used
--   by specifying a path to a `.ttf` font file. WoW supports standard font settings such as font size and font flags (e.g., "OUTLINE").
--
-- - Font Sizes in WoW:
--   The font size in WoW is controlled via the `SetFont()` function, which takes three parameters: the font path, the font size, 
--   and an optional font flag (such as "OUTLINE"). Example: `fontString:SetFont("Fonts\\FRIZQT__.TTF", 14, "OUTLINE")`
--
-- - Font Color in WoW:
--   WoW's `SetTextColor()` function allows you to set text color using an RGB scale from 0 to 1. 
--   This is different from HTML's 0-255 RGB scale. To convert HTML color codes to WoW's RGB, divide each component by 255.
--
--   For example, HTML RGB (255, 255, 0) for yellow:
--   - HTML: rgb(255, 255, 0)
--   - WoW: 255 / 255 = 1, 255 / 255 = 1, 0 / 255 = 0 → WoW RGB: (1, 1, 0)
--   Example: `fontString:SetTextColor(1, 1, 0)` sets the text color to yellow.
--
-- - Button Color in WoW:
--   WoW allows you to set button colors using textures or solid colors with the `SetColorTexture()` method.
--   LUA Example: 
--   local normalTexture = button:CreateTexture(nil, "BACKGROUND")
--   normalTexture:SetAllPoints(button)
--   normalTexture:SetColorTexture(0.2, 0.6, 0.8, 1)  -- Light blue color (R:0.2, G:0.6, B:0.8, Alpha:1)
--   button:SetNormalTexture(normalTexture)
--   ```
--   Similar to text color, WoW button colors are set using RGB values normalized to the 0-1 scale.
--
-- Conversion from HTML RGB to WoW API RGB:
-- - HTML uses RGB values ranging from 0 to 255 (e.g., rgb(255, 0, 0) for red).
-- - WoW's API normalizes these values between 0 and 1, so you need to divide the HTML values by 255 to convert them to WoW's format.
-- - Example: HTML red (rgb(255, 0, 0)) converts to WoW's red (1, 0, 0).
--   Conversion formula: WoW_R = HTML_R / 255, WoW_G = HTML_G / 255, WoW_B = HTML_B / 255
--
-- Example Conversion:
-- - HTML: rgb(255, 165, 0) (orange)
-- - WoW: 255/255 = 1, 165/255 ≈ 0.647, 0/255 = 0 → WoW RGB: (1, 0.647, 0)
--   Use: `fontString:SetTextColor(1, 0.647, 0)` to set orange text color in WoW.
--
-- Summary of available font flags:
-- - "OUTLINE": Thin outline around the text.
-- - "THICKOUTLINE": Thicker outline around the text.
-- - "MONOCHROME": Pixelated, no anti-aliasing.
-- - "MONOCHROMEOUTLINE": Pixelated with a thin outline.
-- - "THICKMONOCHROMEOUTLINE": Pixelated with a thick outline.
-- - Custom Fonts can be used:
-- - frame.TitleText:SetFont("Interface\\AddOns\\YourAddon\\Fonts\\CustomFont.ttf", 20, "OUTLINE")
-- - frame.TitleText:SetTextColor(1, 1, 0)  -- Yellow color
--
-- To enable debugging errors in wow use these console commands
-- - Example Commands:
-- -- /console scriptErrors 1 (Show Lua Errors) 
-- -- /console scriptErrors 0 (Hide Lua Errors) 
-- ***********************************************************************

-- Saved variable to store character data across sessions
CkInfoDB = CkInfoDB or {}

-- Global variable to set and show all World of Warcraft characters >= 90 (current max level is: 90)
CurrentMaxLvl = 81  -- Modify to load characters of other levels
selectedCharacterKey = nil  -- Global variable to track the selected character key

-- List of currencies to track (with ID and name)
local currencies = {
    -- Season One Items
    { id = 3383, name = "(cap: 233) Adventurer Dawncrest" },
    { id = 3341, name = "(cap: 246) Veteran Dawncrest" },
    { id = 3343, name = "(cap: 263) Champion Dawncrest" },
    { id = 3345, name = "(cap: 276) Hero Dawncrest" },
    { id = 3347, name = "(cap: 289) Mythic Dawncrest" },
    
    { header = true, name = "----- Season Items -----" },
    { id = 3310, name = "S1 - Coffer Key Shards" },
    { id = 3028, name = "S1 - Coffer Keys" },
    { id = 2803, name = "S1 - Undercoins" },

    -- Season Two Items
    -- Season Three Items
}    

-- Create the main frame for the addon interface
local frame = CreateFrame("Frame", "MyCharacterInfoFrame", UIParent, "BasicFrameTemplateWithInset")
frame:SetSize(450, 550)  -- Set character name frame size e.g., (450, 550)
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)  -- Center the frame
frame:SetMovable(true)
frame:EnableMouse(true)
frame:RegisterForDrag("LeftButton", "RightButton") -- Allow dragging with left or right mouse buttons
frame:SetScript("OnDragStart", frame.StartMoving)
frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
frame:Hide()  -- Initially hide the frame
-- Set the frame strata to "HIGH" to make it appear on top
frame:SetFrameStrata("HIGH")  -- Options: "BACKGROUND", "LOW", "MEDIUM", "HIGH", "DIALOG", "FULLSCREEN", etc.
-- Set the frame level to a higher value to make sure it stays on top within the same strata
frame:SetFrameLevel(200)  -- You can increase this value if needed

-- Variable to store the original scale of WeeklyRewardsFrame
local originalScale

-- ***********************************************************************
-- Function to handle closing both frames with Escape
-- ***********************************************************************
local function CloseFramesWithEscape()
    -- Check if the WeeklyRewardsFrame exists before trying to interact with it
    if WeeklyRewardsFrame then
        -- Check if the original scale is stored, and reset the frame's scale
        if originalScale then
            WeeklyRewardsFrame:SetScale(originalScale)
        end
        
        -- Hide the WeeklyRewardsFrame
        WeeklyRewardsFrame:Hide()

        -- Disable moving and dragging
        WeeklyRewardsFrame:SetMovable(false)
        WeeklyRewardsFrame:EnableMouse(false)
        WeeklyRewardsFrame:RegisterForDrag()  -- Unregister dragging
        WeeklyRewardsFrame:SetScript("OnDragStart", nil)
        WeeklyRewardsFrame:SetScript("OnDragStop", nil)
    end
    
    -- Hide the addon frame
    frame:Hide()
end

-- ***********************************************************************
-- Create a "Send" button to send character info in chat
-- ***********************************************************************
local sendButton = CreateFrame("Button", "SendCharacterInfoButton", frame, "UIPanelButtonTemplate")
sendButton:SetSize(100, 30)  -- Set button size
sendButton:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 10, 10)  -- Set position

-- Set the button text to "Send"
sendButton:SetText("Send")

-- Create checkboxes for chat options
local whisperCheckbox = CreateFrame("CheckButton", "WhisperCheckbox", frame, "UICheckButtonTemplate")
whisperCheckbox:SetPoint("BOTTOMLEFT", sendButton, "BOTTOMLEFT", 0, 30)
whisperCheckbox.text:SetText("Whisper %target")

local guildCheckbox = CreateFrame("CheckButton", "GuildCheckbox", frame, "UICheckButtonTemplate")
guildCheckbox:SetPoint("BOTTOMLEFT", whisperCheckbox, "BOTTOMLEFT", 0, 30)
guildCheckbox.text:SetText("Guild")

local partyCheckbox = CreateFrame("CheckButton", "PartyCheckbox", frame, "UICheckButtonTemplate")
partyCheckbox:SetPoint("BOTTOMLEFT", sendButton, "BOTTOMLEFT", 125, 30)
partyCheckbox.text:SetText("Party")

local sayCheckbox = CreateFrame("CheckButton", "SayCheckbox", frame, "UICheckButtonTemplate")
sayCheckbox:SetPoint("BOTTOMLEFT", partyCheckbox, "BOTTOMLEFT", 0, 30)
sayCheckbox.text:SetText("Say")

-- ***********************************************************************
-- Function to ensure only one checkbox is selected at a time
-- ***********************************************************************
local function UpdateCheckboxes(selectedCheckbox)
    if selectedCheckbox == whisperCheckbox then
        guildCheckbox:SetChecked(false)
        partyCheckbox:SetChecked(false)
        sayCheckbox:SetChecked(false)
    elseif selectedCheckbox == guildCheckbox then
        whisperCheckbox:SetChecked(false)
        partyCheckbox:SetChecked(false)
        sayCheckbox:SetChecked(false)
    elseif selectedCheckbox == partyCheckbox then
        whisperCheckbox:SetChecked(false)
        guildCheckbox:SetChecked(false)
        sayCheckbox:SetChecked(false)
    elseif selectedCheckbox == sayCheckbox then
        whisperCheckbox:SetChecked(false)
        guildCheckbox:SetChecked(false)
        partyCheckbox:SetChecked(false)
    end
end

-- ***********************************************************************
-- Add the OnClick function to each checkbox
-- ***********************************************************************
whisperCheckbox:SetScript("OnClick", function() UpdateCheckboxes(whisperCheckbox) end)
guildCheckbox:SetScript("OnClick", function() UpdateCheckboxes(guildCheckbox) end)
partyCheckbox:SetScript("OnClick", function() UpdateCheckboxes(partyCheckbox) end)
sayCheckbox:SetScript("OnClick", function() UpdateCheckboxes(sayCheckbox) end)

-- ***********************************************************************
-- Function to format the character info for chat (Name, ilvl, and Items)
-- ***********************************************************************
local function FormatCharacterInfo(characterKey)
    local charData = CkInfoDB[characterKey]
    if not charData then return "" end

    -- Ensure valid values for name and itemLevel, with default fallbacks
    local name = charData.name or "Unknown"
    local itemLevel = charData.itemLevel or 0  -- Default to 0 if itemLevel is nil

    -- Base message | Format the character info string with name and item level
    local infoText = string.format("Character: %s || ilvl: %.2f", name, itemLevel)  -- Escape the pipe

    -- Chat Message: Find the currency you want to show
    local trackedCurrencies = {
        [3310] = true, --Coffer Key Shards
        [3028] = true, --Coffer Keys
        [2803] = true --Undercoins
    }
    -- Chat Message: The currency you want to show
    for _, currency in ipairs(charData.currencies) do
        if not currency.header and trackedCurrencies[currency.id] then
            infoText = infoText .. string.format(" || %s: %d", currency.name, currency.amount)
        end
    end

    return infoText

end

-- ***********************************************************************
-- Send the character info to the appropriate chat channel
-- ***********************************************************************
sendButton:SetScript("OnClick", function()
    -- Ensure that character data is displayed
    if not selectedCharacterKey then
        print("No character selected.")
        return
    end

    local infoText = FormatCharacterInfo(selectedCharacterKey)  -- Get the formatted character info

    -- Send message to a whisper target
    if whisperCheckbox:GetChecked() then
        local targetName = UnitName("target")
        if targetName then
            SendChatMessage(infoText, "WHISPER", nil, targetName)  -- Whisper to the target
        else
            print("No target selected for whisper.")
        end
    end
    
    -- Send message to guild
    if guildCheckbox:GetChecked() then
        SendChatMessage(infoText, "GUILD")  -- Send to guild chat
    end
    
    -- Send message to party
    if partyCheckbox:GetChecked() then
        SendChatMessage(infoText, "PARTY")  -- Send to party chat
    end
    
    -- Send message in /say
    if sayCheckbox:GetChecked() then
        SendChatMessage(infoText, "SAY")  -- Send to say
    end
end)

-- ***********************************************************************
-- Function to reset the WeeklyRewardsFrame when the addon is closed
-- ***********************************************************************
local function ResetWeeklyRewardsFrame()
    if WeeklyRewardsFrame and WeeklyRewardsFrame:IsShown() then
        -- Reset the scale to the original value
        if originalScale then
            WeeklyRewardsFrame:SetScale(originalScale)
        end

        -- Disable moving and dragging
        WeeklyRewardsFrame:SetMovable(false)
        WeeklyRewardsFrame:EnableMouse(false)
        WeeklyRewardsFrame:RegisterForDrag()  -- Unregister dragging
        WeeklyRewardsFrame:SetScript("OnDragStart", nil)
        WeeklyRewardsFrame:SetScript("OnDragStop", nil)
    end
end

-- ***********************************************************************
-- Register the close functionality on pressing Escape
-- ***********************************************************************
frame:SetScript("OnHide", CloseFramesWithEscape)
tinsert(UISpecialFrames, "MyCharacterInfoFrame")

--Set & customize the frame title
frame.TitleText:SetText("Character Info")
frame.TitleText:SetFont("Fonts\\FRIZQT__.TTF", 14) -- Set the font name, size, and outline (optional)
frame.TitleText:SetTextColor(1, 0.82, 0) -- Set the font color (e.g., Goldish color)


-- Add a custom background texture (optional)
-- =================================================================================
frame:SetClipsChildren(true) -- Keep background image from drawing outside the main frame.

local bg = frame:CreateTexture(nil, "BORDER")
bg:SetTexture("Interface\\AddOns\\DelveInfo\\Images\\Midnight-S1-Delves.png")
bg:SetAlpha(0.5)
bg:SetAllPoints(frame)

-- Cropt your image aspect ratio 
local function FitBg()
    bg:SetTexCoord(0, 1, 0, 1)
    local w, h = frame:GetSize()
    -- Get the actual texture's pixel dimensions
    local texW, texH = bg:GetSize()
    -- Use the texture's original size for scaling
    local scale = math.min(w / texW, h / texH)
    bg:SetSize(texW * scale, texH * scale)
    bg:ClearAllPoints()
    --bg:SetPoint("CENTER", frame, "CENTER") -- Anchor the texture's center to the frame's center (keeps it centered both horizontally and vertically).
    bg:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, 0) -- Pin the texture's top-left corner to the frame's top-left corner with no offset.
    bg:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 0) -- Pin the texture's bottom-right corner to the frame's bottom-right corner with no offset.
end

FitBg()
frame:HookScript("OnSizeChanged", FitBg)
-- =================================================================================

-- Separator image placed below the buttons
local separator = frame:CreateTexture(nil, "ARTWORK")
separator:SetTexture("Interface\\AddOns\\DelveInfo\\Images\\Separator.png")  -- Separator image path
separator:SetSize(400, 10)  -- Adjust separator size

-- Display area for character information (with custom font and alignment)
local charInfoText = frame:CreateFontString(nil, "OVERLAY")
charInfoText:SetFontObject("GameFontNormal")
charInfoText:SetFont("Fonts\\FRIZQT__.TTF", 14)  -- Set default font size
charInfoText:SetJustifyH("LEFT")  -- Align text to the left

-- ***********************************************************************
-- Function to display guilded stash info then print below
-- Line 374 & 
-- ***********************************************************************
local function GetGildedStashProgress()
    local info = C_UIWidgetManager.GetSpellDisplayVisualizationInfo(7591)

    if info and info.spellInfo and info.spellInfo.tooltip and info.spellInfo.tooltip ~= "" then
        local current, max = info.spellInfo.tooltip:match("(%d+)%s*/%s*(%d+)")
        if current and max then
            return tonumber(current), tonumber(max)
        end
    end

    return nil, nil
end

-- ***********************************************************************
-- Function to display character info, currencies, and items
-- ***********************************************************************
local function ShowCharacterInfo(characterKey)
    local charData = CkInfoDB[characterKey]
    
    -- check/variable to check if Delver's Bounty Map was received
    local isLooted = charData.isLooted
    
    -- Gilded Stash check/variables to check how many T11 delves were run and guilded stash looted
    local current = charData.gildedCurrent
    local max = charData.gildedMax

    if isLooted == nil then
        isLooted = false
    end

    if not current or not max then
        current, max = "?", 4
    end
    
    -- check/variable to check if Delver's Bounty Map was received
    --local isLooted = C_QuestLog.IsQuestFlaggedCompleted(86371)

    -- Gilded Stash check/variables to check how many T11 delves were run and guilded stash looted
    --local current, max = GetGildedStashProgress()
    --if not current or not max then
        --current, max = "?", 4
    --end

    if not charData then return end  -- Exit if no data

    -- Update frame title with character name
    frame.TitleText:SetText(string.format("Character Details: %s", charData.name))

    -- Format and display character info
    local infoText = string.format("|cFFFFD200Character:\n|cFFC0C0C0Name:|r %s\n|cFFC0C0C0Realm:|r %s\n|cFFC0C0C0Avg ilvl:|r %.2f\n\n", 
                                   charData.name, charData.realm, charData.itemLevel)
    
      -- Append currency information
    infoText = infoText .. "|cFFFFD200Currencies:|r\n"
    for _, currency in ipairs(charData.currencies) do
        if currency.header then
            infoText = infoText .. string.format("\n|cFFFFD700%s|r\n", currency.name)
        else
            infoText = infoText .. string.format("|cFFC0C0C0%s:|r %d\n", currency.name, currency.amount)
        end
    end
    
    -- Delvers Bounty Map Info
    infoText = infoText .. string.format("\n----- Delver’s Bounty -----")
    infoText = infoText .. string.format("\n|cFFC0C0C0Map Used:|r ")
    infoText = infoText .. string.format(isLooted and "Yes" or "No")

    -- Gilded Stash Info
    infoText = infoText .. string.format("\n\n----- T11 Gilded Stash  -----")
    infoText = infoText .. string.format("\n|cFFC0C0C0Completed:|r %d/%d\n", current, max)
    --infoText = infoText .. string.format("TESTING")

    -- Set the formatted info in the text area
    charInfoText:SetText(infoText)
end

-- ***********************************************************************
-- Function to create buttons for each character in saved data
-- ***********************************************************************
local function CreateCharacterButton(characterKey, index, totalButtons)
    local charData = CkInfoDB[characterKey]
    if not charData then return end  -- Exit if no data

    local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    button:SetSize(100, 30)
    button:SetText(charData.name)  -- Display character's name on the button

    -- Calculate row and column based on index (3 buttons per row)
    local row = math.floor((index - 1) / 3)
    local col = (index - 1) % 3

    -- Calculate total button width and center horizontally
    local totalButtonWidth = 3 * 100 + 2 * 20
    local frameWidth = frame:GetWidth()
    local xOffset = (frameWidth - totalButtonWidth) / 2

    -- Set button position
    button:SetPoint("TOPLEFT", frame, "TOPLEFT", xOffset + col * (100 + 20), -40 - row * 40)

    -- Click event to show character info when clicked
    button:SetScript("OnClick", function()
        selectedCharacterKey = characterKey  -- Store the selected character key
        ShowCharacterInfo(characterKey)  -- Display character info
    end)
end

-- ***********************************************************************
-- Function to dynamically resize the frame based on the number of buttons
-- ***********************************************************************
local function ResizeFrameBasedOnContent(numCharacters)
    local rows = math.ceil(numCharacters / 3)  -- Assume 3 buttons per row
    local buttonHeight = 30  -- Height of each button
    local SendbuttonHeight = 30  -- Height of each button
    local padding = 40  -- Additional padding for separators and titles
    local separatorHeight = 10  -- Height of the separator

    -- Estimate height for character info, currencies, and items
    local infoHeight = 100  -- Character info section height
    local currencyHeight = #currencies * 20  -- Each currency takes 20 pixels

    -- Total dynamic height based on content
    local extraSectionHeight = 2 * 20  -- 4 extra lines so delver's bounty and gilded stash are not cramped.
    local dynamicHeight = (rows * buttonHeight) + SendbuttonHeight + padding + separatorHeight + infoHeight + currencyHeight + extraSectionHeight + buttonHeight + 100
        --print("Dynamic Height: ", dynamicHeight)
    local dynamicWidth = 450  -- Adjust width if needed

    -- Set the frame size dynamically
    frame:SetSize(dynamicWidth, dynamicHeight)
end

-- ***********************************************************************
-- Function to save the current character's data into saved variables
-- ***********************************************************************
local function SaveCharacterData()
    local name, realm = UnitName("player")
    realm = realm or GetRealmName()

    local itemLevel = GetAverageItemLevel()
    local level = UnitLevel("player")

    if level >= CurrentMaxLvl then
        local characterKey = name .. "-" .. realm
        
         -- Live values for the currently logged-in character
        local isLooted = C_QuestLog.IsQuestFlaggedCompleted(86371)
        
        local gildedCurrent, gildedMax
        local info = C_UIWidgetManager.GetSpellDisplayVisualizationInfo(7591)
        if info and info.spellInfo and info.spellInfo.tooltip and info.spellInfo.tooltip ~= "" then
            local current, max = info.spellInfo.tooltip:match("(%d+)%s*/%s*(%d+)")
            if current and max then
                gildedCurrent = tonumber(current)
                gildedMax = tonumber(max)
            end
        end

        local characterData = {
            name = name,
            realm = realm,
            itemLevel = itemLevel,
            level = level,
            currencies = {},
            isLooted = isLooted,
            gildedCurrent = gildedCurrent,
            gildedMax = gildedMax,
        }

        -- Save character's currencies
        for _, currency in ipairs(currencies) do
            if currency.header then
                table.insert(characterData.currencies, {
                    header = true,
                    name = currency.name
                })
            else
                local info = C_CurrencyInfo.GetCurrencyInfo(currency.id)
                local amount = info and info.quantity or 0
                table.insert(characterData.currencies, {
                     id = currency.id,   -- added
                    name = currency.name,
                    amount = amount
                })
            end
        end

        CkInfoDB[characterKey] = characterData
        selectedCharacterKey = characterKey
    end
end

-- ***********************************************************************
-- Function to create a "Toggle Vault Rewards" button
-- ***********************************************************************
local function CreateVaultButton()
    local vaultButton = CreateFrame("Button", "ToggleVaultRewardsButton", frame, "UIPanelButtonTemplate")
    vaultButton:SetSize(160, 30)  -- Set button size
    vaultButton:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -10, 10)  -- Set position at the bottom-right

    -- Set the button text to "Toggle Vault Rewards"
    vaultButton:SetText("Toggle Vault Rewards")

    -- Variables to store original scale
    local originalScale

    vaultButton:SetScript("OnClick", function(self)
        -- Ensure the Blizzard WeeklyRewards addon is loaded
        if not C_AddOns.IsAddOnLoaded("Blizzard_WeeklyRewards") then
            C_AddOns.LoadAddOn("Blizzard_WeeklyRewards")
        end

        -- Toggle the visibility of the WeeklyRewardsFrame
        if WeeklyRewardsFrame:IsShown() then
            -- Hide the WeeklyRewardsFrame and reset to original scale
            if originalScale then
                WeeklyRewardsFrame:SetScale(originalScale)
            end
            WeeklyRewardsFrame:Hide()

            -- Disable moving and dragging
            WeeklyRewardsFrame:SetMovable(false)
            WeeklyRewardsFrame:EnableMouse(false)
            WeeklyRewardsFrame:RegisterForDrag()  -- Unregister dragging
            WeeklyRewardsFrame:SetScript("OnDragStart", nil)
            WeeklyRewardsFrame:SetScript("OnDragStop", nil)
        else
            -- Store the original scale only if we haven't already
            if not originalScale then
                originalScale = WeeklyRewardsFrame:GetScale()
            end

            -- Now scale the frame to 0.8 (or adjust as needed)
            WeeklyRewardsFrame:SetScale(0.7)  -- Adjust this value as needed

            WeeklyRewardsFrame:SetMovable(true)
            WeeklyRewardsFrame:EnableMouse(true)
            WeeklyRewardsFrame:RegisterForDrag("LeftButton", "RightButton")  -- Enable dragging
            WeeklyRewardsFrame:SetScript("OnDragStart", WeeklyRewardsFrame.StartMoving)
            WeeklyRewardsFrame:SetScript("OnDragStop", WeeklyRewardsFrame.StopMovingOrSizing)

            -- Center the frame on the player's screen
            WeeklyRewardsFrame:ClearAllPoints()
            --WeeklyRewardsFrame:SetPoint("CENTER", UIParent, "CENTER")
            WeeklyRewardsFrame:SetPoint("RIGHT", frame, "LEFT", -10, 0)  -- Adjust the "-10" for spacing as needed


            -- Show the frame
            WeeklyRewardsFrame:Show()
        end
    end)
end

-- ***********************************************************************
-- Hook into the addon frame movement to move the vault screen as well
-- ***********************************************************************
frame:HookScript("OnDragStop", function()
      -- Check if WeeklyRewardsFrame exists before attempting to modify it
      if WeeklyRewardsFrame then
        -- Now scale the frame to 0.8 (or adjust as needed)
        WeeklyRewardsFrame:SetScale(0.7)  -- Adjust this value as needed
        
        -- Re-anchor the WeeklyRewardsFrame to the addon frame when dragging stops
        WeeklyRewardsFrame:ClearAllPoints()
        WeeklyRewardsFrame:SetPoint("RIGHT", frame, "LEFT", -10, 0)  -- Adjust the "-10" for spacing as needed
      else
        -- Print a message or handle the case where the Great Vault hasn't been opened yet
        --print("WeeklyRewardsFrame is not available yet. Please open the Great Vault once.")
    end        
end)

-- ***********************************************************************
-- Initialize the addon: Create buttons, resize frame, and display info
-- ***********************************************************************
local function InitializeAddon()
    --print("Initializing addon...") -- Used for debugging only!

    -- Reset frame and clear previous info
    charInfoText:SetText("")
    frame.TitleText:SetText("Character Info")
    --print("Reset frame title and cleared info.") -- Used for debugging only!

    -- Get current player info and key
    local index = 1
    local name, realm = UnitName("player")
    realm = realm or GetRealmName()
    local currentCharacterKey = name .. "-" .. realm

    -- Count total number of characters
    local totalButtons = 0
    for characterKey, charData in pairs(CkInfoDB) do
        if charData.level >= CurrentMaxLvl then  -- Only count characters level 90 or higher
            totalButtons = totalButtons + 1
        end
    end

    -- Create buttons for all saved characters
    for characterKey, charData in pairs(CkInfoDB) do
        if charData.level >= CurrentMaxLvl then  -- Only create buttons for characters level 90 or higher
            --print("Creating button for character: " .. characterKey) -- Used for debugging only!
            CreateCharacterButton(characterKey, index, totalButtons)
            index = index + 1
        end
    end

    -- Resize the frame dynamically based on content
    ResizeFrameBasedOnContent(index - 1)

    -- Position the separator below the buttons
    local totalRows = math.ceil((index - 1) / 3)
    separator:SetPoint("TOPLEFT", frame, "TOPLEFT", 20, -40 - totalRows * 40)
    charInfoText:SetPoint("TOPLEFT", separator, "BOTTOMLEFT", 0, -20)
    --print("Updated separator and text positions.") -- Used for debugging only!

    -- Show current character's info by default
    if CkInfoDB[currentCharacterKey] and CkInfoDB[currentCharacterKey].level >= CurrentMaxLvl then
        ShowCharacterInfo(currentCharacterKey)
    else
        --print("No data found for current character or character is below level 90.") -- Used for debugging only!
    end

    -- Create the "Show Vault Rewards" button
    CreateVaultButton()
    --print("Addon initialization complete.") -- Used for debugging only!
end

-- ***********************************************************************
-- Event handler for when the player logs in
-- ***********************************************************************
local function OnPlayerLogin()
    SaveCharacterData()  -- Save the current character's data when they log in
end

-- Register event to track when the player logs in
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("PLAYER_LOGIN")
eventFrame:SetScript("OnEvent", OnPlayerLogin)

-- ***********************************************************************
-- Slash command to toggle frame visibility and initialize addon
-- ***********************************************************************
SLASH_CKINFO1 = "/ckinfo"
SLASH_CKINFO2 = "/di"
SLASH_CKINFO3 = "/delveinfo"

SlashCmdList["CKINFO"] = function(msg)
     msg = msg:lower() -- Support case insensative
    
    -- Default toggle behavior
     if frame:IsShown() then
        frame:Hide()
    else
        -- Ensure the current character data is refreshed
        SaveCharacterData()  -- Refresh the character's data (currencies, items, etc.)
        --print("Attempting to initialize the addon.") -- Used for debugging only!
        -- Call function once and store value

        InitializeAddon()  -- Create buttons and show the saved data
        frame:Show()
        --print("Addon loaded, frame showing.") -- Used for debugging only!
    end
end

-- Print message to confirm addon is loaded
--print("Character Info addon with Enhanced Currency and Item Storage loaded. Use /ckinfo to toggle the frame.") -- Used for debugging only!