-- ~/.config/nvim/lua/user/cmp.lua

local status_ok, cmp = pcall(require, "cmp")
if not status_ok then
    vim.notify("nvim-cmp not found — run :PackerSync", vim.log.levels.WARN)
    return
end

cmp.setup({
	-- Throttle LSP completion requests.
	-- Default: no debounce → every keystroke fires a compiler pass (CPU heat).
	performance = {
		debounce = 300, -- wait 300ms after typing stops before requesting
		throttle = 500, -- max one completion request every 500ms
		max_view_entries = 30,
	},
	snippet = {
		expand = function(args)
			require("luasnip").lsp_expand(args.body)
		end,
	},
	mapping = cmp.mapping.preset.insert({
		["<C-b>"] = cmp.mapping.scroll_docs(-4),
		["<C-f>"] = cmp.mapping.scroll_docs(4),
		["<C-Space>"] = cmp.mapping.complete(),
		["<CR>"] = cmp.mapping.confirm({ select = true }), -- Confirm selection with Enter

		-- Tab to navigate forward through completion menu
		["<Tab>"] = cmp.mapping(function(fallback)
			if cmp.visible() then
				cmp.select_next_item()
			elseif require("luasnip").expand_or_jumpable() then
				require("luasnip").expand_or_jump()
			else
				fallback()
			end
		end, { "i", "s" }),

		-- Shift-Tab to navigate backward through completion menu
		["<S-Tab>"] = cmp.mapping(function(fallback)
			if cmp.visible() then
				cmp.select_prev_item()
			elseif require("luasnip").jumpable(-1) then
				require("luasnip").jump(-1)
			else
				fallback()
			end
		end, { "i", "s" }),
	}),
	sources = cmp.config.sources({
		{ name = "nvim_lsp" },
		{ name = "luasnip" }, -- Snippet support
	}, {
		{ name = "buffer" }, -- Buffer as a fallback source
	}),
})

-- Ensure that capabilities are extended for LSP
local capabilities = require("cmp_nvim_lsp").default_capabilities(vim.lsp.protocol.make_client_capabilities())
