-- ============================================================================
-- Vamoose's Companion - Pet Summoner
-- Auto-summons linked battle pets when switching companions
-- ============================================================================

VC = VC or {}
VC.PetSummoner = {}

function VC.PetSummoner:Initialize()
    self._lastSummoned = nil
    self._pendingSummon = nil
    self._manualOverride = false
    self._lastCompanion = nil

    local f = CreateFrame("Frame")
    self._frame = f

    -- Companion switch detection via VC_STATE_CHANGED
    VC.EventBus:Register("VC_STATE_CHANGED", function(data)
        local current = data.state.config.activeCompanion
        if current ~= self._lastCompanion then
            self._lastCompanion = current
            self:OnCompanionChanged(current)
        end
    end)

    -- Event wiring for auto-resummon + combat deferral
    f:RegisterEvent("PLAYER_REGEN_ENABLED")
    f:RegisterEvent("PLAYER_ENTERING_WORLD")
    f:RegisterEvent("UNIT_EXITED_VEHICLE")
    f:RegisterEvent("PET_BATTLE_CLOSE")
    f:RegisterEvent("UPDATE_SUMMONPETS_ACTION")

    f:SetScript("OnEvent", function(_, event, arg1)
        if event == "PLAYER_REGEN_ENABLED" then
            if self._pendingSummon then
                self:TrySummon(self._pendingSummon)
                self._pendingSummon = nil
            end

        elseif event == "PLAYER_ENTERING_WORLD" or event == "PET_BATTLE_CLOSE"
            or (event == "UNIT_EXITED_VEHICLE" and arg1 == "player") then
            local state = VC.Store:GetState()
            if state.config.autoResummon and not self._manualOverride then
                local petGUID = state.config.linkedPets[state.config.activeCompanion]
                if petGUID then
                    C_Timer.After(1.0, function() self:TrySummon(petGUID) end)
                end
            end

        elseif event == "UPDATE_SUMMONPETS_ACTION" then
            -- Detect manual pet summons (player overrode our linked pet)
            local newPet = C_PetJournal.GetSummonedPetGUID()
            if newPet and newPet ~= self._lastSummoned then
                self._manualOverride = true
            elseif not newPet and self._lastSummoned then
                -- Player dismissed what we summoned — also an override
                self._manualOverride = true
                self._lastSummoned = nil
            end
        end
    end)

    -- Initialize tracking from current state
    local state = VC.Store:GetState()
    self._lastCompanion = state.config.activeCompanion
end

function VC.PetSummoner:TrySummon(petGUID)
    if not petGUID then return end
    if not VC.Store:GetState().config.autoSummonEnabled then return end
    if InCombatLockdown() then
        self._pendingSummon = petGUID
        return
    end
    local isSummonable = C_PetJournal.GetPetSummonInfo(petGUID)
    if not isSummonable then return end
    local start = C_PetJournal.GetSummonBattlePetCooldown()
    if start ~= 0 then
        C_Timer.After(1.5, function() self:TrySummon(petGUID) end)
        return
    end
    local current = C_PetJournal.GetSummonedPetGUID()
    if current == petGUID then return end -- already out
    C_PetJournal.SummonPetByGUID(petGUID)
    self._lastSummoned = petGUID
end

function VC.PetSummoner:OnCompanionChanged(companionKey)
    self._manualOverride = false -- reset on companion switch
    local state = VC.Store:GetState()
    local petGUID = state.config.linkedPets[companionKey]
    if petGUID then
        self:TrySummon(petGUID)
    elseif state.config.autoSummonEnabled then
        -- No linked pet for this companion — dismiss current if we summoned it
        local current = C_PetJournal.GetSummonedPetGUID()
        if current and self._lastSummoned == current then
            C_PetJournal.SummonPetByGUID(current) -- toggles = dismiss
            self._lastSummoned = nil
        end
    end
end
