-- ***********************************************************************
-- **** WoW Addon: Character Info & Currency Tracker *********************
-- **** Author: Matthew ("Rush") *****************************************
-- **** Purpose: Display character info for all characters on the account,
-- **** with the logged-in character shown at the top, and only 
-- **** characters at level 80 or above are included, with modern layout.
-- ***********************************************************************

-- Create saved variables to store character data across sessions
CkInfoDB = CkInfoDB or {}

-- Create a basic frame to display character info with scrollable content
local frame = CreateFrame("Frame", "MyCharacterInfoFrame", UIParent, "BasicFrameTemplateWithInset")
frame:SetSize(450, 550)  -- Increased Width, Height for more content
frame:SetPoint("CENTER")  -- Position in the center of the screen
frame:SetMovable(true)  -- Allow the frame to be movable
frame:EnableMouse(true)  -- Allow mouse interaction
frame:RegisterForDrag("LeftButton", "RightButton")  -- Enable dragging
frame:SetScript("OnDragStart", frame.StartMoving)
frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
frame:Hide()  -- Start hidden by default

-- Register the frame to be closed with the Escape key
tinsert(UISpecialFrames, "MyCharacterInfoFrame")

-- Add your custom background image
local background = frame:CreateTexture(nil, "BORDER")
background:SetAllPoints()
background:SetTexture("Interface\\AddOns\\CofferKeys\\Images\\TWW1-S1-Delves.png")  -- Path to your custom image
background:SetAlpha(0.2)  -- Set transparency for a modern, subtle effect

-- Add a border around the frame for a polished look
local border = frame:CreateTexture(nil, "OVERLAY")
border:SetPoint("TOPLEFT", -10, 10)
border:SetPoint("BOTTOMRIGHT", 10, 30)

-- Add a scroll frame to allow scrolling if text overflows
local scrollFrame = CreateFrame("ScrollFrame", nil, frame, "UIPanelScrollFrameTemplate")
scrollFrame:SetPoint("TOPLEFT", 15, -40)
scrollFrame:SetPoint("BOTTOMRIGHT", -40, 20)

-- Create the scrollable content frame
local content = CreateFrame("Frame", nil, scrollFrame)
content:SetSize(400, 1)  -- Set width to match the scroll area, height will adjust dynamically
scrollFrame:SetScrollChild(content)

-- Add a title to the frame
frame.title = frame:CreateFontString(nil, "OVERLAY")
frame.title:SetFontObject("GameFontHighlightLarge")
frame.title:SetPoint("TOP", frame, "TOP", 0, -5)
frame.title:SetText("Character Info")

-- FontString to display character info (inside the scrollable content frame)
content.charInfo = content:CreateFontString(nil, "OVERLAY")
content.charInfo:SetFontObject("GameFontNormal")
content.charInfo:SetPoint("TOPLEFT", content, "TOPLEFT", 0, 0)
content.charInfo:SetWidth(380)  -- Set width to ensure text wraps within the scroll frame
content.charInfo:SetJustifyH("LEFT")

-- Currencies to fetch with ID and name
local currencies = {
    { id = 3028, name = "Coffer Keys" },
    { id = 2916, name = "Runed Harbinger Crest" },
    { id = 2914, name = "Weathered Harbinger Crest" },
    { id = 2917, name = "Gilded Harbinger Crest" },
    { id = 2915, name = "Carved Harbinger Crest" },
    { id = 2803, name = "Undercoin" },
    { id = 3008, name = "Valorstones" }
}

-- Function to clean up CkInfoDB by removing characters below level 80
local function CleanupCharacterData()
    for charKey, charData in pairs(CkInfoDB) do
        if charData.level and charData.level < 80 then
            CkInfoDB[charKey] = nil  -- Remove characters below level 80
        end
    end
end

-- Function to update the character info and store in saved variables
local function UpdateCharacterInfo()
    
-------------------------------------------------------------------------------------------------
    -- Destroy the previous content frame and recreate it to avoid stacking issues
    if content then
        content:Hide()
        content:SetParent(nil)
    end

    -- Create a new scrollable content frame
    content = CreateFrame("Frame", nil, scrollFrame)
    content:SetSize(400, 1)  -- Set width to match the scroll area, height will adjust dynamically
    scrollFrame:SetScrollChild(content)
