local PT = AhUI
local L = PT.L
PT.ConfirmButtons = PT.ConfirmButtons or {}
local M = PT.ConfirmButtons

M.STYLES = {
    default = {
        name   = L["CONFIRM_STYLE_DEFAULT"],
        ok     = "Interface\\AddOns\\AhUI\\media\\confirm_ok.tga",
        reload = "Interface\\AddOns\\AhUI\\media\\confirm_reload.tga",
    },
    horde = {
        name   = L["CONFIRM_STYLE_HORDE"],
        ok     = "Interface\\AddOns\\AhUI\\media\\horde\\confirm_ok.tga",
        reload = "Interface\\AddOns\\AhUI\\media\\horde\\confirm_reload.tga",
    },
    alliance = {
        name   = L["CONFIRM_STYLE_ALLIANCE"],
        ok     = "Interface\\AddOns\\AhUI\\media\\alliance\\confirm_ok.tga",
        reload = "Interface\\AddOns\\AhUI\\media\\alliance\\confirm_reload.tga",
    },
    midnight = {
        name   = L["CONFIRM_STYLE_MIDNIGHT"],
        ok     = "Interface\\AddOns\\AhUI\\media\\midnight\\confirm_ok.tga",
        reload = "Interface\\AddOns\\AhUI\\media\\midnight\\confirm_reload.tga",
    },
}

M.DEFAULT_EXCLUSIONS = {
    VOTE_BOOT_PLAYER = true,
    GUILD_INVITE = true,
    CONFIRM_BATTLEFIELD_ENTRY = true,
    ADDON_ACTION_FORBIDDEN = true,
    CAMP = true,
    QUIT = true,
    RESURRECT = true,
	CONFIRM_BUY_BANK_TAB = true,
    RESURRECT_NO_SICKNESS = true,
    CONFIRM_UNLEARN_AND_SWITCH_TALENT = true,
    CONFIRM_UPGRADE_ITEM = true,
    SPELL_CONFIRMATION_PROMPT = true,
	SPELL_CONFIRMATION_PROMPT_ALERT = true,
    INSTANCE_BOOT = true,
    CONFIRM_BUY_OUTFIT_SLOT = true,
    USE_BIND = true,
}

local function CopyTableShallow(src)
    local t = {}
    if type(src) == "table" then
        for k, v in pairs(src) do t[k] = v end
    end
    return t
end

local okBtn, okText
local reloadBar
local currentPopup
local okEnabledRuntime = false
local escCatcher

local function EnsureDB()
    AhUI_DB = AhUI_DB or {}
    AhUI_DB.confirmExcludedPopups =
        AhUI_DB.confirmExcludedPopups or CopyTableShallow(M.DEFAULT_EXCLUSIONS)
    AhUI_DB.confirmPopupDecision  = AhUI_DB.confirmPopupDecision or {}

    AhUI_CharConfig = AhUI_CharConfig or {}

PT.config.confirmOK = PT.config.confirmOK ~= false
PT.config.confirmReload = PT.config.confirmReload ~= false
PT.config.confirmButtonStyle = PT.config.confirmButtonStyle or "default"

end

local function EnsureEscCatcher()
    if escCatcher then return end

    escCatcher = CreateFrame("Frame", "AhUI_OK_ESC_Catcher", UIParent)
    escCatcher:Hide()

    tinsert(UISpecialFrames, escCatcher:GetName())
end

function M:GetActiveStyle()
    EnsureDB()
    local key = PT.config.confirmButtonStyle or "default"
    return M.STYLES[key] or M.STYLES.default
end

function M:ApplyStyleToButton(frame, kind)
    if not frame or not frame.icon then return end
    local style = M:GetActiveStyle()
    local tex = (kind == "ok") and style.ok or style.reload
    if not tex then return end
    frame.icon:SetTexture(tex)
    frame.icon:SetTexCoord(0, 1, 0, 1)
    frame.icon:SetAlpha(1)
    frame.icon:Show()
end

function M:ApplyStyle()
    if okBtn then M:ApplyStyleToButton(okBtn, "ok") end
    if reloadBar then M:ApplyStyleToButton(reloadBar, "reload") end
end

function M:IsOKEnabled()
    return PT.config.confirmOK == true
end

function M:IsReloadEnabled()
    return PT.config.confirmReload == true
end

function M:SetOKEnabled(v)
    if v then
        M:EnableOK()
    else
        M:DisableOK()
    end
end

function M:SetReloadEnabled(v)
    if v then
        M:ShowReload()
    else
        M:HideReload()
    end
end

function M:ResetOKExclusions()
    EnsureDB()
    AhUI_DB.confirmExcludedPopups = CopyTableShallow(M.DEFAULT_EXCLUSIONS)
    AhUI_DB.confirmPopupDecision = {}
    
    print(L["CONFIRM_RESET_OK"])
