-- TimerFrame.lua
-- ############################################################

local addonVersion = "v 1.359"

syncedTimerData = {}
syncTimestamp = 0


-- Create the main frame
local TimerFrame = CreateFrame("Frame", "TimerFrame", UIParent, "BackdropTemplate")
TimerFrame:SetSize(236, 100)  -- Adjust width/height as needed
TimerFrame:SetPoint("CENTER")
TimerFrame:SetMovable(true)
TimerFrame:EnableMouse(true)
TimerFrame:RegisterForDrag("LeftButton")
TimerFrame:SetScript("OnDragStart", TimerFrame.StartMoving)
TimerFrame:SetScript("OnDragStop", TimerFrame.StopMovingOrSizing)

-- Determine faction color
local isHorde = UnitFactionGroup("player") == "Horde"
local backdropColor = isHorde and {0.75, 0, 0, 1} or {0, 0, 0.75, 1} -- Red for Horde, Blue for Alliance
local borderColor = {1, 0.84, 0, 1} -- Gold border remains the same

-- Set a backdrop with rounded edges using tooltip textures
TimerFrame:SetBackdrop({
  bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
  edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
  tile = true, tileSize = 16, edgeSize = 16,
  insets = { left = 4, right = 4, top = 4, bottom = 4 }
})
TimerFrame:SetBackdropColor(unpack(backdropColor))
TimerFrame:SetBackdropBorderColor(unpack(borderColor))
TimerFrame:SetClampedToScreen(true)

-- Create a smaller close button without a border
local closeButton = CreateFrame("Button", nil, TimerFrame)
closeButton:SetSize(16, 16) -- Smaller size
closeButton:SetPoint("TOPRIGHT", TimerFrame, "TOPRIGHT", -5, -5)

-- Set a custom texture for the close button
closeButton.texture = closeButton:CreateTexture(nil, "ARTWORK")
closeButton.texture:SetAllPoints()
closeButton.texture:SetTexture("Interface\\Buttons\\UI-StopButton") -- Example texture, replace if needed

-- Add a click handler to hide the TimerFrame
closeButton:SetScript("OnClick", function()
    TimerFrame:Hide()
    BlackBoxDB.settings.timerFrameHidden = true -- Save the hidden state
end)

-- Ensure the TimerFrame's visibility state is saved when shown
TimerFrame:HookScript("OnShow", function()
    BlackBoxDB.settings.timerFrameHidden = false
end)

-- Add a version text under the close button
local versionText = TimerFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
versionText:SetPoint("TOPRIGHT", TimerFrame, "TOPRIGHT", -5, -18) -- Position under the close button
versionText:SetText(addonVersion)
versionText:SetTextColor(1, 1, 1, 1) -- White color

------------------------------------------------------------
-- Add a tooltip to TimerFrame on mouseover
TimerFrame:SetScript("OnEnter", function(self)
  GameTooltip:SetOwner(self, "ANCHOR_CURSOR")
  GameTooltip:SetText("Right Click Change\nTransparancy.", 1, 1, 1, true)
  GameTooltip:Show()

  C_Timer.After(3, function()
    if GameTooltip:IsOwned(self) then
      GameTooltip:Hide()
    end
  end)
end)

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

------------------------------------------------------------
-- Create an overlay frame to detect clicks outside the slider
local SliderOverlay = CreateFrame("Frame", "SliderOverlay", UIParent)
SliderOverlay:SetAllPoints(UIParent)
SliderOverlay:EnableMouse(true)
SliderOverlay:Hide()
SliderOverlay:SetFrameStrata("FULLSCREEN_DIALOG")
SliderOverlay:SetScript("OnMouseDown", function(self, button)
  if button == "LeftButton" then
    HideSlider()
    self:Hide()
  end
end)

------------------------------------------------------------
-- Create the transparency slider (initially hidden) as a child of UIParent
local TransparencySlider = CreateFrame("Slider", "TransparencySlider", UIParent, "OptionsSliderTemplate")
TransparencySlider:SetSize(150, 20)
-- Position it relative to TimerFrame
TransparencySlider:SetPoint("BOTTOM", TimerFrame, "TOP", 0, 20)
-- Ensure the slider is above the overlay
TransparencySlider:SetFrameStrata("FULLSCREEN_DIALOG")
TransparencySlider:SetFrameLevel(SliderOverlay:GetFrameLevel() + 1)
TransparencySlider:SetMinMaxValues(0, 1)
TransparencySlider:SetValueStep(0.01)
TransparencySlider:SetValue(1)  -- Default: fully opaque
TransparencySlider:SetObeyStepOnDrag(true)
TransparencySlider:Hide()

