-- OtherTimers.lua
-- Parses raid warnings and starts crate timers if the message format matches

local f = CreateFrame("Frame")
f:RegisterEvent("CHAT_MSG_RAID_WARNING")
f:RegisterEvent("CHAT_MSG_RAID")
f:RegisterEvent("CHAT_MSG_PARTY")
f:RegisterEvent("CHAT_MSG_GUILD")

-- Check if debug mode is enabled
local function IsDebugMode()
    return BlackBoxDB and BlackBoxDB.settings and BlackBoxDB.settings.debugMode
end

local function DebugPrint(...)
    if IsDebugMode() then
        print("[OtherTimers]", ...)
    end
end

local function ParseCrateWarning(msg)
    return msg:match("Flying in (.-) %- Shard = (%d+)")
end

local zoneRemap = {
    ["City of Threads"] = "Azj-Kahet",
    ["City of Threads - Lower"] = "Azj-Kahet",
    ["Slam Central Station"] = "Undermine",
    ["Blood Tower"] = "Azj-Kahet",
}

local allowedZones = {
    ["Azj-Kahet"] = true,
    ["Siren Isle"] = true,
    ["Isle of Dorn"] = true,
    ["The Ringing Deeps"] = true,
    ["Hallowfall"] = true,
    ["Undermine"] = true,
}

f:SetScript("OnEvent", function(_, event, msg, sender)
    DebugPrint("Event triggered:", event, "Message:", msg, "Sender:", sender)

    local zone, shard = ParseCrateWarning(msg)
    if not zone or not shard then
        DebugPrint("Failed to parse message.")
        return
    end

    zone = zoneRemap[zone] or zone

    if not allowedZones[zone] then
        DebugPrint("Zone not allowed:", zone)
        return
    end

    local isFromGuildmate = (event == "CHAT_MSG_GUILD")
    local source = isFromGuildmate and "GUILD" or event

    if BBTIMERS and BBTIMERS.CreateOrResetTimer then
        DebugPrint("Creating or resetting timer for", zone, "shard", shard)
        BBTIMERS.CreateOrResetTimer(zone, shard, 1097, nil, source)
    else
        DebugPrint("BBTIMERS not available.")
    end
end)