-- Create font string to display the ShardID
local shardIDText = TimerFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
shardIDText:SetPoint("TOPLEFT", TimerFrame, "TOPLEFT", 2, -20)
shardIDText:SetText("ShardID: |cffff0000N/A|r") -- Start off red and ashamed

local flashingColor = "|cff00ff00" -- Start with green
local isGreen = true

-- Create a ticker to alternate the flashing color
C_Timer.NewTicker(0.5, function()
    if isGreen then
        flashingColor = "|cffffff00" -- Yellow
    else
        flashingColor = "|cff00ff00" -- Green
    end
    isGreen = not isGreen
end)

-- Add hover functionality to highlight the ShardID text and show a tooltip
shardIDText:SetScript("OnEnter", function()
    shardIDText:SetTextColor(1, 1, 0) -- Change text color to yellow

    -- Show tooltip
    GameTooltip:SetOwner(shardIDText, "ANCHOR_RIGHT")
    GameTooltip:ClearLines()
    GameTooltip:AddLine("Left-Click to Show Shards " .. flashingColor .. "<-------NEW|r", 1, 1, 1) -- Add "NEW" pointing to the first line
    GameTooltip:AddLine("Displays Recorded Shards", 1, 1, 1)
    GameTooltip:Show()

    -- Start a ticker to refresh the tooltip periodically
    if not shardIDText.tooltipTicker then
        shardIDText.tooltipTicker = C_Timer.NewTicker(0.5, function()
            if GameTooltip:IsOwned(shardIDText) then
                GameTooltip:ClearLines()
                GameTooltip:AddLine("Left-Click to Show Shards " .. flashingColor .. "<-------NEW|r", 1, 1, 1) -- Refresh "NEW" pointing to the first line
                GameTooltip:AddLine("Displays Recorded Shards", 1, 1, 1)
                GameTooltip:Show()
            else
                shardIDText.tooltipTicker:Cancel()
                shardIDText.tooltipTicker = nil
            end
        end)
    end
end)

shardIDText:SetScript("OnLeave", function()
    shardIDText:SetTextColor(1, 1, 1) -- Revert text color to white

    -- Hide tooltip
    GameTooltip:Hide()

    -- Cancel the tooltip ticker if it exists
    if shardIDText.tooltipTicker then
        shardIDText.tooltipTicker:Cancel()
        shardIDText.tooltipTicker = nil
    end
end)

-- Table to store addon messages (persistent in BlackBoxDB)
BlackBoxDB = BlackBoxDB or {}
BlackBoxDB.shardIDLog = BlackBoxDB.shardIDLog or {}