-- Add a label below the slider
local sliderLabel = TransparencySlider:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
sliderLabel:SetPoint("TOP", TransparencySlider, "BOTTOM", 0, -2)
sliderLabel:SetText("Transparency")

-- When the slider value changes, update TimerFrame’s backdrop transparency and save to BlackBoxDB
TransparencySlider:SetScript("OnValueChanged", function(self, value)
  TimerFrame:SetBackdropColor(backdropColor[1], backdropColor[2], backdropColor[3], value)
  BlackBoxDB = BlackBoxDB or {}
  BlackBoxDB.transparency = value -- Save the current transparency value
end)

-- Load the saved transparency value when initializing the slider
local savedTransparency = BlackBoxDB and BlackBoxDB.transparency or 1 -- Default to fully opaque
TransparencySlider:SetValue(savedTransparency)
TimerFrame:SetBackdropColor(backdropColor[1], backdropColor[2], backdropColor[3], savedTransparency)

------------------------------------------------------------
-- Functions to show and hide the slider with a slide animation
function ShowSlider()
  if TransparencySlider:IsShown() then return end
  TransparencySlider:Show()
  local ag = TransparencySlider:CreateAnimationGroup()
  local anim = ag:CreateAnimation("Translation")
  anim:SetDuration(0.3)
  anim:SetSmoothing("IN_OUT")
  anim:SetOffset(0, -20)  -- Slide down into view
  ag:Play()
end

function HideSlider()
  if not TransparencySlider:IsShown() then return end
  local ag = TransparencySlider:CreateAnimationGroup()
  local anim = ag:CreateAnimation("Translation")
  anim:SetDuration(0.3)
  anim:SetSmoothing("IN_OUT")
  anim:SetOffset(0, 20)  -- Slide up out of view
  ag:SetScript("OnFinished", function()
    TransparencySlider:Hide()
  end)
  ag:Play()
end

------------------------------------------------------------
-- TimerFrame click handler: on left-click, show the slider if not already shown.
TimerFrame:SetScript("OnMouseDown", function(self, button)
  if button == "RightButton" then
    if not TransparencySlider:IsShown() then
      ShowSlider()
      SliderOverlay:Show()
    end
  end
end)

-- Ensure BlackBoxDB is initialized when the addon is loaded
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("PLAYER_ENTERING_WORLD") -- Trigger when the player logs in or reloads
frame:SetScript("OnEvent", function(self, event, addonName)
    if event == "ADDON_LOADED" and addonName == "BlackBox" then
        BlackBoxDB = BlackBoxDB or {} -- Initialize BlackBoxDB if it doesn't exist
        BlackBoxDB.settings = BlackBoxDB.settings or {}
        BlackBoxDB.transparency = BlackBoxDB.transparency or 1 -- Default transparency to 1 if not set

        -- Apply the saved transparency value
        TransparencySlider:SetValue(BlackBoxDB.transparency)
        TimerFrame:SetBackdropColor(backdropColor[1], backdropColor[2], backdropColor[3], BlackBoxDB.transparency)

        -- Restore the TimerFrame visibility state
        if BlackBoxDB.settings.timerFrameHidden then
            TimerFrame:Hide()
        else
            TimerFrame:Show()
        end
    elseif event == "PLAYER_ENTERING_WORLD" then
        -- Determine the appropriate communication channel
        local channel
        if IsInInstance() then
            channel = "INSTANCE_CHAT" -- Use INSTANCE_CHAT for instance groups
        elseif IsInRaid() then
            channel = "RAID"
        elseif IsInGroup() then
            channel = "PARTY"
        end

        if channel then
            C_ChatInfo.SendAddonMessage("BlackBoxPing", "pong", channel)
        else
            print("You aren't in a party or raid.")
        end
    end
end)

-- Add a resize grip to the bottom-left corner of TimerFrame
local ResizeGrip = CreateFrame("Frame", "ResizeGrip", TimerFrame)
ResizeGrip:SetSize(16, 16) -- Size of the grip
ResizeGrip:SetPoint("BOTTOMLEFT", TimerFrame, "BOTTOMLEFT", 0, 0)

