local f = CreateFrame("Frame")
f:RegisterEvent("CURRENCY_DISPLAY_UPDATE")
f:RegisterEvent("CHAT_MSG_ADDON")
f:RegisterEvent("ZONE_CHANGED_NEW_AREA")

local hasReceivedAnnouncement = {}
local currentZone = nil

local prefix = "BlackBoxCrate"
C_ChatInfo.RegisterAddonMessagePrefix(prefix)

local function GetPlayerZone()
    local mapID = C_Map.GetBestMapForUnit("player")
    if not mapID then return "Unknown Zone" end
    return C_Map.GetMapInfo(mapID).name or "Unknown Zone"
end

local function GetPlayerPosition()
    local mapID = C_Map.GetBestMapForUnit("player")
    if not mapID then return "Unknown Zone", 0, 0 end

    local position = C_Map.GetPlayerMapPosition(mapID, "player")
    if not position then return "Unknown Zone", 0, 0 end

    local zoneName = C_Map.GetMapInfo(mapID).name or "Unknown Zone"
    local x = position.x * 100
    local y = position.y * 100
    return zoneName, x, y
end

f:SetScript("OnEvent", function(_, event, arg1, arg2, arg3)
    if event == "CURRENCY_DISPLAY_UPDATE" then
        local currencyID = arg1
        if currencyID == 1602 then -- 1602 is the ID for Honor currency
            local zone, x, y = GetPlayerPosition()

            -- Check if the player is near a War Supply Chest (pseudo-check, replace with actual logic if available)
            local isNearWarSupplyChest = C_Map.GetBestMapForUnit("player") == 1234 -- Replace 1234 with the map ID of the chest's location
            if isNearWarSupplyChest and not hasReceivedAnnouncement[zone] then
                hasReceivedAnnouncement[zone] = true

                local message = string.format("Crate Down: %s at (%.2f,%.2f)", zone, x, y)
                if IsInRaid() then
                    SendChatMessage(message, "RAID")
                elseif IsInGroup() then
                    SendChatMessage(message, "PARTY")
                else
                    print("Crate Down (solo mode): " .. message)
                end

                C_ChatInfo.SendAddonMessage(prefix, zone, IsInGroup(2) and "RAID" or IsInGroup() and "PARTY" or "SAY")
            end
        end

    elseif event == "CHAT_MSG_ADDON" then
        local incomingPrefix, zone = arg1, arg2
        if incomingPrefix == prefix then
            hasReceivedAnnouncement[zone] = true
        end

    elseif event == "ZONE_CHANGED_NEW_AREA" then
        local newZone = GetPlayerZone()
        if currentZone and currentZone ~= newZone then
            -- Clean up previous zone's flag
            hasReceivedAnnouncement[currentZone] = nil
        end
        currentZone = newZone
    end
end)