end

function M:GetPopupList()
    EnsureDB()

    local list = {}

    for k in pairs(AhUI_DB.confirmPopupDecision or {}) do
        if not M.DEFAULT_EXCLUSIONS[k] then
            table.insert(list, k)
        end
    end

    table.sort(list)
    return list
end

function M:GetPopupLabel(which)
    if not which then return "" end

    local dialog = StaticPopupDialogs and StaticPopupDialogs[which]
    if dialog and type(dialog.text) == "string" then
        local text = dialog.text

        text = text:gsub("\n", " ")
        text = text:gsub("%%.-[sd]", "...")
        text = text:gsub("%s+", " ")

        if #text > 70 then
            text = text:sub(1, 67) .. "..."
        end

        return text
    end

    return which
end

function M:GetPopupFullText(which)
    if not which then return "" end

    local dialog = StaticPopupDialogs and StaticPopupDialogs[which]
    if not dialog then return which end

    local text = dialog.text

    if type(text) == "function" then

        local ok, result = pcall(text)
        if ok and type(result) == "string" then
            text = result
        else
            return which
        end
    end

    if type(text) ~= "string" then
        return which
    end

    return text
end

function M:IsPopupEnabled(which)
    EnsureDB()
    if AhUI_DB.confirmExcludedPopups[which] then return false end
    local d = AhUI_DB.confirmPopupDecision[which]
    if d == false then return false end
    return true
end

function M:SetPopupEnabled(which, enabled)
    EnsureDB()
    if enabled then
        AhUI_DB.confirmExcludedPopups[which] = nil
        AhUI_DB.confirmPopupDecision[which]  = nil
    else
        AhUI_DB.confirmExcludedPopups[which] = true
        AhUI_DB.confirmPopupDecision[which]  = false
    end
end

local function ShouldExclude(which)
    EnsureDB()
    if not which then return true end

    if AhUI_DB.confirmExcludedPopups and AhUI_DB.confirmExcludedPopups[which] then
        return true
    end

    local d = AhUI_DB.confirmPopupDecision and AhUI_DB.confirmPopupDecision[which]
    if d == false then
        return true
    end

    return false
end

local function CreateOKButton()
    if okBtn then return okBtn end

    local b = CreateFrame("Button", "AhUI_OKConfirmButton", UIParent, "BackdropTemplate")
    b:SetSize(44, 44)
    b:SetFrameStrata("TOOLTIP")
    b:SetFrameLevel(1000)
    b:Hide()

    b:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        tile = true, tileSize = 16,
        insets = { left = 3, right = 3, top = 3, bottom = 3 }
    })
    b:SetBackdropColor(0, 0, 0, 0)

    b.icon = b:CreateTexture(nil, "OVERLAY")
    b.icon:SetAllPoints()

    okText = b:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    okText:SetPoint("CENTER")

b:RegisterForClicks("LeftButtonUp", "RightButtonUp")

b:SetScript("OnClick", function(self, mouseButton)
    if not currentPopup then return end

    local popupName = currentPopup:GetName()

if mouseButton == "RightButton" then
    local cancel = _G[popupName .. "Button2"] or currentPopup.button2

    if cancel and cancel:IsShown() then
        cancel:Click()
    end

    self:Hide()
    currentPopup = nil
    return
end

    if not currentPopup.button1 then return end

    local editBox = _G[popupName .. "EditBox"]
    if editBox then
        local locale = GetLocale()
        if currentPopup.which == "DELETE_GOOD_ITEM"
        or currentPopup.which == "DELETE_GOOD_QUEST_ITEM" then
            editBox:SetText(DELETE_ITEM_CONFIRM_STRING
                or (locale == "ruRU" and "удалить" or "DELETE"))
        elseif currentPopup.which == "UNLEARN_SKILL" then
            editBox:SetText(locale == "ruRU" and "забыть" or "unlearn")
        end
    end

    local which = currentPopup.which
    currentPopup.button1:Click()

    self:Hide()
    currentPopup = nil
end)

b:SetScript("OnUpdate", function(self)
    if not self:IsShown() then return end

    local x, y = GetCursorPosition()
    local scale = UIParent:GetEffectiveScale()

    self:ClearAllPoints()
    self:SetPoint("CENTER", UIParent, "BOTTOMLEFT", x / scale, y / scale)
end)

    okBtn = b
    M:ApplyStyle()
    return b
end

local function ShowOKUnderCursor()
    if not okBtn then CreateOKButton() end
    EnsureEscCatcher()
    escCatcher:Show()
    okBtn:Show()
end

local function HideOK()
    if okBtn then okBtn:Hide() end
    if escCatcher then escCatcher:Hide() end
    currentPopup = nil
end