-- Set a diagonal texture for the grip
ResizeGrip.texture = ResizeGrip:CreateTexture(nil, "OVERLAY")
ResizeGrip.texture:SetAllPoints()
ResizeGrip.texture:SetTexture("Interface\\CHATFRAME\\UI-ChatIM-SizeGrabber-Up") -- Blizzard's built-in diagonal grip texture
ResizeGrip.texture:SetTexCoord(1, 0, 0, 1) -- Corrected to use four arguments
ResizeGrip.texture:SetVertexColor(0, 1, 0, 1) -- Green color

-- Enable mouse interaction for resizing
ResizeGrip:EnableMouse(true)
ResizeGrip:SetScript("OnMouseDown", function(self, button)
  if button == "LeftButton" then
    TimerFrame:StartSizing("BOTTOMLEFT")
    self:GetParent():SetUserPlaced(true)
  end
end)

ResizeGrip:SetScript("OnMouseUp", function(self, button)
  if button == "LeftButton" then
    TimerFrame:StopMovingOrSizing()
  end
end)

-- Ensure TimerFrame is resizable with min and max size constraints
TimerFrame:SetResizable(true)
TimerFrame:SetResizeBounds(236, 69, 410, 500) -- Minimum width, minimum height, maximum width, maximum height

-------------------------------------------------------------
-- Conquest icon and text display
-------------------------------------------------------------   

-- Conquest Icon and Text Display (inside TimerFrame, saved in BlackBoxDB)
local fallbackIconPath = "Interface\\AddOns\\BlackBox\\conquestIcon.tga"
BlackBoxDB = BlackBoxDB or {}

-- Create the conquest frame as a child of TimerFrame
local conquestFrame = CreateFrame("Frame", "BlackBox_ConquestFrame", TimerFrame, "BackdropTemplate")
conquestFrame:SetSize(40, 40)
conquestFrame:SetResizable(true) -- Allow resizing
conquestFrame:SetResizeBounds(20, 20, 100, 100) -- Set min and max size constraints

-- Function to clamp position within TimerFrame's safe area
local function ClampPosition(offsetX, offsetY)
    local parentWidth, parentHeight = TimerFrame:GetWidth(), TimerFrame:GetHeight()
    local cw, ch = conquestFrame:GetWidth(), conquestFrame:GetHeight()
    local minX = 25
    local maxX = parentWidth - cw - 45
    local maxY = -5
    local minY = -(parentHeight - ch - 30)
    offsetX = math.max(minX, math.min(offsetX, maxX))
    offsetY = math.max(minY, math.min(offsetY, maxY))
    return offsetX, offsetY
end

-- Set initial position, clamping saved values if available
local initialX, initialY
if BlackBoxDB.conquestOffsetX and BlackBoxDB.conquestOffsetY then
    initialX, initialY = ClampPosition(BlackBoxDB.conquestOffsetX, BlackBoxDB.conquestOffsetY)
else
    initialX, initialY = 15, -20
end
conquestFrame:SetPoint("TOPLEFT", TimerFrame, "TOPLEFT", initialX, initialY)

-- Enable dragging and save the clamped position on drag stop
conquestFrame:EnableMouse(true)
conquestFrame:SetMovable(true)
conquestFrame:RegisterForDrag("LeftButton")
conquestFrame:SetScript("OnDragStart", function(self)
    self:StartMoving()
end)
conquestFrame:SetScript("OnDragStop", function(self)
    self:StopMovingOrSizing()
    local parentLeft, parentTop = TimerFrame:GetLeft(), TimerFrame:GetTop()
    local selfLeft, selfTop = self:GetLeft(), self:GetTop()
    local offsetX = selfLeft - parentLeft
    local offsetY = selfTop - parentTop
    offsetX, offsetY = ClampPosition(offsetX, offsetY)
    self:ClearAllPoints()
    self:SetPoint("TOPLEFT", TimerFrame, "TOPLEFT", offsetX, offsetY)
    BlackBoxDB.conquestOffsetX = offsetX
    BlackBoxDB.conquestOffsetY = offsetY
end)

-- Enable resizing on right-click
conquestFrame:SetScript("OnMouseDown", function(self, button)
  if button == "RightButton" then
    self:StartSizing("BOTTOMRIGHT") -- Allow resizing from the bottom-right corner
    self:SetResizable(true)
    self:SetResizeBounds(20, 20, 100, 100) -- Set min and max size constraints
  end
end)

