-- =========================================================================
-- ArenaCore Conflict Checker
-- Because running two arena frame addons at once is like bringing two
-- healers to a rated match -- someone's gonna get upset and nothing works.
-- =========================================================================

local AC = _G.ArenaCore
if not AC then return end

AC.ConflictChecker = {}
local CC = AC.ConflictChecker

-- Conflicting addon names we watch for (must match folder name exactly)
local CONFLICTING_ADDONS = {
    "sArena_Reloaded",
}

-- Pretty names shown to the user (key = folder name, value = display name)
local DISPLAY_NAMES = {
    ["sArena_Reloaded"] = "sArena Reloaded",
}

local function GetDisplayName(folderName)
    return DISPLAY_NAMES[folderName] or folderName
end

-- We'll stash state on AC so it's easy to check everywhere
AC._conflictDetected = false
AC._conflictAddonName = nil

-- -------------------------------------------------------------------------
-- Detection helpers
-- -------------------------------------------------------------------------

local function IsAddonEnabledAndLoaded(name)
    -- loaded means it's turned on and Blizzard loaded it this session
    local loaded = C_AddOns and C_AddOns.IsAddOnLoaded and C_AddOns.IsAddOnLoaded(name)
    if loaded then
        return true, name
    end
    return false, nil
end

local function ScanForConflicts()
    for _, name in ipairs(CONFLICTING_ADDONS) do
        local found, foundName = IsAddonEnabledAndLoaded(name)
        if found then
            return true, foundName
        end
    end
    return false, nil
end

-- -------------------------------------------------------------------------
-- Popup creation (ArenaCore styled, not Blizzard StaticPopup)
-- -------------------------------------------------------------------------

