-- completions.lua: Provides intelligent code completion via LSP or snippet engines.
-- completion.lua (nvim-cmp + LuaSnip)

return {
  ------------------------------------------------------------------
  -- 1. Snippet engine & pre-made snippets
  ------------------------------------------------------------------
  {
    "L3MON4D3/LuaSnip",
    version = "v2.*",
    build = "make install_jsregexp",
    dependencies = { "rafamadriz/friendly-snippets" },
    config = function()
      require("luasnip.loaders.from_vscode").lazy_load()
      require("luasnip.loaders.from_lua").load({
        paths = { vim.fn.stdpath("config") .. "/snippets" },
      })
    end,
  },
  --------------------------------------------------------------
  -- 2. Core completion engine + standard sources
  ------------------------------------------------------------------
  {
    "hrsh7th/nvim-cmp",
    dependencies = {
      "hrsh7th/cmp-nvim-lsp",
      "hrsh7th/cmp-buffer",
      "hrsh7th/cmp-path",
      "hrsh7th/cmp-cmdline",
      "hrsh7th/cmp-nvim-lua",
      "micangl/cmp-vimtex",
      "saadparwaiz1/cmp_luasnip",
    },
    ------------------------------------------------------------------
    -- 3. nvim-cmp setup
    ------------------------------------------------------------------
    config = function()
      local cmp = require("cmp")
      local luasnip = require("luasnip")

      cmp.setup({
        snippet = {
          expand = function(args)
            luasnip.lsp_expand(args.body) -- Correctly calls LuaSnip [3]
          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 }),

          -- Fix: Tab now handles expansion and jumping
          ["<Tab>"] = cmp.mapping(function(fallback)
            if cmp.visible() then
              cmp.select_next_item()
            elseif luasnip.expand_or_jumpable() then
              luasnip.expand_or_jump()
            else
              fallback()
            end
          end, { "i", "s" }),

          ["<S-Tab>"] = cmp.mapping(function(fallback)
            if cmp.visible() then
              cmp.select_prev_item()
            elseif luasnip.jumpable(-1) then
              luasnip.jump(-1)
            else
              fallback()
            end
          end, { "i", "s" }),
        }),
        sources = cmp.config.sources({
          { name = "luasnip", priority = 1000 }, -- Priority 2: Standard Snippets
          { name = "nvim_lsp", priority = 750 }, -- Priority 1: LSP (Snippets)
          { name = "vimtex", priority = 500 }, -- Priority 3: Vimtex (Text/Commands)
          { name = "nvim_lua", priority = 250 },
        }, {
          { name = "buffer" },
          { name = "path" },
        }),
      })
    end,
  },
}
