local LibDBIcon = LibStub("LibDBIcon-1.0")

-- Check if LibDBIcon is available
if not LibDBIcon then
    print("|cFFFF0000<< |r|cFFFF0000Death|r|cFFFFFFFFRoll|r Enhancer: |cFFFF0000LibDBIcon-1.0 not found >>")
else
    print("|cFF00FF00<< |r|cFFFF0000Death|r|cFFFFFFFFRoll|r Enhancer: |cFF00FF00Has been loaded >>")
end


function CusRound(num, numDecimalPlaces)
    local mult = 10^(numDecimalPlaces or 0)
    return math.floor(num * mult + 0.5) / mult
end

-- Function to pick a random happy emote from a list
function GetRandomHappyEmote()
    local happyEmotes = {"CHEER", "LAUGH", "SALUTE", "DANCE", "VICTORY"} -- Add more happy emotes as needed
    local randomIndex = math.random(1, #happyEmotes)
    return happyEmotes[randomIndex]
end

-- Function to pick a random sad emote from a list
function GetRandomSadEmote()
    local sadEmotes = {"CRY", "SIGH", "SURRENDER", "LAY", "CONGRATULATE"} -- Add more sad emotes as needed
    local randomIndex = math.random(1, #sadEmotes)
    return sadEmotes[randomIndex]
end

-- Create a frame for measuring text dimensions
local textMeasureFrame = CreateFrame("Frame", nil, DeathRollFrame)
textMeasureFrame.title = textMeasureFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
textMeasureFrame.title:SetSize(0, 0) -- Set initial size to 0 to avoid interference

-- Function to create or update the infoFrame
local function UpdateInfoFrame(text)
    if not DeathRollFrame.infoFrame then
        DeathRollFrame.infoFrame = CreateFrame("Frame", nil, DeathRollFrame, "TranslucentFrameTemplate")
        DeathRollFrame.infoFrame:SetPoint("BOTTOM", DeathRollFrame.titleFrame.title, "TOP", 0, 0)
        DeathRollFrame.infoFrame.title = DeathRollFrame.infoFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
        DeathRollFrame.infoFrame.title:SetPoint("CENTER", DeathRollFrame.infoFrame)
        DeathRollFrame.infoFrame.title:SetTextColor(0.741, 0.718, 0.420, 1)
    end

    -- Set the text for measuring dimensions
    textMeasureFrame.title:SetText(text)

    -- Set the size of the infoFrame based on the text dimensions
    local textWidth = textMeasureFrame.title:GetStringWidth()
    DeathRollFrame.infoFrame:SetSize(textWidth + 30, 40) -- Add some padding
    DeathRollFrame.infoFrame.title:SetText(text)

    DeathRollFrame.infoFrame:SetScript("OnMouseDown", function(self) DeathRollFrame:StartMoving() end)
    DeathRollFrame.infoFrame:SetScript("OnMouseUp", function(self, button)
    if button == "LeftButton" then
        DeathRollFrame:StopMovingOrSizing()
    elseif button == "RightButton" then
        DeathRollFrame:ResetUI()
        DeathRollFrame:HideUI()
    end
    end)
end


local WindowX = 150
local WindowY = 70
local customText = "DeathRoll Enhancer!"

-- Create the main frame
local DeathRollFrame = CreateFrame("Frame", "DeathRollFrame", UIParent, "TranslucentFrameTemplate")
DeathRollFrame:SetPoint("CENTER", UIParent, "CENTER")
DeathRollFrame:SetSize(WindowX-15, WindowY)
DeathRollFrame:SetMovable(true)
DeathRollFrame:EnableMouse(true)
DeathRollFrame:SetScript("OnMouseDown", function(self) self:StartMoving() end)
DeathRollFrame:SetScript("OnMouseUp", function(self) self:StopMovingOrSizing() end)
-- DeathRollFrame:Hide()


-- Register for the PLAYER_REGEN_DISABLED event to capture when entering combat or interacting with UI
DeathRollFrame:RegisterEvent("PLAYER_REGEN_DISABLED")
DeathRollFrame:SetScript("OnEvent", function(self, event, ...)
    if event == "PLAYER_REGEN_DISABLED" then
        -- Release keyboard input when entering combat or interacting with UI
        self:SetPropagateKeyboardInput(false)
        self:HideUI()
    end
end)


-- Create a translucent frame
DeathRollFrame.titleFrame = CreateFrame("Frame", nil, DeathRollFrame, "TranslucentFrameTemplate")
DeathRollFrame.titleFrame:SetSize(WindowX, 40)
DeathRollFrame.titleFrame:SetPoint("CENTER", DeathRollFrame, "TOP", 0, 0)
DeathRollFrame.titleFrame.title = DeathRollFrame.titleFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
DeathRollFrame.titleFrame.title:SetPoint("CENTER", DeathRollFrame.titleFrame, "CENTER", 0, 0)
DeathRollFrame.titleFrame.title:SetText("DeathRoll Enhancer!")
DeathRollFrame.titleFrame.title:SetTextColor(0.863, 0.078, 0.235, 1)
DeathRollFrame:SetFrameStrata("HIGH")
DeathRollFrame.titleFrame:SetScript("OnMouseDown", function(self) DeathRollFrame:StartMoving() end)
DeathRollFrame.titleFrame:SetScript("OnMouseUp", function(self, button)
    if button == "LeftButton" then
        DeathRollFrame:StopMovingOrSizing()
    elseif button == "RightButton" then
        DeathRollFrame:ResetUI()
        DeathRollFrame:HideUI()
    end
end)

-- -- Create a custom close button
-- DeathRollFrame.closeButton = CreateFrame("Button", "DeathRollCloseButton", DeathRollFrame, "UIPanelCloseButton")
-- DeathRollFrame.closeButton:SetPoint("LEFT", DeathRollFrame.title, "RIGHT", 0, 0)
-- DeathRollFrame.closeButton:SetScript("OnClick", function() DeathRollFrame:HideUI() end)

-- Create an input box for the number
DeathRollFrame.inputBox = CreateFrame("EditBox", "DeathRollInputBox", DeathRollFrame, "InputBoxTemplate")
DeathRollFrame.inputBox:SetSize(WindowX * 0.60, 25)
DeathRollFrame.inputBox:SetPoint("CENTER", DeathRollFrame, "CENTER", 2.5, 10)
DeathRollFrame.inputBox:SetAutoFocus(false)
DeathRollFrame.inputBox:SetMaxLetters(6)
DeathRollFrame.inputBox:SetNumeric(true)
DeathRollFrame.inputBox:SetJustifyH("CENTER")

-- Create a roll button
DeathRollFrame.rollButton = CreateFrame("Button", "DeathRollButton", DeathRollFrame, "GameMenuButtonTemplate")
DeathRollFrame.rollButton:SetSize(WindowX*0.75, 25)
DeathRollFrame.rollButton:SetPoint("BOTTOM", DeathRollFrame, "BOTTOM", 0, 11)
DeathRollFrame.rollButton:SetText("Roll!")
DeathRollFrame.rollButton:SetScript("OnClick", function(self)
    DeathRollFrame:OnRollButtonClick()
    DeathRollFrame.infoFrame:Show()
    if DeathRollFrame.infoFrame then
    else
        UpdateInfoFrame(customText)
        DeathRollFrame.inputBox:ClearFocus()

    end
end)


-- -- Create a background frame
-- local BackgroundFrame = CreateFrame("Frame", "DeathRollBackground", DeathRollFrame)
-- BackgroundFrame:SetAllPoints()
-- BackgroundFrame:SetFrameLevel(DeathRollFrame:GetFrameLevel() - 1) -- Set it to a level below the main frame

-- -- Set a background texture for the background frame
-- BackgroundFrame.texture = BackgroundFrame:CreateTexture(nil, "BACKGROUND")
-- BackgroundFrame.texture:SetAllPoints()
-- BackgroundFrame.texture:SetColorTexture(0, 0, 0, 0.5) -- Set the texture to a color
-- BackgroundFrame.texture:SetTexture("Interface\\AddOns\\DeathRoll\\skull.tga")


-- Create a ScrollingMessageFrame
local scrollingMessageFrame = CreateFrame("ScrollingMessageFrame", "MyScrollingMessageFrame", DeathRollFrame)
scrollingMessageFrame:SetSize(WindowX, WindowY)
scrollingMessageFrame:SetPoint("TOP", DeathRollFrame, "BOTTOM", 0, 5)
scrollingMessageFrame:SetFontObject(ChatFontNormal)
scrollingMessageFrame:SetJustifyH("CENTER")
scrollingMessageFrame:SetFading(true)
scrollingMessageFrame:SetFadeDuration(30)
scrollingMessageFrame:SetMaxLines(1000)
scrollingMessageFrame:SetFrameStrata("LOW")
-- Set new messages to be inserted at the top
scrollingMessageFrame:SetInsertMode("TOP")

-- Add text to the ScrollingMessageFrame
scrollingMessageFrame:AddMessage("Line 1")
scrollingMessageFrame:AddMessage("Line 2")
scrollingMessageFrame:AddMessage("Line 3")
scrollingMessageFrame:AddMessage("Line 4")
scrollingMessageFrame:AddMessage("Line 4")
scrollingMessageFrame:AddMessage("Line 4")
scrollingMessageFrame:AddMessage("AddOn Loaded!", 0.0, 1.0, 0.0, nil, false);

-- Disable mouse wheel scrolling
scrollingMessageFrame:EnableMouseWheel(false)

-- Adjust the size of the ScrollingMessageFrame to fit the content
scrollingMessageFrame:SetSize(200, scrollingMessageFrame:GetHeight())















-- Variables to store target information
local targetName = nil
local rollNumber = nil

-- Function to handle the Roll button click
function DeathRollFrame:OnRollButtonClick()
    rollNumber = tonumber(self.inputBox:GetText())

    if rollNumber then
        -- Store the target player when rolling
        local target = UnitName("target")
        if rollNumber <= 1 then
            UpdateInfoFrame("Please enter a number greater than 1.")
            return
        end
        if target then
            targetName = target
            RandomRoll(1, rollNumber)
            UpdateInfoFrame("Waiting for " .. targetName .. " to roll...")
            self.rollButton:SetText("Waiting...")
            self.rollButton:Disable()
        else
            UpdateInfoFrame("Target a player before rolling.")
        end
    else
        UpdateInfoFrame("Please enter a number.")
    end
    self.inputBox:ClearFocus()
end

-- Event handler for CHAT_MSG_SYSTEM to capture the target's roll
function DeathRollFrame:OnChatMsgSystem(event, msg)
    local playerName, rollResult, targetRollString = msg:match("^(.+) rolls (%d+) %((%d+)%-(%d+)%)")

    if playerName and targetName and targetRollString then
        -- Check if the player has already rolled
        if (playerName ~= UnitName("player")) or (UnitName("player") == UnitName("target")) then
            -- scrollingMessageFrame:AddMessage(msg, 0,0.4667,1)
            -- scrollingMessageFrame:AddMessage(msg, 1,0.5333,0)
            self.rollButton:SetText("Roll!")
            self.rollButton:Enable()
            self.inputBox:SetText(tostring(rollResult)) -- Set the next max roll
            UpdateInfoFrame("You have a " .. CusRound((1 / (tonumber(rollResult))) * 100, 3) .. "% chance of losing")
            scrollingMessageFrame:AddMessage(msg, 0.863, 0.078, 0.235)
        else
            UpdateInfoFrame(targetName .. " has a " .. CusRound((1 / (tonumber(rollResult))) * 100, 3) .. "% chance of losing")
            scrollingMessageFrame:AddMessage(msg, 0.741, 0.718, 0.420)
        end

        if tonumber(rollResult) == 1 then
            self.rollButton:Disable()
            if playerName ~= UnitName("player") then
                self.rollButton:SetText("You won!!!")
                scrollingMessageFrame:AddMessage("You won!!!")
                DoEmote(GetRandomHappyEmote())
            else
                self.rollButton:SetText("You lost...")
                scrollingMessageFrame:AddMessage("You lost...")
                DoEmote(GetRandomSadEmote())
            end

            C_Timer.After(3, function() self:HideUI() end)
        end
    end
end

-- Function to show the DeathRoll UI
function DeathRollFrame:ShowUI()
    self:Show()
    self.inputBox:SetText("")
end

-- Function to hide the DeathRoll UI
function DeathRollFrame:HideUI()
    self:ResetUI()
    self:Hide()
end

-- Function to reset variables and UI elements
function DeathRollFrame:ResetUI()
    targetName = nil
    rollNumber = nil

    self.inputBox:SetText("")
    if self.infoFrame then
        self.infoFrame:Hide()
    end
    self.rollButton:SetText("Roll!")
    self.rollButton:Enable()
end

-- Register events
DeathRollFrame:RegisterEvent("CHAT_MSG_SYSTEM")
DeathRollFrame:SetScript("OnEvent", DeathRollFrame.OnChatMsgSystem)

-- Slash command to open the DeathRoll UI
SLASH_DEATHROLL1 = "/deathroll"
SLASH_DEATHROLL2 = "/dr"
SlashCmdList["DEATHROLL"] = function(msg)
    DeathRollFrame:ShowUI()
end

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

-- Create the minimap button using LibDBIcon
local miniButton = LibStub("LibDataBroker-1.1"):NewDataObject("DeathRollEnhancer", {
    type = "data source",
    text = "DeathRoll Enhancer",
    icon = "Interface\\AddOns\\DeathRollEnhancer\\Media\\Logo",
    OnClick = function(self, btn)
        if DeathRollFrame:IsVisible() then
            DeathRollFrame:HideUI()
        else
            DeathRollFrame:ShowUI()
        end
    end,
    OnTooltipShow = function(tooltip)
        if not tooltip or not tooltip.AddLine then return end
        tooltip:AddLine("|cFFFF0000Death|r|cffffffffRoll|r Enhancer")
        tooltip:AddLine("|cff808080Left Click:|r Toggle UI")
        tooltip:AddLine("|cff808080Right click the UI to close it.")
    end,
})

LibDBIcon:Register("DeathRollEnhancer", miniButton, DeathRollEnhancer)

print("End of DeathRollEnhancer.lua")