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

local addonVersion = "v 1.34"

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)

-- 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:SetScript("OnEvent", function(self, event, addonName)
    if addonName == "BlackBox" then -- Replace "BlackBox" with your actual addon folder name
        BlackBoxDB = BlackBoxDB or {} -- Initialize BlackBoxDB if it doesn't exist
        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)
    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) -- Flip the texture to face the correct direction
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, 400, 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)

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