local on = vim.api.nvim_create_autocmd
local group = vim.api.nvim_create_augroup("autocmds", {clear = true})

on({ "BufNewFile", "BufRead" }, {
	desc = "Enable word wrap in text files and markdown documents",
	group = group,
	pattern = { "*.txt", "*.md" },
	callback = function()
		vim.opt_local.wrap = true
		vim.opt_local.signcolumn = "no"
	end,
})

on({ "TermOpen", "TermEnter" }, {
	desc = "Disable sign column in terminals",
	group = group,
	callback = function()
		vim.opt_local.signcolumn = "no"
	end,
})

on({ "TextYankPost" }, {
	desc = "Highlight when copying text",
	group = group,
	callback = function()
		vim.highlight.on_yank()
	end,
})

on({ "VimEnter" }, {
	desc = "Allow opening a directory and jumping to project root",
	group = group,
	callback = function()
		-- Change file to its directory if needed
		local name = vim.api.nvim_buf_get_name(0)
		local is_directory = vim.fn.isdirectory(name)

		if is_directory == 0 then
			name = vim.fs.dirname(name)
		end

		-- Switch to root directory of the project
		local root_patterns = { ".git", "go.mod", "init.lua" }
		local root_dir = vim.fs.dirname(vim.fs.find(root_patterns, {
			upward = true,
			path = name,
		})[1])

		if root_dir then
			vim.api.nvim_set_current_dir(root_dir)
		else
			vim.api.nvim_set_current_dir(name)
		end

		if is_directory ~= 0 then
			require("telescope.builtin").find_files()
		end
	end,
})