conquestFrame:SetScript("OnMouseUp", function(self, button)
  if button == "RightButton" then
    self:StopMovingOrSizing()
    -- Save the new size to BlackBoxDB
    BlackBoxDB.conquestWidth = self:GetWidth()
    BlackBoxDB.conquestHeight = self:GetHeight()

    -- Re-anchor the conquest frame to ensure proper positioning
    local offsetX = BlackBoxDB.conquestOffsetX or 15
    local offsetY = BlackBoxDB.conquestOffsetY or -20
    offsetX, offsetY = ClampPosition(offsetX, offsetY)
    self:ClearAllPoints()
    self:SetPoint("TOPLEFT", TimerFrame, "TOPLEFT", offsetX, offsetY)
  end
end)

-- Apply saved size on load
local savedWidth = BlackBoxDB.conquestWidth or conquestFrame:GetWidth()
local savedHeight = BlackBoxDB.conquestHeight or conquestFrame:GetHeight()
conquestFrame:SetSize(savedWidth, savedHeight)

conquestFrame:SetSize(savedWidth, savedHeight)

-- Respect the user's setting on load
if BlackBoxDB.settings and BlackBoxDB.settings.showConquestIcon == false then
    conquestFrame:Hide()
else
    conquestFrame:Show()
end


-- Create and set up the conquest icon texture
local conquestIcon = conquestFrame:CreateTexture(nil, "BACKGROUND") -- Change "ARTWORK" to "BACKGROUND"
conquestIcon:SetAllPoints(conquestFrame)
conquestIcon:SetTexture(fallbackIconPath)

-- Create a font string to display conquest currency
local conquestText = conquestFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
conquestText:SetPoint("BOTTOM", conquestFrame, "BOTTOM", 0, -12)
conquestText:SetTextColor(0, 1, 0, 1)

-- Function to update conquest display using currency ID 1602
local maxTotalEarned = 0 -- Track the maximum total earned during the session

local function UpdateConquestDisplay()
    local currencyInfo = C_CurrencyInfo and C_CurrencyInfo.GetCurrencyInfo(1602)
    if not currencyInfo then
        conquestText:SetText("0/???")
        conquestIcon:SetTexture(fallbackIconPath)
        return
    end

    local totalEarned = currencyInfo.totalEarned or 0 -- Total earned during the season
    local seasonCap = (currencyInfo.maxQuantity and currencyInfo.maxQuantity > 0) and currencyInfo.maxQuantity or "???"

    -- Update the maximum total earned
    maxTotalEarned = math.max(maxTotalEarned, totalEarned)

    -- Display the maximum total earned and season cap
    conquestText:SetText(maxTotalEarned .. "/" .. seasonCap)
    conquestIcon:SetTexture(currencyInfo.icon or fallbackIconPath)
end

-- Update immediately and every 5 seconds
UpdateConquestDisplay()
C_Timer.NewTicker(5, UpdateConquestDisplay)

-- Add a tooltip to the conquest frame on mouseover
conquestFrame:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_CURSOR")
    GameTooltip:SetText("Drag to move\nRight-click to resize", 1, 1, 1, true)
    GameTooltip:Show()
end)

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

-- When TimerFrame is resized, re-clamp and reapply the conquest frame position
TimerFrame:HookScript("OnSizeChanged", function(self, width, height)
    local offsetX = BlackBoxDB.conquestOffsetX or 15
    local offsetY = BlackBoxDB.conquestOffsetY or -20
    offsetX, offsetY = ClampPosition(offsetX, offsetY)
    conquestFrame:ClearAllPoints()
    conquestFrame:SetPoint("TOPLEFT", TimerFrame, "TOPLEFT", offsetX, offsetY)
    BlackBoxDB.conquestOffsetX = offsetX
    BlackBoxDB.conquestOffsetY = offsetY
end)

-- Ensure ConquestFrame resizes uniformly
conquestFrame:SetScript("OnSizeChanged", function(self, width, height)
    local size = math.min(width, height) -- Use the smaller of the two dimensions
    self:SetSize(size, size) -- Set both width and height to the same value
end)

-- Add a "Black Box" clickable text to TimerFrame
local titleText = TimerFrame:CreateFontString("TitleText", "OVERLAY", "GameFontNormal")
titleText:SetPoint("TOPLEFT", TimerFrame, "TOPLEFT", 2, -2) -- Position the text
titleText:SetText("War Supply Crates")
titleText:SetTextColor(0, 1, 0) -- Initial color: Green

