-- WoWTetris Keybinds
-- Customizable keyboard controls

local addonName, addon = ...

-- Key name mappings for display
local KEY_NAMES = {
    LEFT = "Left Arrow",
    RIGHT = "Right Arrow",
    UP = "Up Arrow",
    DOWN = "Down Arrow",
    SPACE = "Spacebar",
    LCTRL = "Left Ctrl",
    RCTRL = "Right Ctrl",
    LSHIFT = "Left Shift",
    RSHIFT = "Right Shift",
    LALT = "Left Alt",
    RALT = "Right Alt",
    TAB = "Tab",
    ENTER = "Enter",
    BACKSPACE = "Backspace",
    ESCAPE = "Escape",
}

-- Action descriptions
local ACTION_NAMES = {
    moveLeft = "Move Left",
    moveRight = "Move Right",
    softDrop = "Soft Drop",
    hardDrop = "Hard Drop",
    rotateClockwise = "Rotate CW",
    rotateCounterClockwise = "Rotate CCW",
    hold = "Hold Piece",
    pause = "Pause",
    ultimate = "Ultimate",
    pvpAbility = "PvP Sabotage",
    racialAbility = "Racial Ability",
}

-- Action order for display
local ACTION_ORDER = {
    "moveLeft",
    "moveRight",
    "softDrop",
    "hardDrop",
    "rotateClockwise",
    "rotateCounterClockwise",
    "hold",
    "pause",
    "ultimate",
    "pvpAbility",
    "racialAbility",
}

-- Preset keybind configurations
local PRESETS = {
    arrows = {
        name = "Arrow Keys",
        keybinds = {
            moveLeft = "LEFT",
            moveRight = "RIGHT",
            softDrop = "DOWN",
            hardDrop = "SPACE",
            rotateClockwise = "UP",
            rotateCounterClockwise = "LCTRL",
            hold = "C",
            pause = "P",
            ultimate = "R",
            pvpAbility = "V",
            racialAbility = "B",
        }
    },
    wasd = {
        name = "WASD",
        keybinds = {
            moveLeft = "A",
            moveRight = "D",
            softDrop = "S",
            hardDrop = "SPACE",
            rotateClockwise = "W",
            rotateCounterClockwise = "Q",
            hold = "E",
            pause = "P",
            ultimate = "R",
            pvpAbility = "V",
            racialAbility = "B",
        }
    },
    qeArrows = {
        name = "Q/E + Arrows",
        keybinds = {
            moveLeft = "LEFT",
            moveRight = "RIGHT",
            softDrop = "DOWN",
            hardDrop = "SPACE",
            rotateClockwise = "E",
            rotateCounterClockwise = "Q",
            hold = "C",
            pause = "P",
            ultimate = "R",
            pvpAbility = "V",
            racialAbility = "B",
        }
    },
}

-- Get display name for a key
local function GetKeyName(key)
    if not key then return "None" end
    return KEY_NAMES[key] or key
end

-- Initialize keybinds
function addon:InitializeKeybinds()
    local frame = addon.mainFrame
    if not frame then return end
    
    -- Start with NOT propagating - we'll handle our keys
    frame:SetPropagateKeyboardInput(false)
    frame:EnableKeyboard(true)
    
    frame:SetScript("OnKeyDown", function(self, key)
        local handled = addon:HandleKeyDown(key)
        -- Only propagate if we didn't handle this key
        self:SetPropagateKeyboardInput(not handled)
    end)
    
    frame:SetScript("OnKeyUp", function(self, key)
        self:SetPropagateKeyboardInput(false)
    end)
end

