{ lib, ... }: let
  inherit (lib.generators) mkLuaInline;
in {
  imports = [
    ./commit-message
    ./git
    ./insert_file_path.nix
  ];
  nixpkgs.overlays = [(final: prev: {
    vimPlugins = prev.vimPlugins // {
      snacks-nvim = prev.vimPlugins.snacks-nvim.overrideAttrs (old: {
        patches = (old.patches or [ ]) ++ [
          # Upstream fix: https://github.com/folke/snacks.nvim/pull/2999
          ./tags-nomagic.patch
        ];
      });
    };
  })];
  my.nvim.snacks.setupArgs = {
    picker = {
      # Always open results in the invoking window. The default main.file = true
      # skips help and other non-file buffers, unexpectedly using another window.
      main.current = true;
      previewers.diff.style = "syntax";
      actions = {
        # Snacks ships toggle_input and toggle_preview but no toggle_list, though
        # Picker:toggle accepts "input"|"list"|"preview".
        toggle_list = mkLuaInline /*lua*/''function(picker)
          if picker.resolved_layout.preset == "my_vertical" then
            local layout = picker.layout
            -- Release the preview's fixed share while the list is hidden.
            layout.opts.layout[1].height = layout:is_hidden("list") and picker.resolved_layout.layout[1].height or nil
          end
          return picker:toggle("list")
        end'';
      } // (let
        gen_preview_scroll_line = down: mkLuaInline /*lua*/ ''function(picker)
          local win = picker.preview.win
          if win:valid() then
            vim.api.nvim_win_call(win.win, function()
              vim.cmd("normal! " .. vim.keycode("${if down then "<C-e>" else "<C-y>"}"))
            end)
          end
        end'';
      in {
        # Snacks' preview_scroll_up/down step by the preview's 'scroll' option (half a page).
        # These move a single line, so the Shift+Up/Down keys stay fine-grained and
        # <c-f>/<c-b> keep their half-page step.
        preview_scroll_line_up = gen_preview_scroll_line false;
        preview_scroll_line_down = gen_preview_scroll_line true;
      }) // (let
        # Both my_vertical and select declare their panes in top-to-bottom order.
        gen_focus_vertical = dir: mkLuaInline /*lua*/ ''function(picker)
          local layout = picker.resolved_layout.layout
          local current = picker:current_win()
          for i, child in ipairs(layout) do
            if child.win == current then
              for j = i + ${dir}, ${if dir == "1" then "#layout" else "1"}, ${dir} do
                local name = layout[j].win
                local win = picker.layout.wins[name]
                if win and win:valid() and not picker.layout:is_hidden(name) then
                  return win:focus()
                end
              end
              return
            end
          end
        end'';
      in {
        focus_up = gen_focus_vertical "-1";
        focus_down = gen_focus_vertical "1";
      });
      win = {
        input = {
          keys = {
            # Scroll the preview without leaving the prompt.
            "<S-Up>" = mkLuaInline ''{ "preview_scroll_line_up", mode = { "n", "i" } }'';
            "<S-Down>" = mkLuaInline ''{ "preview_scroll_line_down", mode = { "n", "i" } }'';
            "<a-up>" = mkLuaInline ''{ "focus_up", mode = { "n", "i" } }'';
            "<a-down>" = mkLuaInline ''{ "focus_down", mode = { "n", "i" } }'';
            "<a-l>" = mkLuaInline ''{ "toggle_list", mode = { "n", "i" } }'';
          };
        };
        list = {
          keys = {
            "<S-Up>" = "list_scroll_up";
            "<S-Down>" = "list_scroll_down";
            "<a-up>" = "focus_up";
            "<a-down>" = "focus_down";
            "<a-l>" = "toggle_list";
          };
          wo = {
            # Global list window config: show ">" on cursor line as current-item indicator
            # for all picker layouts, not only the custom my_vertical preset.
            statuscolumn = "%#SnacksPickerListCursorLine#%{v:relnum==0?\">\":\" \"}%*";
          };
        };
        # The preview is a normal buffer, so these keys are normal mode only.
        preview = {
          keys = {
            "<a-up>" = "focus_up";
            "<a-down>" = "focus_down";
            "<a-l>" = "toggle_list";
          };
        };
      };
      config = mkLuaInline /*lua*/''function(opts)
        -- The source declares which input keys to advertise; the merged config says what they do.
        local keys = opts.source and vim.tbl_get(opts.sources, opts.source, "win", "input", "keys") or {}
        local hints = {}
        for lhs, declared in pairs(keys) do
          local spec = opts.win.input.keys[lhs]
          if declared and spec and lhs ~= "?" then
            local label = type(spec) == "table" and (spec.desc or spec[2] or spec[1]) or spec
            if type(label) == "table" then
              label = table.concat(vim.tbl_filter(function(v) return type(v) == "string" end, label), ", ")
            end
            hints[#hints + 1] = type(label) == "string" and label ~= "" and (lhs .. " " .. label) or lhs
          end
        end
        table.sort(hints)
        hints[#hints + 1] = "? All keys"
        opts.layouts.my_vertical.layout.footer = { { table.concat(hints, "  "), "NonText" } }
      end'';
      layouts = {
        # custom presets
        my_vertical = {
          layout = mkLuaInline /*lua*/''{
            backdrop = false,
            box = "vertical",
            border = true,
            title = "{title} {live} {flags}",
            title_pos = "center",
            -- Top to bottom: preview, input, list. Without `reverse`, list items run
            -- downwards, so list_down matches the screen now that the list sits at the bottom.
            { win = "preview", title = "{preview}", border = "bottom", height = 0.7 },
            { win = "input", height = 1 },
            { win = "list", border = "top" },
          }'';
          fullscreen = true;
        };
      };
      # Global Config
      # Keep the global layout behind a named preset instead of defining the
      # full layout table here. Per-source layouts (e.g. ui.select) are
      # deep-merged with the global layout; if the global value contains layout
      # children directly, source presets inherit those children and may not
      # resolve cleanly. A preset reference lets sources override with their own
      # preset, such as the built-in "select" layout.
      layout = { preset = "my_vertical"; cycle = false; };
      # Per-source Config
      sources = {
        # Snacks' LSP sources opt in to jump.reuse_win = true, which moves focus to
        # a window that already shows the target file instead of replacing the
        # current buffer. Keep jumps in the current window.
        lsp_definitions.jump.reuse_win = false;
        lsp_declarations.jump.reuse_win = false;
        lsp_type_definitions.jump.reuse_win = false;
        lsp_implementations.jump.reuse_win = false;
        lsp_references.jump.reuse_win = false;
      };
    };
  };
  my.nvim.snacks.extraLuaConfig = /*lua*/ ''
    do
      function get_buffer_dir()
        local file = vim.api.nvim_buf_get_name(0)
        return file ~= "" and vim.fs.dirname(file) or nil
      end

      -- f
      vim.keymap.set('n', "<space>f", function() Snacks.picker.files({ cwd = get_buffer_dir() }) end)
      vim.keymap.set('n', "<space>F", function() Snacks.picker.files() end)
      vim.keymap.set('n', "<space>b", function() Snacks.picker.buffers() end)
      -- s
      vim.keymap.set('n', "<space>g", function() Snacks.picker.grep({ cwd = get_buffer_dir() }) end)
      vim.keymap.set('n', "<space>G", function() Snacks.picker.grep() end)
      vim.keymap.set('n', "<space>h", function() Snacks.picker.help() end)

      vim.keymap.set('n', '<space>c', function() Snacks.picker.command_history() end)
      vim.keymap.set('n', '<space>C', function() Snacks.picker.commands() end)

      vim.keymap.set('n', '<space>s', function() Snacks.picker.git_status() end)
      vim.keymap.set('n', '<space>l', function() Snacks.picker.git_log() end)
      vim.keymap.set('n', '<space>p', function() Snacks.picker.pickers() end)
    end
  '';
}