-- ===================== Alias input popup =====================
StaticPopupDialogs["BPS_ALIAS_PROMPT"] = {
    text = "", -- set dynamically
    button1 = "", -- set dynamically
    hasEditBox = true,
    maxLetters = 16,
    OnShow = function(self)
        local editBox = self.editBox or _G[self:GetName() .. "EditBox"]
        editBox:SetText(BattlePetStatisticsDB.alias or "")
        editBox:HighlightText()
        editBox:SetFocus()
    end,
    OnAccept = function(self)
        local editBox = self.editBox or _G[self:GetName() .. "EditBox"]
        local text = editBox:GetText()
        if text and text ~= "" then
            BattlePetStatisticsDB.alias = text:sub(1, 16)
            BattlePetStatisticsDB.tradeWinEnabled = true
        end
    end,
    EditBoxOnEnterPressed = function(self)
        local parent = self:GetParent()
        local text = self:GetText()
        if text and text ~= "" then
            BattlePetStatisticsDB.alias = text:sub(1, 16)
            BattlePetStatisticsDB.tradeWinEnabled = true
        end
        parent:Hide()
    end,
    EditBoxOnEscapePressed = function(self)
        self:GetParent():Hide()
    end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}

-- Returns true if the player's pets have already been custom-renamed by this
-- addon (i.e. the first battle pet's name no longer matches its species name).
local function IsFirstPetAlreadyRenamed()
    if not C_PetJournal or not C_PetJournal.GetPetLoadOutInfo or not C_PetJournal.GetPetInfoByPetID then
        return false
    end
    local ok, petID = pcall(C_PetJournal.GetPetLoadOutInfo, 1)
    if not ok or not petID then return false end
    local ok2, _, customName = pcall(C_PetJournal.GetPetInfoByPetID, petID)
    return ok2 and customName ~= nil and customName ~= ""
end

local function ShowAliasPopup()
    local L = BPS_GetLocale()
    local d2 = StaticPopupDialogs["BPS_ALIAS_PROMPT"]
    d2.text = L.ALIAS_PROMPT_TITLE
    d2.button1 = L.ALIAS_VALIDATE
    StaticPopup_Show("BPS_ALIAS_PROMPT")
end

-- Called once per login, a few seconds after entering the world. Whether the
-- alias popup actually appears depends on BattlePetStatisticsDB.showWindowMode,
-- set in the Options tab:
--   "startup"            -> always show at login
--   "after_first_battle" -> don't show here; BPS_MaybeShowAliasAfterBattle
--                            handles it once the first PvP battle resolves
--   "never"              -> never show
--   "if_not_renamed"     -> only show if the pets aren't already renamed
function BPS_MaybeShowSetupPrompt()
    EnsureDB()
    local mode = BattlePetStatisticsDB.showWindowMode

    if mode == "after_first_battle" or mode == "never" then return end

    if mode == "if_not_renamed" then
        if IsFirstPetAlreadyRenamed() then return end
        ShowAliasPopup()
        return
    end

    -- "startup" (default)
    ShowAliasPopup()
end

-- Called right after the first PvP pet battle of the login session resolves.
-- Only relevant when showWindowMode == "after_first_battle".
function BPS_MaybeShowAliasAfterBattle()
    EnsureDB()
    if BattlePetStatisticsDB.showWindowMode ~= "after_first_battle" then return end
    ShowAliasPopup()
end

-- Forces the alias popup open regardless of showWindowMode. Used by the
-- "/bps setup" slash command so the player can always reconfigure manually.
function BPS_ForceShowAliasPopup()
    EnsureDB()
    ShowAliasPopup()
end

-- ===================== Pet renaming at end of battle =====================
-- Renames the player's first 3 active battle pets according to the alias,
-- as a way to let opponents who also run this addon identify the player
-- reliably (pet species can vary battle to battle, a custom name doesn't).
function BPS_RenameOwnPetsForTradeWin()
    if not BattlePetStatisticsDB.tradeWinEnabled then return end
    local alias = BattlePetStatisticsDB.alias
    if not alias or alias == "" then return end

    if not C_PetJournal or not C_PetJournal.GetPetLoadOutInfo or not C_PetJournal.SetCustomName then
        return
    end

    local pet1Name
    if #alias < 7 then
        pet1Name = string.format("(%s) TradeWin", alias)
    else
        pet1Name = alias
    end

    local names = { pet1Name, "TradeWin", "I Need To Win" }

    for slot = 1, 3 do
        local ok, petID = pcall(C_PetJournal.GetPetLoadOutInfo, slot)
        if ok and petID then
            -- Skip the call entirely if the pet already has this name
            -- (case-insensitive, so a pre-existing pet named slightly
            -- differently in case isn't needlessly re-renamed). Re-sending
            -- SetCustomName on an already-correctly-named pet is the trigger
            -- for Blizzard's intermittent "invalid characters" error on some
            -- accounts, even with a perfectly valid name.
            local ok2, _, currentName = pcall(C_PetJournal.GetPetInfoByPetID, petID)
            local matches = ok2 and currentName and currentName:lower() == names[slot]:lower()
            if not matches then
                pcall(C_PetJournal.SetCustomName, petID, names[slot])
            end
        end
    end
end

-- Restores the player's first 3 active battle pets to their default (no
-- custom name) state. Called on logout when
-- BattlePetStatisticsDB.restoreNamesOnLogout is enabled in the Options tab.
function BPS_RestoreOwnPetNames()
    if not C_PetJournal or not C_PetJournal.GetPetLoadOutInfo or not C_PetJournal.SetCustomName then
        return
    end
    for slot = 1, 3 do
        local ok, petID = pcall(C_PetJournal.GetPetLoadOutInfo, slot)
        if ok and petID then
            -- Passing an empty string clears the custom name in the Pet Journal API.
            pcall(C_PetJournal.SetCustomName, petID, "")
        end
    end
end
