local map = vim.keymap.set

-- Clear search highlighting on Escape
map("n", "<Esc>", "<cmd>nohlsearch<cr>", { silent = true, desc = "Clear search highlight" })

-- Visual line navigation (move by display line over wrapped text)
for _, mode in ipairs({ "n", "x" }) do
    map(mode, "j", "gj", { silent = true, desc = "Down (display line)" })
    map(mode, "k", "gk", { silent = true, desc = "Up (display line)" })
end

-- Hover: native LSP hover (press K again to focus the window).
-- Border comes from the global `winborder` option.
map("n", "K", function() vim.lsp.buf.hover({ max_width = 80 }) end,
    { desc = "LSP: hover docs" })

-- LSP (rename/code-action/references use native gr* defaults on 0.11+)
map("n", "<leader>gf",
    function() require("conform").format({ lsp_format = "fallback" }) end,
    { desc = "LSP: format buffer" })
map("x", "<leader>gs",
    function() require("conform").format({ lsp_format = "fallback" }) end,
    { desc = "LSP: format selection" })
map("n", "<leader>gd", vim.lsp.buf.definition, { desc = "LSP: go to definition" })
map("n", "<leader>gD", vim.lsp.buf.declaration, { desc = "LSP: go to declaration" })

-- Trouble
map("n", "<leader>xx", "<cmd>Trouble diagnostics toggle focus=true<cr>",
    { desc = "Trouble: workspace diagnostics" })
map("n", "<leader>xX", "<cmd>Trouble diagnostics toggle filter.buf=0 focus=true<cr>",
    { desc = "Trouble: buffer diagnostics" })
map("n", "<leader>xt", "<cmd>Trouble todo toggle focus=true<cr>", { desc = "Trouble: todo list" })

-- Pickers / files
map("n", "<C-f>", "<cmd>Pick files<cr>", { desc = "Find: files" })
map("n", "<C-g>", "<cmd>Pick grep_live<cr>", { desc = "Find: grep project (disk)" })
map("n", "<C-S-g>", "<cmd>Pick buf_lines scope='all'<cr>", { desc = "Find: grep open buffers" })
map("n", "<C-b>", "<cmd>Pick buffers<cr>", { desc = "Find: buffers" })
map("n", "<C-h>", "<cmd>Pick help<cr>", { desc = "Find: help tags" })
map("n", "<C-e>", "<cmd>Oil<cr>", { desc = "File explorer (Oil)" })
map("n", "<C-k>", "<cmd>Pick keymaps<cr>", { desc = "Find: keymaps" })

-- DAP
map("n", "<leader>duo", function() require("dapui").open() end, { desc = "Debug: open UI" })
map("n", "<leader>duc", function() require("dapui").close() end, { desc = "Debug: close UI" })
map("n", "<leader>dbp", function() require("dap").toggle_breakpoint() end, { desc = "Debug: toggle breakpoint" })
map("n", "<leader>drc", function() require("dap").run_to_cursor() end, { desc = "Debug: run to cursor" })

-- Spell
map("n", "<leader>sc", function()
    vim.wo.spell = not vim.wo.spell
    vim.notify("Spell: " .. (vim.wo.spell and "ON" or "OFF"))
end, { desc = "Spell: toggle" })

map("n", "<leader>sl", function()
    local cur = vim.opt.spelllang:get()[1] or ""
    local new = cur == "en" and "de" or "en"
    vim.opt.spelllang = new
    vim.notify("Spell lang: " .. new)
end, { desc = "Spell: switch language (en/de)" })
