local pickers = require("telescope.pickers")
local finders = require("telescope.finders")
local conf = require("telescope.config").values
local actions = require("telescope.actions")
local action_state = require("telescope.actions.state")

-- Utility: Given a line number, returns the fold's starting line.
local function get_fold_start(l)
  local closed = vim.fn.foldclosed(l)
  if closed ~= -1 then
    return closed
  else
    local level = vim.fn.foldlevel(l)
    if level == 0 then
      return l
    end
    local start = l
    while start > 1 and vim.fn.foldlevel(start - 1) >= level do
      start = start - 1
    end
    return start
  end
end

local function jump_to_fold_starts()
  local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
  local entries = {}
  local prev_level = 0

  -- Detect fold-start lines by checking if foldlevel increases.
  for i, line in ipairs(lines) do
    local current_level = vim.fn.foldlevel(i)
    if current_level > prev_level then
      table.insert(entries, {
        value     = line,
        display   = string.format("%d: %s", i, line),
        ordinal   = line,
        file_line = i, -- Save the actual file line number.
      })
    end
    prev_level = current_level
  end

  pickers.new({}, {
    prompt_title = "Fold Starts",
    finder = finders.new_table {
      results = entries,
      entry_maker = function(entry)
        return entry  -- Already in the expected shape.
      end,
    },
    sorter = conf.generic_sorter({}),
    attach_mappings = function(prompt_bufnr, _)
      actions.select_default:replace(function()
        actions.close(prompt_bufnr)
        local selection = action_state.get_selected_entry()
        if selection then
          local target_line = get_fold_start(selection.file_line)
          vim.cmd(string.format("normal! %dG", target_line))
          vim.cmd("normal! zv")
        end
      end)
      return true
    end,
  }):find()
end

-- Expose the function so you can require it.
return { jump_to_fold_starts = jump_to_fold_starts }