-- Add a title to the ShardIDDrawer
local function CreateShardIDDrawer()
    if not ShardIDDrawer then
        ShardIDDrawer = CreateFrame("Frame", "ShardIDDrawer", UIParent, "BackdropTemplate")
        ShardIDDrawer:SetSize(400, 100) 
        ShardIDDrawer: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 }
        })
        ShardIDDrawer:SetBackdropColor(0, 0, 0, 0.8)
        ShardIDDrawer:SetBackdropBorderColor(1, 0.84, 0) -- Gold color (RGB: 255, 215, 0)
        ShardIDDrawer:Hide()

        -- Ensure the frame stays within the screen boundaries
        ShardIDDrawer:SetClampedToScreen(true)        

        -- Enable dragging
        ShardIDDrawer:SetMovable(true)
        ShardIDDrawer:EnableMouse(true)
        ShardIDDrawer:RegisterForDrag("LeftButton")
        ShardIDDrawer:SetScript("OnDragStart", function(self)
            self:StartMoving()
        end)
        ShardIDDrawer:SetScript("OnDragStop", function(self)
            self:StopMovingOrSizing()
        end)

        -- Add a smaller close button ("X")
        local closeButton = CreateFrame("Button", nil, ShardIDDrawer, "UIPanelCloseButton")
        closeButton:SetSize(16, 16) -- Make the close button smaller
        closeButton:SetPoint("TOPRIGHT", ShardIDDrawer, "TOPRIGHT", -5, -5)
        closeButton:SetScript("OnClick", function()
            ShardIDDrawer:Hide()
        end)

        -- Add a title at the top left
        local title = ShardIDDrawer:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        title:SetPoint("TOPLEFT", ShardIDDrawer, "TOPLEFT", 10, -5)
        title:SetText("ShardID Log")
        title:SetHeight(10) -- Set the height to 10px

        -- Add a scrollable text area for ShardID log
        ShardIDDrawer.ScrollFrame = CreateFrame("ScrollFrame", nil, ShardIDDrawer, "UIPanelScrollFrameTemplate")
        ShardIDDrawer.ScrollFrame:SetPoint("TOPLEFT", 10, -15) -- Full size, adjusted for padding
        ShardIDDrawer.ScrollFrame:SetPoint("BOTTOMRIGHT", -10, 10)

        -- Shorten the scroll bar
        ShardIDDrawer.ScrollFrame.ScrollBar:SetHeight(70)

        -- Adjust the scroll bar position
        ShardIDDrawer.ScrollFrame.ScrollBar:ClearAllPoints()
        ShardIDDrawer.ScrollFrame.ScrollBar:SetPoint("TOPRIGHT", ShardIDDrawer.ScrollFrame, "TOPRIGHT", 5, -30) -- Move left by 15 and down by 25
        ShardIDDrawer.ScrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", ShardIDDrawer.ScrollFrame, "BOTTOMRIGHT", -15, 10) -- Keep the bottom position consistent

        ShardIDDrawer.Content = CreateFrame("Frame", nil, ShardIDDrawer.ScrollFrame)
        ShardIDDrawer.Content:SetSize(380, 80) -- Adjusted to fit the drawer size
        ShardIDDrawer.ScrollFrame:SetScrollChild(ShardIDDrawer.Content)

        ShardIDDrawer.Text = ShardIDDrawer.Content:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        ShardIDDrawer.Text:SetPoint("TOPLEFT")
        ShardIDDrawer.Text:SetWidth(360)
        ShardIDDrawer.Text:SetJustifyH("LEFT")
        ShardIDDrawer.Text:SetJustifyV("TOP")
    end
end

-- Update the drawer content without the "ShardID Log:" text
local function UpdateShardIDDrawer()
    if not ShardIDDrawer then return end

    -- Define the color codes for each zone abbreviation
    local zoneColors = {
        ["AK"] = "|cffA330C9", -- Azj-Kahet
        ["SI"] = "|cffC79C6E", -- Siren Isle
        ["ID"] = "|cff40C7EB", -- Isle of Dorn
        ["RD"] = "|cffC41F3B", -- The Ringing Deeps
        ["HF"] = "|cff00FF96", -- Hallowfall
        ["UN"] = "|cffffa500"  -- Undermine
    }

    local text = ""
    for i = #BlackBoxDB.shardIDLog, 1, -1 do -- Iterate in reverse order
        local logEntry = BlackBoxDB.shardIDLog[i]
        -- Extract the zone abbreviation from the log entry
        local abbreviation = logEntry:match("%((%S+)%)")
        local color = zoneColors[abbreviation] or "|cffffffff" -- Default to white if no color is found
        text = text .. color .. logEntry .. "|r\n" -- Append the log entry with the color
    end
    ShardIDDrawer.Text:SetText(text)
end

-- Function to toggle the drawer with animation
local function ToggleShardIDDrawer()
    if not ShardIDDrawer then CreateShardIDDrawer() end

    if ShardIDDrawer:IsShown() then
        local ag = ShardIDDrawer:CreateAnimationGroup()
        local slide = ag:CreateAnimation("Translation")
        slide:SetOffset(-400, 0) -- Slide left to hide
        slide:SetDuration(0.3)
        slide:SetSmoothing("IN_OUT")
        ag:SetScript("OnFinished", function()
            ShardIDDrawer:Hide()
        end)
        ag:Play()
    else
        ShardIDDrawer:Show()
        ShardIDDrawer:ClearAllPoints()
        ShardIDDrawer:SetPoint("TOPRIGHT", TimerFrame, "TOPLEFT", -10, 0)
        local ag = ShardIDDrawer:CreateAnimationGroup()
        local slide = ag:CreateAnimation("Translation")
        slide:SetOffset(400, 0) -- Slide right to show
        slide:SetDuration(0.3)
        slide:SetSmoothing("IN_OUT")
        ag:Play()
        UpdateShardIDDrawer()
    end
end

-- Add click functionality to the ShardID text
shardIDText:SetScript("OnMouseDown", function(_, button)
    if button == "LeftButton" then
        ToggleShardIDDrawer()
    end
end)

