local map = vim.keymap.set

if require("core.util").is_available("which-key") then
	require("which-key").add({
		{ "<localleader>c", group = "codecells" },
		{ "<localleader>e", group = "criticmarkup" },
	})
end

if require("core.util").is_available("zk") and require("zk.util").notebook_root(vim.fn.expand("%:p")) ~= nil then
	map("n", "<CR>", "<cmd>lua vim.lsp.buf.definition()<cr>", { silent = true })
end

-- edit code cells with full lsp access
map("n", "<localleader>ce", "<cmd>FeMaco<cr>", { silent = true, desc = "edit code block" })
-- execute code cells
map("n", "<localleader>cc", "<cmd>MdEval<cr>", { silent = true, desc = "evaluate code block" })
map("n", "<localleader>cx", "<cmd>MdEvalClean<cr>", { silent = true, desc = "clear code results" })

-- jump to beginning of previous/ next cell code
map("n", "]c", "/^```<cr>}:nohl<cr>", { desc = "next code cell" })
map("n", "[c", "?^```<cr>n}:nohl<cr>", { desc = "previous code cell" })
-- insert cell header above/below
map("n", "<localleader>co", "o```python<cr><cr>```<esc>k", { desc = "Insert quarto cell below" })
map("n", "<localleader>cO", "O```python<cr><cr>```<esc>k", { desc = "Insert quarto cell above" })

if require("core.util").is_available("which-key") then
	require("which-key").add({ "<localleader>p", group = "prose" })
end
-- show nice md preview in browser (auto-syncs scrolling)
if require("core.util").is_available("peek") then
	local peek = require("peek")
	local function togglePeek()
		if peek.is_open() then
			peek.close()
		else
			peek.open()
		end
	end
	map("n", "<leader>po", togglePeek, { desc = "show md preview" })
else
	map("n", "<leader>po", "<Plug>MarkdownPreviewToggle", { desc = "show md preview" })
end

-- create mindmaps directly from markdown! requires external executable
if vim.fn.executable("markmap") then
	map("n", "<leader>pm", "<cmd>MarkmapOpen<cr>", { desc = "open md mindmap" })
	map("n", "<leader>pM", "<cmd>MarkmapWatch<cr>", { desc = "watch for md mindmap" })
end