-- Handle key down events - returns true if we handled the key
function addon:HandleKeyDown(key)
    local state = addon.gameState
    local keybinds = addon.db.keybinds
    local effects = addon.pvpEffects or {}
    
    -- Check if this is one of our keys
    local isOurKey = false
    for _, boundKey in pairs(keybinds) do
        if key == boundKey then
            isOurKey = true
            break
        end
    end
    
    if not isOurKey then
        return false  -- Let WoW handle it
    end
    
    -- Always allow pause
    if key == keybinds.pause then
        addon:TogglePause()
        return true
    end
    
    -- Don't process other keys if not playing or paused
    if not state.isPlaying or state.isPaused then return true end
    
    -- Check if frozen - block all movement/rotation
    if effects.frozen then
        print("|cff00ffff[Tetris]|r You're FROZEN!")
        return true
    end
    
    -- Ultimate ability
    if key == keybinds.ultimate then
        -- Check if ultimate is disabled by Silence
        if effects.ultimateDisabled then
            print("|cffff0000[Tetris]|r Ultimate is SILENCED!")
            return true
        end
        addon:UseUltimate()
        return true
    end
    
    -- PvP Sabotage ability (only in PvP matches)
    if key == keybinds.pvpAbility then
        if addon.mpState and addon.mpState.inMatch then
            addon:UsePvPAbility()
        end
        return true
    end
    
    -- Racial ability
    if key == keybinds.racialAbility then
        addon:UseRacialAbility()
        return true
    end
    
    -- Handle reversed controls
    local actualKey = key
    if effects.reversedControls then
        if key == keybinds.moveLeft then
            actualKey = keybinds.moveRight
        elseif key == keybinds.moveRight then
            actualKey = keybinds.moveLeft
        elseif key == keybinds.softDrop then
            actualKey = keybinds.hardDrop  -- Down becomes instant drop (punishing!)
        elseif key == keybinds.rotateClockwise then
            actualKey = keybinds.rotateCounterClockwise
        elseif key == keybinds.rotateCounterClockwise then
            actualKey = keybinds.rotateClockwise
        end
    end
    
    -- Game controls (using potentially reversed key)
    if actualKey == keybinds.moveLeft then
        addon:MovePieceLeft()
    elseif actualKey == keybinds.moveRight then
        addon:MovePieceRight()
    elseif actualKey == keybinds.softDrop then
        addon:SoftDrop()
    elseif actualKey == keybinds.hardDrop then
        addon:HardDrop()
    elseif actualKey == keybinds.rotateClockwise then
        addon:RotateClockwise()
    elseif actualKey == keybinds.rotateCounterClockwise then
        addon:RotateCounterClockwise()
    elseif actualKey == keybinds.hold then
        -- Check if hold is disabled
        if effects.holdDisabled then
            print("|cffff0000[Tetris]|r Hold is DISABLED!")
            return true
        end
        addon:HoldPiece()
    end
    
    return true
end


-- Keybind options frame
local keybindFrame