local function TryAutoFillConfirmText(popup, which)
    local editBox = _G[popup:GetName() .. "EditBox"]
    if not editBox then return end

    local locale = GetLocale()

    if which == "DELETE_GOOD_ITEM"
    or which == "DELETE_GOOD_QUEST_ITEM" then
        editBox:SetText(DELETE_ITEM_CONFIRM_STRING
            or (locale == "ruRU" and "удалить" or "DELETE"))
    elseif which == "UNLEARN_SKILL" then
        editBox:SetText(locale == "ruRU" and "забыть" or "unlearn")
    end
end

local PROTECTED_POPUPS = {
    ADDON_ACTION_FORBIDDEN = true,
    SPELL_CONFIRMATION_PROMPT = true,
    SPELL_CONFIRMATION_PROMPT_ALERT = true,
}

local function TryShowForPopup(which)
    if not okEnabledRuntime then return end
    if not which then return end
    if PROTECTED_POPUPS[which] then return end
    if ShouldExclude(which) then return end

local popup = StaticPopup_FindVisible(which)
local button1 = popup and _G[popup:GetName() .. "Button1"]
if not (popup and popup:IsShown() and button1) then return end

if not button1.__AhUIEnableHooked then
    button1.__AhUIEnableHooked = true
    hooksecurefunc(button1, "Enable", function()
        if okEnabledRuntime and currentPopup == popup and popup:IsShown() then
            ShowOKUnderCursor()
        end
    end)
end
    currentPopup = popup
    currentPopup.which = which
    currentPopup.button1 = button1
	TryAutoFillConfirmText(popup, which)
    ShowOKUnderCursor()
end

hooksecurefunc("StaticPopup_Show", function(which)
    EnsureDB()
    if not PT.config.confirmOK then return end
	if not PROTECTED_POPUPS[which] then
    --print("|cffffd700[AhUI Confirm]|r Popup: |cff00ff00" .. which .. "|r")
end
    TryShowForPopup(which)
end)

hooksecurefunc("StaticPopupSpecial_Show", function(frame)
    EnsureDB()
    if not PT.config.confirmOK then return end
    if not frame then return end
     -- print("|cffffd700[AhUI Confirm]|r Специальный попап: |cff00ff00"
		 -- .. tostring(frame.which) .. "|r")	
    TryShowForPopup(frame.which or "UNKNOWN")
end)

hooksecurefunc("StaticPopup_Hide", function()
    HideOK()
end)

function M:EnableOK()
    EnsureDB()
    okEnabledRuntime = true
    CreateOKButton()
    M:ApplyStyle()
end

function M:DisableOK()
    okEnabledRuntime = false
    HideOK()
end

local function SaveReloadPos()
    AhUI_DB = AhUI_DB or {}
    AhUI_DB.positions = AhUI_DB.positions or {}

    local point, _, relPoint, x, y = reloadBar:GetPoint()
    AhUI_DB.positions.reload = {
        point = point,
        relPoint = relPoint,
        x = x,
        y = y,
    }
end

local function LoadReloadPos()
    reloadBar:ClearAllPoints()

    if AhUI_DB
       and AhUI_DB.positions
       and AhUI_DB.positions.reload
    then
        local p = AhUI_DB.positions.reload
        reloadBar:SetPoint(p.point, UIParent, p.relPoint, p.x, p.y)
    else
        reloadBar:SetPoint("CENTER", UIParent, "CENTER", 300, 0)
    end
end

local function CreateReload()
    if reloadBar then return reloadBar end

    local b = CreateFrame("Button", "AhUI_ReloadButton", UIParent, "BackdropTemplate")
    b:SetSize(50, 50)
    b:SetFrameStrata("TOOLTIP")
    b:SetFrameLevel(900)
    b:SetMovable(true)
    b:SetClampedToScreen(true)

    b:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        tile = true, tileSize = 16,
        insets = { left = 3, right = 3, top = 3, bottom = 3 }
    })
    b:SetBackdropColor(0, 0, 0, 0)

    b.icon = b:CreateTexture(nil, "OVERLAY")
    b.icon:SetAllPoints()

    b:RegisterForDrag("LeftButton")
    b:SetScript("OnDragStart", b.StartMoving)
    b:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
        SaveReloadPos()
    end)

    b:SetScript("OnClick", ReloadUI)

    reloadBar = b
    LoadReloadPos()
    M:ApplyStyle()
    return b
end

function M:ShowReload()
    EnsureDB()
    CreateReload():Show()
end

function M:HideReload()
    if reloadBar then reloadBar:Hide() end
end

local init = CreateFrame("Frame")
init:RegisterEvent("PLAYER_LOGIN")
init:SetScript("OnEvent", function()
    EnsureDB()

if PT.config.confirmOK then
    M:EnableOK()
else
    M:DisableOK()
end

if PT.config.confirmReload then
    M:ShowReload()
else
    M:HideReload()
end

M:ApplyStyle()

end)