-- Autocompletion engine with LSP, snippet, buffer, and path sources.
-- Keymaps: Tab/S-Tab (navigate), Enter (confirm), Ctrl-Space (trigger), Esc (dismiss).
-- See README.md "Autocomplete" section for full usage details.
return {
  "hrsh7th/nvim-cmp",
  dependencies = {
    "hrsh7th/cmp-nvim-lsp", -- LSP completion source
    "hrsh7th/cmp-buffer", -- Buffer word completion source
    "hrsh7th/cmp-path", -- Filesystem path completion source
    "saadparwaiz1/cmp_luasnip", -- Snippet completion source (bridges LuaSnip)
    "L3MON4D3/LuaSnip", -- Snippet engine
    "onsails/lspkind-nvim", -- Completion menu icons
  },
  config = function()
    local cmp = require("cmp")
    local luasnip = require("luasnip")
    local lspkind = require("lspkind")

    cmp.setup({
      snippet = {
        expand = function(args)
          luasnip.lsp_expand(args.body)
        end,
      },
      mapping = cmp.mapping.preset.insert({
        ["<Tab>"] = cmp.mapping.select_next_item({ behavior = cmp.SelectBehavior.Select }),
        ["<S-Tab>"] = cmp.mapping.select_prev_item({ behavior = cmp.SelectBehavior.Select }),
        ["<CR>"] = cmp.mapping.confirm({ select = true }),
        ["<C-Space>"] = cmp.mapping.complete(),
        ["<Esc>"] = cmp.mapping.abort(),
      }),
      sources = cmp.config.sources({
        { name = "nvim_lsp" },
        { name = "luasnip" },
        {
          name = "buffer",
          keyword_length = 2,
          option = {
            get_bufnrs = function()
              local bufs = {}
              for _, buf in ipairs(vim.api.nvim_list_bufs()) do
                if vim.api.nvim_buf_is_loaded(buf) then
                  bufs[#bufs + 1] = buf
                end
              end
              return bufs
            end,
          },
        },
        { name = "path" },
      }),
      formatting = {
        format = lspkind.cmp_format({
          mode = "symbol_text",
          menu = {
            nvim_lsp = "[LSP]",
            luasnip = "[Snippet]",
            buffer = "[Buffer]",
            path = "[Path]",
          },
        }),
      },
      window = {
        documentation = cmp.config.window.bordered(),
      },
    })

  end,
}