function addon:ShowKeybindOptions()
    if keybindFrame and keybindFrame:IsShown() then
        keybindFrame:Hide()
        return
    end
    
    if not keybindFrame then
        keybindFrame = CreateFrame("Frame", "WoWTetrisKeybindFrame", addon.mainFrame, "BackdropTemplate")
        keybindFrame:SetSize(280, 380)
        keybindFrame:SetPoint("LEFT", addon.mainFrame, "RIGHT", 10, 0)
        keybindFrame:SetBackdrop({
            bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
            edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Gold-Border",
            tile = true, tileSize = 32, edgeSize = 32,
            insets = { left = 8, right = 8, top = 8, bottom = 8 }
        })
        keybindFrame:SetFrameStrata("DIALOG")
        
        -- Title
        local title = keybindFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        title:SetPoint("TOP", keybindFrame, "TOP", 0, -15)
        title:SetText("|cffffffffKeybinds|r")
        
        -- Close button
        local closeBtn = CreateFrame("Button", nil, keybindFrame, "UIPanelCloseButton")
        closeBtn:SetPoint("TOPRIGHT", keybindFrame, "TOPRIGHT", -5, -5)
        closeBtn:SetScript("OnClick", function()
            keybindFrame:Hide()
        end)
        
        -- Preset buttons
        local presetLabel = keybindFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        presetLabel:SetPoint("TOPLEFT", keybindFrame, "TOPLEFT", 20, -40)
        presetLabel:SetText("|cff888888Presets:|r")
        
        local prevPresetBtn = nil
        for _, presetKey in ipairs({"arrows", "wasd", "qeArrows"}) do
            local preset = PRESETS[presetKey]
            local btn = CreateFrame("Button", nil, keybindFrame, "UIPanelButtonTemplate")
            btn:SetSize(75, 22)
            if prevPresetBtn then
                btn:SetPoint("LEFT", prevPresetBtn, "RIGHT", 5, 0)
            else
                btn:SetPoint("TOPLEFT", presetLabel, "BOTTOMLEFT", 0, -5)
            end
            btn:SetText(preset.name)
            btn:SetScript("OnClick", function()
                for action, key in pairs(preset.keybinds) do
                    addon.db.keybinds[action] = key
                end
                addon:UpdateKeybindButtons()
            end)
            prevPresetBtn = btn
        end
        
        -- Keybind buttons
        keybindFrame.buttons = {}
        local yOffset = -100
        
        for _, action in ipairs(ACTION_ORDER) do
            local label = keybindFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
            label:SetPoint("TOPLEFT", keybindFrame, "TOPLEFT", 20, yOffset)
            label:SetText(ACTION_NAMES[action])
            label:SetWidth(100)
            label:SetJustifyH("LEFT")
            
            local btn = CreateFrame("Button", nil, keybindFrame, "UIPanelButtonTemplate")
            btn:SetSize(120, 22)
            btn:SetPoint("TOPLEFT", label, "TOPRIGHT", 10, 3)
            btn.action = action
            
            btn:SetScript("OnClick", function(self)
                -- Start listening for key
                self:SetText("|cff00ff00Press a key...|r")
                self:EnableKeyboard(true)
                self:SetScript("OnKeyDown", function(self, key)
                    if key == "ESCAPE" then
                        -- Cancel
                        self:SetText(GetKeyName(addon.db.keybinds[self.action]))
                    else
                        -- Set new keybind
                        addon.db.keybinds[self.action] = key
                        self:SetText(GetKeyName(key))
                    end
                    self:EnableKeyboard(false)
                    self:SetScript("OnKeyDown", nil)
                end)
            end)
            
            keybindFrame.buttons[action] = btn
            yOffset = yOffset - 30
        end
        
        -- Ghost piece toggle
        local ghostCheck = CreateFrame("CheckButton", nil, keybindFrame, "UICheckButtonTemplate")
        ghostCheck:SetPoint("TOPLEFT", keybindFrame, "TOPLEFT", 15, yOffset - 10)
        ghostCheck.text = ghostCheck:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        ghostCheck.text:SetPoint("LEFT", ghostCheck, "RIGHT", 5, 0)
        ghostCheck.text:SetText("Show Ghost Piece")
        ghostCheck:SetChecked(addon.db.ghostPieceEnabled)
        ghostCheck:SetScript("OnClick", function(self)
            addon.db.ghostPieceEnabled = self:GetChecked()
        end)
        keybindFrame.ghostCheck = ghostCheck
        
        -- Instructions
        local instructions = keybindFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        instructions:SetPoint("BOTTOM", keybindFrame, "BOTTOM", 0, 20)
        instructions:SetText("|cff888888Click a button and press a key to rebind|r")
    end
    
    addon:UpdateKeybindButtons()
    keybindFrame:Show()
end

function addon:UpdateKeybindButtons()
    if not keybindFrame then return end
    
    for action, btn in pairs(keybindFrame.buttons) do
        btn:SetText(GetKeyName(addon.db.keybinds[action]))
    end
    
    keybindFrame.ghostCheck:SetChecked(addon.db.ghostPieceEnabled)
end
