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 promptLock = false
local lastPromptWhich = nil
local tutorialCancelled = false

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_DB.confirmPrompted       = AhUI_DB.confirmPrompted 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
hooksecurefunc("CloseAllWindows", function()
    if StaticPopup_FindVisible("AHUI_OK_TUTORIAL") then
        tutorialCancelled = true
    end
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 = {}
    AhUI_DB.confirmPrompted = {}
    print(L["CONFIRM_RESET_OK"])
end

StaticPopupDialogs["AHUI_OK_TUTORIAL"] = {
    text = L["CONFIRM_TUTORIAL_TEXT"],
    button1 = L["CONFIRM_TUTORIAL_ACCEPT"],
    button2 = L["CONFIRM_TUTORIAL_CANCEL"],
    timeout = 0,
    whileDead = true,
	hideOnEscape = true,
    preferredIndex = 3,

    OnAccept = function(_, data)
	tutorialCancelled = false
        EnsureDB()
        local which = data and data.which
        if which then
			AhUI_DB.confirmPrompted[which] = true
            AhUI_DB.confirmPopupDecision[which] = true
            AhUI_DB.confirmExcludedPopups[which] = nil
        end
        promptLock = false
        lastPromptWhich = nil
    end,

    OnCancel = function(_, data)
    tutorialCancelled = false
        EnsureDB()
        local which = data and data.which
        if which then
			
            AhUI_DB.confirmPopupDecision[which] = false
            AhUI_DB.confirmExcludedPopups[which] = true
        end
        promptLock = false
        lastPromptWhich = nil
        if okBtn then okBtn:Hide() end
    end,

OnHide = function()
    if tutorialCancelled then
        tutorialCancelled = false
        promptLock = false
        lastPromptWhich = nil
        return
    end

    promptLock = false
    lastPromptWhich = nil
end,

}

local function AttachCancelCross(popup)
    if popup.__AhUICancel then return end

    local btn = CreateFrame("Button", nil, popup, "UIPanelCloseButton")
    btn:SetSize(18, 18)
    btn:SetPoint("TOPRIGHT", popup, "TOPRIGHT", -6, -6)

btn:SetScript("OnClick", function()
    tutorialCancelled = true
    popup:Hide()
end)

    popup.__AhUICancel = btn
end

local function PromptDecision(which)
    EnsureDB()
    if promptLock then return end
    if AhUI_DB.confirmPrompted[which] then return end

    promptLock = true
    lastPromptWhich = which

    StaticPopup_Show("AHUI_OK_TUTORIAL", nil, nil, { which = which })
	local p = StaticPopup_FindVisible("AHUI_OK_TUTORIAL")
	if p then
		AttachCancelCross(p)
	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 which = currentPopup.which

    local cancel =
        _G[popupName .. "Button2"]
        or currentPopup.button2

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

    if AhUI_DB.confirmPopupDecision[which] == nil then
        C_Timer.After(0, function()
            PromptDecision(which)
        end)
    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()

    if AhUI_DB.confirmPopupDecision[which] == nil then
        PromptDecision(which)
    end

    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 or which == "AHUI_OK_TUTORIAL" 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()

    M:ApplyStyle()
end)