-------------------------------------------------------------------------------------------------    

    local name, realm = UnitName("player")
    local itemLevel, _ = GetAverageItemLevel()
    local level = UnitLevel("player")
    
    realm = realm or GetRealmName()

    -- Only add characters that are level 80 or above
    if level >= 80 then
        -- Fetch currencies for the character
        local characterKey = name .. "-" .. realm
        local characterData = {
            name = name,
            realm = realm,
            itemLevel = itemLevel,
            level = level,  -- Store level for cleanup check
            currencies = {}
        }

        for _, currency in ipairs(currencies) do
            local info = C_CurrencyInfo.GetCurrencyInfo(currency.id)
            local amount = info and info.quantity or 0
            table.insert(characterData.currencies, { name = currency.name, amount = amount })
        end

        -- Store the character data in the saved variables
        CkInfoDB[characterKey] = characterData  -- Save by unique key (name-realm)
    end

    -- Cleanup data: remove any characters below level 80
    CleanupCharacterData()

    -- Initialize starting position (Y offset)
    local currentYOffset = -10  -- Start at a slight offset from the top

    -- Function to add separator image between characters
    local function AddSeparator(contentFrame, currentYOffset)
        local separator = contentFrame:CreateTexture(nil, "ARTWORK")
        separator:SetTexture("Interface\\AddOns\\CofferKeys\\Images\\separator.png")  -- Path to your separator image
        separator:SetSize(380, 10)  -- Adjust the size of the separator
        separator:SetPoint("TOPLEFT", contentFrame, "TOPLEFT", 0, currentYOffset)  -- Set Y offset
        return currentYOffset - 20  -- Adjust Y offset after adding the separator (for spacing)
    end

    -- Function to add character info text
    local function AddCharacterInfo(contentFrame, charInfo, currentYOffset)
        local charInfoText = contentFrame:CreateFontString(nil, "OVERLAY")
        charInfoText:SetFontObject("GameFontNormal")
        charInfoText:SetText(charInfo)
        charInfoText:SetWidth(380)  -- Ensure the text fits within the scrollable content
        charInfoText:SetJustifyH("LEFT")  -- Set text alignment to left
        charInfoText:SetPoint("TOPLEFT", contentFrame, "TOPLEFT", 0, currentYOffset)
        return currentYOffset - charInfoText:GetStringHeight() - 10  -- Adjust Y offset after adding text
    end

    -- Add current character info first (if level >= 80)
    if level >= 80 then
        local currentCharInfo = string.format("|cFFFFFFFFName:|r %s\n|cFFFFFFFFRealm:|r %s\n|cFFFFFFFFAvg ilvl:|r %.2f\n", name, realm, itemLevel)
        currentCharInfo = currentCharInfo .. "\n|cffffff00Currencies:|r\n"
        for _, currency in ipairs(CkInfoDB[name .. "-" .. realm].currencies) do
            currentCharInfo = currentCharInfo .. string.format("|cFFFFFFFF%s:|r %d\n", currency.name, currency.amount)
        end
        
        -- Add the current character info text and adjust the Y position
        currentYOffset = AddCharacterInfo(content, currentCharInfo, currentYOffset)
        
        -- Add the separator image and adjust the Y position
        currentYOffset = AddSeparator(content, currentYOffset)
    end

    -- Add the rest of the characters to the list
    for charKey, charData in pairs(CkInfoDB) do
        if charKey ~= (name .. "-" .. realm) then  -- Skip the logged-in character
            -- Properly format the character info with string concatenation and string.format
            local charInfo = "|cFFFFFFFFName:|r " .. charData.name .. "\n" ..
                             "|cFFFFFFFFRealm:|r " .. charData.realm .. "\n" ..
                             "|cFFFFFFFFAvg ilvl:|r " .. string.format("%.2f", charData.itemLevel) .. "\n\n" ..
                             "|cffffff00Currencies:|r\n"
            
            -- Add currency information
            for _, currency in ipairs(charData.currencies) do
                charInfo = charInfo .. string.format("|cFFFFFFFF%s:|r %d\n", currency.name, currency.amount)
            end
            
            -- Add the character info text and adjust the Y position
            currentYOffset = AddCharacterInfo(content, charInfo, currentYOffset)
            
            -- Add the separator image after each character's info and adjust the Y position
            currentYOffset = AddSeparator(content, currentYOffset)
        end
    end
end


-- Slash command to toggle frame visibility
SLASH_CKINFO1 = "/ckinfo"
SlashCmdList["CKINFO"] = function(msg)
    if frame:IsShown() then
        frame:Hide()
    else
        frame:Show()
        UpdateCharacterInfo()  -- Ensure the info is updated when showing the frame
    end
end

-- Initialize hooks and setup the addon
local function InitializeAddon()
    -- No tooltip hook since it's commented out in the current version
end

InitializeAddon()

--[[
-- ***********************************************************************
-- **** Documentation and References *************************************
-- ***********************************************************************
-- API Documentation: 
-- https://warcraft.wiki.gg/wiki/Struct_TooltipData
-- https://github.com/Gethe/wow-ui-source/blob/live/Interface/AddOns/Blizzard_APIDocumentationGenerated/TooltipInfoSharedDocumentation.lua
ommon Draw Layers:
"BACKGROUND": Drawn behind everything else in the frame.
"BORDER": Drawn just above the background but behind other UI elements like buttons or text.
"ARTWORK": Drawn above background and border, but below buttons and other interactive elements.
"OVERLAY": Drawn above most other elements, used for highlighting, borders, etc.
"HIGHLIGHT": Drawn when a UI element (like a button) is highlighted, usually on top of everything else.
-- ***********************************************************************
--]]