-- Add a tooltip and hover effects
titleText:EnableMouse(true)
titleText:SetScript("OnEnter", function(self)
    self:SetTextColor(1, 1, 1) -- Change to white on hover
    GameTooltip:SetOwner(self, "ANCHOR_CURSOR")
    GameTooltip:SetText("Click to send a message", 1, 1, 1, true)
    GameTooltip:Show()
end)

titleText:SetScript("OnLeave", function(self)
    self:SetTextColor(0, 1, 0) -- Revert to green when not hovered
    GameTooltip:Hide()
end)

-- Drawer + scroll frame for listing addon users
local whoDrawer = CreateFrame("Frame", "BlackBox_WhoDrawer", TimerFrame, "BackdropTemplate")
whoDrawer:SetSize(220, 100)
whoDrawer:SetPoint("TOP", TimerFrame, "BOTTOM", 0, -5)
whoDrawer:SetBackdrop({
  bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
  edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
  tile = true, tileSize = 16, edgeSize = 16,
  insets = { left = 4, right = 4, top = 4, bottom = 4 }
})
whoDrawer:SetBackdropColor(0, 0, 0, 0.85)
whoDrawer:Hide()

local scrollFrame = CreateFrame("ScrollFrame", nil, whoDrawer, "UIPanelScrollFrameTemplate")
scrollFrame:SetPoint("TOPLEFT", 5, -5)
scrollFrame:SetPoint("BOTTOMRIGHT", -27, 5)

local scrollContent = CreateFrame("Frame", nil, scrollFrame)
scrollContent:SetSize(200, 200)
scrollFrame:SetScrollChild(scrollContent)

local whoEntries = {}
local receivedPlayers = {}
local lastPingSentTime = 0  -- new variable to track ping time

-- Normalize player names (strip realm suffix and convert to lowercase)
local function NormalizePlayerName(name)
    return name and name:lower():gsub("^%l", string.upper):gsub("%-.*", "") or nil -- Capitalize first letter
end

-- Update the "Who" list logic
local function UpdateWhoList()
    for _, fs in ipairs(whoEntries) do fs:Hide() end
    wipe(whoEntries)

    local yOffset = -5
    for name, version in pairs(receivedPlayers) do
        if version then
            local fs = scrollContent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
            fs:SetPoint("TOPLEFT", 5, yOffset)
            fs:SetText("- " .. name:gsub("^%l", string.upper) .. " (" .. version .. ")") -- Capitalize first letter
            table.insert(whoEntries, fs)
            yOffset = yOffset - 15
        end
    end

    local expectedPlayers = {}
    if IsInRaid() then
        for i = 1, GetNumGroupMembers() do
            local name = NormalizePlayerName(select(1, GetRaidRosterInfo(i)))
            if name then expectedPlayers[name] = true end
        end
    elseif IsInGroup() then
        for i = 1, GetNumGroupMembers() do
            local unit = (i == 1) and "player" or "party" .. (i - 1)
            local name = NormalizePlayerName(UnitName(unit))
            if name then expectedPlayers[name] = true end
        end
    end

    for name, _ in pairs(expectedPlayers) do
        if not receivedPlayers[name] and name ~= NormalizePlayerName(UnitName("player")) then
            local fs = scrollContent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
            fs:SetPoint("TOPLEFT", 5, yOffset)
            fs:SetText("|cffff0000- " .. name:gsub("^%l", string.upper) .. " (no response)|r") -- Capitalize first letter
            table.insert(whoEntries, fs)
            yOffset = yOffset - 15
        end
    end

    scrollContent:SetHeight(math.abs(yOffset) + 5)
end

-- Create the "Who" button (Canvas-style positioning)
local whoButton = CreateFrame("Button", "BlackBox_WhoButton", TimerFrame, "UIPanelButtonTemplate")
whoButton:SetSize(40, 20)
whoButton:SetPoint("LEFT", titleText, "RIGHT", 3, -5)
whoButton:SetText("Who")
whoButton:SetNormalFontObject("GameFontNormalSmall")
whoButton:Hide()

local lastPingTime = 0 -- Track the last time a ping was sent

whoButton:SetScript("OnClick", function()
    if whoDrawer:IsShown() then
        whoDrawer:Hide()
    else
        wipe(receivedPlayers)
        whoDrawer:Show()

        local currentTime = GetTime()
        if currentTime - lastPingTime < 5 then -- Prevent spamming pings within 5 seconds
            print("Ping not sent: Please wait before sending another ping.")
            return
        end

        lastPingTime = currentTime -- Update the last ping time

        -- Avoid sending pings in instance groups
        if not IsInInstance() then
            local channel = IsInRaid() and "RAID" or "PARTY"
            if IsInGroup() then
                C_ChatInfo.SendAddonMessage("BlackBoxPing", "ping", channel) -- Send sync request
            else
                print("You aren't in a party or raid.")
            end
        else
            print("Ping not sent: You are in an instance group.")
        end
    end
end)