-- Ensure the ShardID drawer closes when the main window closes
TimerFrame:HookScript("OnHide", function()
    if ShardIDDrawer and ShardIDDrawer:IsShown() then
        ShardIDDrawer:Hide()
    end
end)

-- Store the current ShardID
local currentShardID = "N/A"

-- Add a mapping of zone names to abbreviations
local zoneAbbreviations = {
    ["Azj-Kahet"] = "AK",
    ["City of Threads"] = "AK", -- Treat as Azj-Kahet
    ["City of Threads - Lower"] = "AK", -- Treat as Azj-Kahet
    ["The Ringing Deeps"] = "RD",
    ["Hallowfall"] = "HF",
    ["Isle of Dorn"] = "ID",
    ["Siren Isle"] = "SI",
    ["Undermine"] = "UN"
}

-- Add a mapping of subzones to their parent zones
local subzoneToZone = {
    ["Slam Central Station"] = "Undermine",
    -- Add other subzones here if needed
}

-- Add a variable to track the last announced zone
local lastAnnouncedZone = nil

-- Reset to player's ShardID (but don't set it to N/A)
local function ResetToPlayerShardID()
    local guid = UnitGUID("player")
    if guid then
        local segments = { strsplit("-", guid) }
        local id = segments[5]
        if id and id ~= currentShardID then
            SetShardID(id)
        end
    end
end

-- Modify the SetShardID function to send ShardID as an addon message
local function SetShardID(id)
    local coloredID
    if id == "N/A" then
        coloredID = "|cffff0000" .. id .. "|r" -- Red, the color of regret
    else
        coloredID = "|cff00ff00" .. id .. "|r" -- Green, the color of success
    end

    -- Get the current zone or subzone name
    local zoneName = GetZoneText()
    local parentZone = subzoneToZone[zoneName] or zoneName -- Map subzone to parent zone if applicable
    local zoneAbbreviation = zoneAbbreviations[parentZone] or "" -- Get the abbreviation for the parent zone

    -- Update the text to include the zone abbreviation if available
    local displayText = "ShardID: " .. coloredID
    if zoneAbbreviation ~= "" then
        displayText = displayText .. " (" .. zoneAbbreviation .. ")"
    end

    shardIDText:SetText(displayText)

    -- Send the ShardID as an addon message if it has changed and is not "N/A"
    local validZones = { "AK", "RD", "HF", "ID", "SI", "UN" }
    local isValidZone = false
    for _, validZone in ipairs(validZones) do
        if zoneAbbreviation == validZone then
            isValidZone = true
            break
        end
    end

    if id ~= currentShardID and id ~= "N/A" and isValidZone and lastAnnouncedZone ~= parentZone then
        if IsInGroup() or IsInRaid() then
            local prefix = "BlackBoxShardID" -- Addon message prefix
            local message = id .. (zoneAbbreviation ~= "" and " (" .. zoneAbbreviation .. ")" or "")
            local channel = IsInRaid() and "RAID" or "PARTY"
            C_ChatInfo.SendAddonMessage(prefix, message, channel)
        end
        lastAnnouncedZone = parentZone -- Update the last announced zone
    end

    currentShardID = id
    BlackBoxDB = BlackBoxDB or {}
    BlackBoxDB.shardID = id
    
    if BBTIMERS and BBTIMERS.MoveMatchingTimerToTop then
        BBTIMERS.MoveMatchingTimerToTop(id)
    end
end    

-- Reset to player's ShardID (but don't set it to N/A)
local function ResetToPlayerShardID()
    local guid = UnitGUID("player")
    if guid then
        local segments = { strsplit("-", guid) }
        local id = segments[5]
        if id and id ~= currentShardID then
            SetShardID(id)
        end
    end
end

-- Restore last saved ShardID on reload (yes, even your previous shame is preserved)
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(self, event, addonName)
    if addonName == "BlackBox" then
        BlackBoxDB = BlackBoxDB or {}
        local savedID = BlackBoxDB.shardID or "N/A"
        SetShardID(savedID)
    end
end)

-- Zone change = back to your personal ShardID, whatever that is
local zoneFrame = CreateFrame("Frame")
zoneFrame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
zoneFrame:SetScript("OnEvent", function()
    SetShardID("N/A") -- Reset ShardID to "N/A" in red
end)

