local _,ns = ...
local L = ns.L

---------------------------------------------------
-- Panel principal
---------------------------------------------------
local f = CreateFrame("Frame", "AutoScrapKeybindFrame", UIParent, "SettingsFrameTemplate")
f:SetSize(350, 200)
f:SetPoint("CENTER")
f:Hide()
f:RegisterForDrag("LeftButton")
f:EnableMouse(true)
f:SetMovable(true)
f:SetClampedToScreen(true)
f:SetScript("OnDragStart", f.StartMoving)
f:SetScript("OnDragStop", f.StopMovingOrSizing)

-- f.title = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
-- f.title:SetPoint("TOP", 0, 0)
-- f.title:SetText("AutoScrap - Asignar tecla")
f.NineSlice.Text:SetText(L["AutoScrap - Assign Key"])

---------------------------------------------------
-- Texto central
---------------------------------------------------
f.text = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
f.text:SetPoint("TOP", 0, - 40)
-- f.text:SetWidth(420)
f.text:SetJustifyH("CENTER")
-- f.text:SetText("Pulsa el botón de asignar tecla para añadir o quitar objetos a la lista de AutoScrap.\n\nTen cuidado y no pulses una tecla que uses en otro binding o se cambiará a esta función.")

---------------------------------------------------
-- Botón asignar tecla
---------------------------------------------------
local assignBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
assignBtn:SetSize(180, 30)
assignBtn:SetPoint("CENTER", 0, - 20)
assignBtn:SetText(L["— Assign New Key —"])

---------------------------------------------------
-- Botón cerrar abajo
---------------------------------------------------
local closeBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
closeBtn:SetSize(100, 24)
closeBtn:SetPoint("BOTTOM", 0, 10)
closeBtn:SetText(L["Close"])
closeBtn:SetScript("OnClick", function()
    f:Hide()
end)

---------------------------------------------------
-- Listener
---------------------------------------------------
local listening = false
local listener = CreateFrame("Frame", nil, f)
listener:SetAllPoints(f)
listener:EnableKeyboard(false)
listener:Hide()

---------------------------------------------------
-- Actualizar texto según la tecla actual
---------------------------------------------------
local function UpdateKeybindText()
    local key1, key2 = GetBindingKey("AUTOSCRAP_INTERACT_WITH_ITEM")
    local initText = L["Assign a key to manually mark\nitems in your inventory.\n\n"]
    if key1 then
        initText = initText..L["Key assigned: |cFFFFFF00"] .. key1
        if key2 then
            initText = initText .. ", " ..key2
        end
        initText = initText .. "|r"
        f.text:SetText(initText)
    else
        -- f.text:SetText("Pulsa el botón de asignar tecla para añadir o quitar objetos a la lista de AutoScrap.\n\nTen cuidado y no pulses una tecla que uses en otro binding o se cambiará a esta función.")
        f.text:SetText(initText..L["Key assigned: -None-"])
    end
end

local function removeAllOldKeys()
    local numKeys = select("#", GetBindingKey("AUTOSCRAP_INTERACT_WITH_ITEM"))
    if numKeys <= 1 then
        return
    end
    for i = 1, numKeys do
        local key = select(i, GetBindingKey("AUTOSCRAP_INTERACT_WITH_ITEM"))
        if key and key ~= "" then
            SetBinding(key)
        end
    end
end

---------------------------------------------------
-- Funciones para manejar el listener
---------------------------------------------------

local forbidenKeys = {
    ["LMETA"] = true,
	["LSHIFT"] = true,
	["RSHIFT"] = true,
	["BUTTON1"] = true,
    ["BUTTON2"] = true,
	["UNKNOWN"] = true,
    ["LCTRL"] = true,
    ["RCTRL"] = true,
    ["LALT"] = true,
    ["RALT"] = true,
}


local function setKeyBinding(key)
-- limpiar bindings previos de esa acción porque hay más de 2 bindings por acción y se lía
    removeAllOldKeys(key)
    -- asignar nueva tecla a la acción
    SetBinding(key, "AUTOSCRAP_INTERACT_WITH_ITEM")
    -- guardar en el perfil actual (0 = cuenta, 1 = personaje)
    SaveBindings(GetCurrentBindingSet())
end


	-- button:EnableMouse(true)
	-- button:EnableMouseWheel(false)
	-- button:RegisterForClicks("AnyDown")
	-- button:SetScript("OnEnter", Control_OnEnter)
	-- button:SetScript("OnLeave", Control_OnLeave)
	-- button:SetScript("OnClick", Keybinding_OnClick)
	-- button:SetScript("OnKeyDown", Keybinding_OnKeyDown)
	-- button:SetScript("OnMouseDown", Keybinding_OnMouseDown)
	-- button:SetScript("OnMouseWheel", Keybinding_OnMouseWheel)
    
local function DisableListener()
    listening = false
    listener:EnableKeyboard(false)
    listener:EnableMouse(false)
	listener:EnableMouseWheel(false)
    listener:Hide()
    listener:SetScript("OnKeyDown", nil)
    listener:SetScript("OnMouseDown", nil)
    assignBtn:Show() -- asegurar que el botón reaparece
end

local function listenerEventKeys(key)
    if listening then
        if forbidenKeys[key] then return end
        if key ~= "ESCAPE" then
            if IsShiftKeyDown() then
                key = "SHIFT-"..key
            end
            if IsControlKeyDown() then
                key = "CTRL-"..key
            end
            if IsAltKeyDown() then
                key = "ALT-"..key
            end
            setKeyBinding(key)
        end
        UpdateKeybindText()
        DisableListener()
    end
end

local function EnableListener()
    listening = true
    listener:EnableKeyboard(true)
    listener:EnableMouse(true)
	listener:EnableMouseWheel(true)
    listener:Show()
    assignBtn:Hide() -- ocultar el botón mientras espera tecla
    f.text:SetText(L["Click to assign a new key\n\nBe careful not to press a key that\nyou use for another binding, or it will be changed to this function."])
    listener:SetScript("OnKeyDown", function(_, key)
        listenerEventKeys(key)
    end)
    --los botones del ratón funcionan así bien como macro
    --pero para pulsar los objetos del inventario no funcionan
    -- listener:SetScript("OnMouseDown", function(_, button)
        --así que los elimino
        -- if button == "LeftButton" or button == "RightButton" then
        --     return
        -- elseif button == "MiddleButton" then
        --     button = "BUTTON3"
        -- elseif button == "Button4" then
        --     button = "BUTTON4"
        -- elseif button == "Button5" then
        --     button = "BUTTON5"
        -- end
        -- listenerEventKeys(button)
    -- end)
    listener:SetScript("OnMouseWheel", function(_, delta)
        local direction = delta > 0 and "MOUSEWHEELUP" or "MOUSEWHEELDOWN"
        listenerEventKeys(direction)
    end)
end

---------------------------------------------------
-- Eventos abrir/cerrar
---------------------------------------------------
assignBtn:SetScript("OnClick", function()
    EnableListener()
end)

f:SetScript("OnShow", function()
    DisableListener()
    UpdateKeybindText()
end)

f:SetScript("OnHide", function()
    DisableListener()
end)

local function toggleVentana()
    if f:IsShown()then
        f:Hide()
    else
        f:Show()
    end
end
ns.toggleBindingKeyCatcher = toggleVentana