local function CreateConflictPopup()
    if CC.popupFrame then
        return CC.popupFrame
    end

    local f = CreateFrame("Frame", "ArenaCoreConflictPopup", UIParent, "BackdropTemplate")
    f:SetSize(460, 290)
    f:SetPoint("CENTER", 0, 80)
    f:SetFrameStrata("DIALOG")
    f:SetFrameLevel(200)
    f:EnableMouse(true)
    f:SetMovable(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)

    -- Backdrop
    f:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 1,
        insets = { left = 1, right = 1, top = 1, bottom = 1 }
    })
    f:SetBackdropColor(0.12, 0.12, 0.12, 1)
    f:SetBackdropBorderColor(0.3, 0.3, 0.3, 1)

    -- Top accent bar (ArenaCore purple)
    local accent = f:CreateTexture(nil, "BORDER")
    accent:SetPoint("TOPLEFT", 1, -1)
    accent:SetPoint("TOPRIGHT", -1, -1)
    accent:SetHeight(3)
    accent:SetColorTexture(0.545, 0.271, 1, 1)

    -- Warning icon
    local icon = f:CreateTexture(nil, "ARTWORK")
    icon:SetSize(48, 48)
    icon:SetPoint("TOP", 0, -24)
    icon:SetAtlas("Crosshair_Important_128")
    icon:SetVertexColor(1, 0.6, 0, 1)

    -- Title
    local title = f:CreateFontString(nil, "OVERLAY")
    title:SetFont(AC.FONT_PATH or "Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 16, "OUTLINE")
    title:SetText("Conflicting AddOn Detected")
    title:SetTextColor(1, 0.6, 0, 1)
    title:SetPoint("TOP", icon, "BOTTOM", 0, -10)

    -- Body text
    local body = f:CreateFontString(nil, "OVERLAY")
    body:SetFont(AC.FONT_PATH or "Fonts\\FRIZQT__.TTF", 12, "")
    body:SetTextColor(0.9, 0.9, 0.9, 1)
    body:SetWidth(400)
    body:SetJustifyH("CENTER")
    body:SetSpacing(4)
    body:SetText(string.format(
        "|cffFF7A18%s|r is currently enabled and conflicts with ArenaCore.\n\n"
        .. "You must disable the conflicting addon before ArenaCore can function.",
        GetDisplayName(AC._conflictAddonName or "sArena_Reloaded")
    ))
    body:SetPoint("TOP", title, "BOTTOM", 0, -14)

    -- Close button (X) top-right
    local closeBtn = CreateFrame("Button", nil, f, "BackdropTemplate")
    closeBtn:SetSize(28, 28)
    closeBtn:SetPoint("TOPRIGHT", -6, -6)
    closeBtn:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        tile = true, tileSize = 16
    })
    closeBtn:SetBackdropColor(0.863, 0.176, 0.176, 1)
    local closeText = closeBtn:CreateFontString(nil, "OVERLAY")
    closeText:SetFont(AC.FONT_PATH or "Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 16, "")
    closeText:SetText("×")
    closeText:SetTextColor(1, 1, 1, 1)
    closeText:SetPoint("CENTER", 0, 1)
    closeBtn:SetScript("OnEnter", function(self)
        self:SetBackdropColor(1, 0.4, 0.4, 1)
    end)
    closeBtn:SetScript("OnLeave", function(self)
        self:SetBackdropColor(0.863, 0.176, 0.176, 1)
    end)
    closeBtn:SetScript("OnClick", function()
        f:Hide()
    end)

    -- "Turn off conflicting addons then Reload" button
    local actionBtn = CreateFrame("Button", nil, f, "BackdropTemplate")
    actionBtn:SetSize(280, 34)
    actionBtn:SetPoint("TOP", body, "BOTTOM", 0, -24)
    actionBtn:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        tile = true, tileSize = 16
    })
    actionBtn:SetBackdropColor(0.545, 0.271, 1, 1)

    local actionText = actionBtn:CreateFontString(nil, "OVERLAY")
    actionText:SetFont(AC.FONT_PATH or "Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 12, "")
    actionText:SetText("Turn off conflicting addons then Reload")
    actionText:SetTextColor(1, 1, 1, 1)
    actionText:SetPoint("CENTER")

    actionBtn:SetScript("OnEnter", function(self)
        self:SetBackdropColor(0.65, 0.37, 1, 1)
    end)
    actionBtn:SetScript("OnLeave", function(self)
        self:SetBackdropColor(0.545, 0.271, 1, 1)
    end)

    actionBtn:SetScript("OnClick", function()
        -- Show confirmation before we start disabling things
        CC:ShowConfirmDialog(function(confirmed)
            if confirmed then
                local target = AC._conflictAddonName
                if target and C_AddOns and C_AddOns.DisableAddOn then
                    C_AddOns.DisableAddOn(target)
                end
                ReloadUI()
            end
            -- If cancelled, just close the confirmation and keep popup open
        end)
    end)

    -- Optional: subtle footer text
    local footer = f:CreateFontString(nil, "OVERLAY")
    footer:SetFont(AC.FONT_PATH or "Fonts\\FRIZQT__.TTF", 10, "")
    footer:SetTextColor(0.5, 0.5, 0.5, 1)
    footer:SetText("ArenaCore will remain disabled until the conflict is resolved.")
    footer:SetPoint("BOTTOM", 0, 16)

    CC.popupFrame = f
    return f
end

-- -------------------------------------------------------------------------
-- Confirmation dialog (small modal over the popup)
-- -------------------------------------------------------------------------

function CC:ShowConfirmDialog(onResult)
    if self.confirmFrame and self.confirmFrame:IsShown() then
        return
    end

    local parent = self.popupFrame or UIParent
    local c = CreateFrame("Frame", "ArenaCoreConflictConfirm", parent, "BackdropTemplate")
    c:SetSize(360, 140)
    c:SetPoint("CENTER", parent, "CENTER", 0, 0)
    c:SetFrameStrata("FULLSCREEN_DIALOG")
    c:SetFrameLevel(250)
    c:EnableMouse(true)

    c:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 1,
        insets = { left = 1, right = 1, top = 1, bottom = 1 }
    })
    c:SetBackdropColor(0.1, 0.1, 0.1, 1)
    c:SetBackdropBorderColor(0.4, 0.4, 0.4, 1)

    local accent = c:CreateTexture(nil, "BORDER")
    accent:SetPoint("TOPLEFT", 1, -1)
    accent:SetPoint("TOPRIGHT", -1, -1)
    accent:SetHeight(2)
    accent:SetColorTexture(0.545, 0.271, 1, 1)

    local msg = c:CreateFontString(nil, "OVERLAY")
    msg:SetFont(AC.FONT_PATH or "Fonts\\FRIZQT__.TTF", 12, "")
    msg:SetTextColor(0.9, 0.9, 0.9, 1)
    msg:SetWidth(320)
    msg:SetJustifyH("CENTER")
    msg:SetText(string.format(
        "This will disable |cffFF7A18%s|r and reload your UI.\nAre you sure?",
        GetDisplayName(AC._conflictAddonName or "sArena_Reloaded")
    ))
    msg:SetPoint("TOP", 0, -28)

    local function makeBtn(text, color, anchorTo, anchorOffsetX, onClick)
        local btn = CreateFrame("Button", nil, c, "BackdropTemplate")
        btn:SetSize(100, 26)
        btn:SetPoint("TOP", anchorTo, "BOTTOM", anchorOffsetX, -16)
        btn:SetBackdrop({
            bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
            tile = true, tileSize = 16
        })
        btn:SetBackdropColor(color[1], color[2], color[3], 1)

        local t = btn:CreateFontString(nil, "OVERLAY")
        t:SetFont(AC.FONT_PATH or "Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 12, "")
        t:SetText(text)
        t:SetTextColor(1, 1, 1, 1)
        t:SetPoint("CENTER")

        btn:SetScript("OnEnter", function(self)
            self:SetBackdropColor(math.min(color[1] + 0.1, 1), math.min(color[2] + 0.1, 1), math.min(color[3] + 0.1, 1), 1)
        end)
        btn:SetScript("OnLeave", function(self)
            self:SetBackdropColor(color[1], color[2], color[3], 1)
        end)
        btn:SetScript("OnClick", function()
            c:Hide()
            c:SetParent(nil)
            onClick()
        end)
        return btn
    end

    makeBtn("OK", {0.133, 0.667, 0.267, 1}, msg, -55, function()
        if type(onResult) == "function" then
            onResult(true)
        end
    end)

    makeBtn("Cancel", {0.863, 0.176, 0.176, 1}, msg, 55, function()
        if type(onResult) == "function" then
            onResult(false)
        end
    end)

    self.confirmFrame = c
    c:Show()
end

-- -------------------------------------------------------------------------
-- Hooks to block ArenaCore while conflict exists
-- -------------------------------------------------------------------------

local function BlockArenaCore()
    if CC._blockApplied then return end
    CC._blockApplied = true

    AC._conflictDetected = true

    -- Capture the REAL OpenConfigPanel (UI.lua's version by PLAYER_LOGIN)
    if not CC._originalOpenConfigPanel then
        CC._originalOpenConfigPanel = AC.OpenConfigPanel
    end

    -- Our wrapper: shows popup when conflict is active, otherwise delegates
    local function ConflictWrapper(self, toggle)
        if AC._conflictDetected then
            if CC.popupFrame then
                CC.popupFrame:Show()
            else
                CreateConflictPopup():Show()
            end
            return
        end
        -- No conflict -- pass through to the real config panel
        if CC._originalOpenConfigPanel then
            CC._originalOpenConfigPanel(self, toggle)
        end
    end

    AC.OpenConfigPanel = ConflictWrapper
    CC._blockWrappedFunc = ConflictWrapper

    -- Failsafe: patch the slash command directly so nothing can bypass us
    if SlashCmdList and SlashCmdList.ARENACORE then
        if not CC._originalSlashHandler then
            CC._originalSlashHandler = SlashCmdList.ARENACORE
        end
        SlashCmdList.ARENACORE = function(msg)
            if AC._conflictDetected then
                if CC.popupFrame then
                    CC.popupFrame:Show()
                else
                    CreateConflictPopup():Show()
                end
                return
            end
            if CC._originalSlashHandler then
                CC._originalSlashHandler(msg)
            end
        end
    end

    -- Safety net: if something overwrites our wrapper after this, slap it back
    C_Timer.After(1, function()
        if AC._conflictDetected and AC.OpenConfigPanel ~= CC._blockWrappedFunc then
            AC.OpenConfigPanel = CC._blockWrappedFunc
        end
    end)

    -- Also block any test mode / frame manager activity if it exists
    if AC.FrameManager and AC.FrameManager.DisableTestMode then
        pcall(function() AC.FrameManager:DisableTestMode() end)
    end
end

-- -------------------------------------------------------------------------
-- Public API
-- -------------------------------------------------------------------------

function CC:CheckAndBlock()
    local hasConflict, addonName = ScanForConflicts()
    if not hasConflict then
        return false
    end

    AC._conflictDetected = true
    AC._conflictAddonName = addonName

    BlockArenaCore()

    -- Show popup immediately
    local popup = CreateConflictPopup()
    popup:Show()

    -- Let the user know in chat too (once)
    if not CC._chatNotified then
        CC._chatNotified = true
        print(string.format(
            "|cffFF0000[ArenaCore]|r Conflicting addon detected: |cffFF7A18%s|r. "
            .. "ArenaCore has been disabled. Disable the conflicting addon and reload to use ArenaCore.",
            GetDisplayName(addonName)
        ))
    end

    return true
end

function CC:IsConflictActive()
    return AC._conflictDetected == true
end

-- -------------------------------------------------------------------------
-- Early event registration
-- -------------------------------------------------------------------------

local checkerFrame = CreateFrame("Frame")
checkerFrame:RegisterEvent("PLAYER_LOGIN")
checkerFrame:SetScript("OnEvent", function(_, event)
    if event == "PLAYER_LOGIN" then
        CC:CheckAndBlock()
    end
end)
