-- timersync.lua
-- Automatically start and display timers when joining a party or raid, based on ticker rotation

local f = CreateFrame("Frame")
f:RegisterEvent("GROUP_ROSTER_UPDATE")
f:RegisterEvent("PLAYER_ENTERING_WORLD")

local function GetTickerTimers()
    local timers = {}

    if UnitIsGroupLeader("player") or not IsInGroup() then
        -- Leader: pull from live frames
        local scrollChild = TimerScrollFrame and TimerScrollFrame:GetScrollChild()
        if scrollChild then
            local frames = { scrollChild:GetChildren() }
            table.sort(frames, function(a, b)
                return (a:GetTop() or 0) > (b:GetTop() or 0)
            end)

            local usedZones = {}
            for _, frame in ipairs(frames) do
                if frame:IsShown() then
                    local zone = frame.zoneName or "Unknown"
                    if not usedZones[zone] then
                        local shard = frame.shardID or "0"
                        local duration = frame.duration or 1097
                        local remaining = frame.remainingSeconds or duration
                        table.insert(timers, {
                            zone = zone,
                            shardID = shard,
                            duration = duration,
                            remaining = remaining
                        })
                        usedZones[zone] = true
                        if #timers >= 6 then break end
                    end
                end
            end
        end
    else
        -- Follower: pull from syncedTickerData
        if syncedTimerData then
            local elapsed = GetTime() - (syncTimestamp or 0)
            local seenZones = {}
            for _, timer in ipairs(syncedTimerData) do
                if not seenZones[timer.zone] then
                    local remaining = (timer.remaining - elapsed) % 1097
                    table.insert(timers, {
                        zone = timer.zone,
                        shardID = timer.shardID,
                        duration = 1097,
                        remaining = remaining
                    })
                    seenZones[timer.zone] = true
                    if #timers >= 6 then break end
                end
            end
        end
    end

    return timers
end

local function StartTimersFromTicker()
    if not BBTIMERS or not BBTIMERS.CreateOrResetTimer then return end
    local timers = GetTickerTimers()
    for _, t in ipairs(timers) do
        local start = time() - (t.duration - t.remaining)
        BBTIMERS.CreateOrResetTimer(t.zone, t.shardID, t.duration, start, "PLAYER_LOGIN")
    end
end

f:SetScript("OnEvent", function(_, event)
    if event == "PLAYER_ENTERING_WORLD" or event == "GROUP_ROSTER_UPDATE" then
        C_Timer.After(1.5, function()
            if IsInGroup() or IsInRaid() then
                StartTimersFromTicker()
            end
        end)
    end
end)