-- Logic to show or hide the button based on group status
local function UpdateWhoButtonVisibility()
    if IsInGroup() and UnitIsGroupLeader("player") then
        whoButton:Show()
    else
        whoButton:Hide()
    end
end

-- Monitor changes to group state
local whoFrame = CreateFrame("Frame")
whoFrame:RegisterEvent("GROUP_ROSTER_UPDATE")
whoFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
whoFrame:SetScript("OnEvent", UpdateWhoButtonVisibility)

-- Call it once to set initial state
UpdateWhoButtonVisibility()

-- Addon message listener
local pingFrame = CreateFrame("Frame")
pingFrame:RegisterEvent("CHAT_MSG_ADDON")
pingFrame:SetScript("OnEvent", function(_, _, prefix, msg, _, sender)
    if prefix == "BlackBoxPing" then
        local normalizedSender = NormalizePlayerName(sender)
        if msg == "ping" then
            local channel = IsInRaid() and "RAID" or "PARTY"
            C_ChatInfo.SendAddonMessage("BlackBoxPing", "pong:" .. addonVersion, channel)
        elseif msg:match("^pong:") then
            local version = msg:sub(6)
            receivedPlayers[normalizedSender] = version
        end
    end
end)

-- Add a periodic timer to refresh the "Who" list in real-time
C_Timer.NewTicker(1, function()
    if whoDrawer:IsShown() then
        UpdateWhoList()
    end
end)

-- Ensure the prefix is registered successfully
if not C_ChatInfo.RegisterAddonMessagePrefix("BlackBoxPing") then
    print("Failed to register addon message prefix: BlackBoxPing")
end

C_ChatInfo.RegisterAddonMessagePrefix("BlackBoxPing")

-- Add a click handler for the text
titleText:SetScript("OnMouseDown", function(self)
    self:SetTextColor(0, 0.5, 0) -- Darker green highlight on click
end)

titleText:SetScript("OnMouseUp", function(self)
    self:SetTextColor(1, 1, 1) -- Reset to white after click

    -- Send test messages to raid or party chat
    if IsInRaid() then
        SendChatMessage("https://www.curseforge.com/wow/addons/warsupplycrates", "RAID")
        SendChatMessage("https://discord.gg/uAPFdxtAE7", "RAID")
    elseif IsInGroup() then
        SendChatMessage("https://www.curseforge.com/wow/addons/warsupplycrates", "PARTY")
        SendChatMessage("https://discord.gg/uAPFdxtAE7", "PARTY")
    else
        print("You are not in a raid or party.")
    end
end)

-- Function to reposition the transparency drawer based on TimerFrame's position
local function UpdateTransparencyDrawerPosition()
    local screenHeight = UIParent:GetHeight()
    local frameTop = TimerFrame:GetTop()

    if frameTop and (screenHeight - frameTop) <= 40 then
        -- If TimerFrame is within 50 points of the top of the screen, move the drawer to the bottom
        TransparencySlider:ClearAllPoints()
        TransparencySlider:SetPoint("TOP", TimerFrame, "BOTTOM", 0, -20)
    else
        -- Default position: above the TimerFrame
        TransparencySlider:ClearAllPoints()
        TransparencySlider:SetPoint("BOTTOM", TimerFrame, "TOP", 0, 20)
    end
end

-- Hook the function to TimerFrame's OnUpdate event to check position dynamically
TimerFrame:HookScript("OnUpdate", UpdateTransparencyDrawerPosition)

-- Highlight ResizeGrip on hover
ResizeGrip:SetFrameStrata("FULLSCREEN_DIALOG") -- Increase the strata to ensure it appears above other elements
ResizeGrip:SetScript("OnEnter", function(self)
    self.texture:SetVertexColor(1, 0.84, 0, 1) -- Gold color
    GameTooltip:SetOwner(self, "ANCHOR_CURSOR")
    GameTooltip:SetText("Drag to resize", 1, 1, 1, true)
    GameTooltip:Show()
end)

ResizeGrip:SetScript("OnLeave", function(self)
    self.texture:SetVertexColor(0, 1, 0, 1) -- Reset to green color
    GameTooltip:Hide()
end)