-- Update on mob mouseover (the actual useful part of your life)
local mouseoverFrame = CreateFrame("Frame")
mouseoverFrame:SetScript("OnUpdate", function()
    if UnitExists("mouseover") and not UnitIsPlayer("mouseover") then
        local name = UnitName("mouseover")
        if name == "Oathsworn Peacekeeper" or name == "Killia" or name == "Melanie Morten" then
            return -- Ignore these NPCs
        end
        local guid = UnitGUID("mouseover")
        if guid then
            local segments = { strsplit("-", guid) }
            local id = segments[5]
            if id and id ~= currentShardID then
                SetShardID(id)
            end
        end
    end
end)

-- Register an event for when the player's target changes
local targetFrame = CreateFrame("Frame")
targetFrame:RegisterEvent("PLAYER_TARGET_CHANGED")
targetFrame:SetScript("OnEvent", function()
    if UnitExists("target") and not UnitIsPlayer("target") and not (UnitPlayerControlled("target") and not UnitInParty("target")) then
        local name = UnitName("target")
        if name == "Oathsworn Peacekeeper" or name == "Killia" or name == "Melanie Morten" then
            return -- Ignore these NPCs
        end
        local guid = UnitGUID("target")
        if guid then
            local segments = { strsplit("-", guid) }
            local id = segments[5]
            if id and id ~= currentShardID then
                SetShardID(id)
            end
        end
    end
end)

-- Function to log addon messages
local function LogShardIDMessage(timestamp, sender, realm, shardID, abbreviation)
    local logEntry = string.format("[%s] ShardID %s (%s): %s-%s", date("%I:%M:%S %p"), shardID, abbreviation, sender, realm)
    table.insert(BlackBoxDB.shardIDLog, logEntry)
    if #BlackBoxDB.shardIDLog > 50 then -- Limit log size to 50 entries
        table.remove(BlackBoxDB.shardIDLog, 1)
    end
    UpdateShardIDDrawer()
end

-- Register for addon messages
local shardIDEventFrame = CreateFrame("Frame")
shardIDEventFrame:RegisterEvent("CHAT_MSG_ADDON")
shardIDEventFrame:RegisterEvent("ADDON_LOADED")
shardIDEventFrame:SetScript("OnEvent", function(_, event, prefix, message, channel, sender)
    if event == "CHAT_MSG_ADDON" and prefix == "BlackBoxShardID" then
        local shardID, abbreviation = message:match("^(%S+)%s%((%S+)%)$")
        if shardID and abbreviation then
            local timestamp = date("%H:%M:%S")
            local senderName, senderRealm = strsplit("-", sender)
            LogShardIDMessage(timestamp, senderName or sender, senderRealm or "Unknown", shardID, abbreviation)
        
            -- Move matching timer to top on all clients
            if BBTIMERS and BBTIMERS.MoveMatchingTimerToTop then
                BBTIMERS.MoveMatchingTimerToTop(shardID)
            end
        end
        
    elseif event == "ADDON_LOADED" and prefix == "BlackBox" then
        BlackBoxDB = BlackBoxDB or {}
        BlackBoxDB.shardIDLog = BlackBoxDB.shardIDLog or {}
        UpdateShardIDDrawer()
    end
end)

-- Register the addon message prefix
C_ChatInfo.RegisterAddonMessagePrefix("BlackBoxShardID")

-- Register for group updates to send ShardID when joining a group
local groupFrame = CreateFrame("Frame")
groupFrame:RegisterEvent("GROUP_ROSTER_UPDATE")
groupFrame:SetScript("OnEvent", function()
    if IsInGroup() or IsInRaid() then
        local prefix = "BlackBoxShardID" -- Addon message prefix
        local zoneName = GetZoneText()
        local parentZone = subzoneToZone[zoneName] or zoneName -- Map subzone to parent zone if applicable
        local zoneAbbreviation = zoneAbbreviations[parentZone] or "" -- Get the abbreviation for the parent zone
        local message = currentShardID .. (zoneAbbreviation ~= "" and " (" .. zoneAbbreviation .. ")" or "")
        local channel = IsInRaid() and "RAID" or "PARTY"
        C_ChatInfo.SendAddonMessage(prefix, message, channel)
    end
end)

-- First time setup: pretend like the player’s shard matters
ResetToPlayerShardID()
