-- disable netrw at the very start of your init.lua (strongly advised)
vim.g.loaded_netrw = 1
vim.g.loaded_netrwPlugin = 1
vim.opt.number = true
vim.opt.signcolumn = "yes"
vim.o.scrolloff = 3
vim.o.sidescrolloff = 2
vim.loader.enable()

vim.o.background = "dark" -- or "light" for light mode
vim.opt.undofile = true
vim.opt.undolevels = 100000
vim.opt.undoreload = 1000000

vim.lsp.config("lua_ls", {
	settings = {
		Lua = {
			runtime = { version = "LuaJIT" },
			diagnostics = { globals = { "vim" } },
			workspace = {
				library = vim.api.nvim_get_runtime_file("", true),
				checkThirdParty = false,
			},
			telemetry = { enable = false },
		},
	},
})

-- Loading Lazy plugin manager itself
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
local uv = vim.uv or vim.loop
if not uv.fs_stat(lazypath) then
	vim.fn.system({
		"git",
		"clone",
		"--filter=blob:none",
		"https://github.com/folke/lazy.nvim.git",
		"--branch=stable", -- latest stable release
		lazypath,
	})
end
vim.opt.rtp:prepend(lazypath)

--Loading plugin manager and the plugins
require("lazy").setup({
	-- Gruvbox colorscheme
	{ "ellisonleao/gruvbox.nvim", priority = 1000 },
	-- Treesitter for better highlighting and moving
	{
		"nvim-treesitter/nvim-treesitter",
		lazy = false,
		build = ":TSUpdate",
		config = function()
			require("nvim-treesitter").setup()
			vim.treesitter.language.register("json", "jsonc")

			vim.api.nvim_create_autocmd("FileType", {
				pattern = "*",
				callback = function(args)
					pcall(vim.treesitter.start, args.buf)
				end,
			})
		end,
	},
	{ "nvim-telescope/telescope.nvim", dependencies = { "nvim-lua/plenary.nvim" } },
	{ "nvim-tree/nvim-tree.lua" },
	{ "jeffkreeftmeijer/vim-numbertoggle" },
	{ "lukas-reineke/indent-blankline.nvim", main = "ibl", opts = {} },
	{ "phaazon/hop.nvim" },
	{ "echasnovski/mini.nvim", version = "*" },
	{ "mg979/vim-visual-multi", branch = "master" },
	{ "ethanholz/nvim-lastplace" },
	{
		"kdheepak/lazygit.nvim",
		dependencies = {
			"nvim-lua/plenary.nvim",
		},
	},
	{ "rmagatti/auto-session", lazy = false },
	{ "akinsho/toggleterm.nvim", version = "*", config = true },
	{ "jiaoshijie/undotree" },
	{
		"williamboman/mason.nvim",
		build = function() pcall(vim.cmd, "MasonUpdate") end,
		opts = {
			ui = {
				icons = {
					package_installed = "✓",
					package_pending = "➜",
					package_uninstalled = "✗",
				},
			},
		},
	},
	{
		"folke/which-key.nvim",
		config = function()
			vim.o.timeout = true
			vim.o.timeoutlen = 300
			require("which-key").setup({})
		end,
	},
	{
		"Wansmer/treesj",
		keys = { "<space>m", "<space>j", "<space>s" },
		dependencies = { "nvim-treesitter/nvim-treesitter" },
		config = function()
			require("treesj").setup({})
		end,
	},
	{
		"williamboman/mason-lspconfig.nvim",
		dependencies = {
			"williamboman/mason.nvim",
			"neovim/nvim-lspconfig",
		},
		opts = {
			ensure_installed = { "lua_ls", "rust_analyzer" },
			automatic_enable = true,
		},
	},
	{ "neovim/nvim-lspconfig" },
})

require("undotree").setup({
	float_diff = false,
	layout = "left_left_bottom",
	ignore_filetype = { "undotree", "undotreeDiff", "qf", "TelescopePrompt", "spectre_panel", "tsplayground" },
	window = {
		winblend = 0,
	},
	keymaps = {
		["j"] = "move_next",
		["k"] = "move_prev",
		["J"] = "move_change_next",
		["K"] = "move_change_prev",
		["<cr>"] = "action_enter",
		["p"] = "enter_diffbuf",
		["q"] = "quit",
	},
})

vim.cmd([[colorscheme gruvbox]])
require("nvim-lastplace").setup({
	lastplace_ignore_buftype = { "quickfix", "nofile", "help" },
	lastplace_ignore_filetype = { "gitcommit", "gitrebase", "svn", "hgcommit" },
	lastplace_open_folds = true,
})

require("hop").setup()
require("mini.ai").setup()
require("mini.pairs").setup()
-- require("mini.comment").setup()
require("mini.starter").setup()
require("mini.statusline").setup()
require("mini.tabline").setup()
require("mini.bracketed").setup()
require("mini.surround").setup()
require("mini.cursorword").setup()
-- require("mini.completion").setup()

vim.opt.clipboard = "unnamedplus"
vim.g.clipboard = {
	name = "OSC 52",
	copy = {
		["+"] = require("vim.ui.clipboard.osc52").copy("+"),
		["*"] = require("vim.ui.clipboard.osc52").copy("*"),
	},
	paste = {
		["+"] = require("vim.ui.clipboard.osc52").paste("+"),
		["*"] = require("vim.ui.clipboard.osc52").paste("*"),
	},
}

local hop = require("hop")
-- local directions = require("hop.hint").HintDirection

vim.keymap.set("n", "<leader>s", function() hop.hint_words() end, { remap = true })

local builtin = require("telescope.builtin")

vim.keymap.set("n", "<leader>fg", builtin.live_grep, {})
vim.keymap.set("n", "<leader>fb", builtin.buffers, {})
vim.keymap.set("n", "<leader>fh", builtin.help_tags, {})

vim.opt.termguicolors = true

require("nvim-tree").setup({
	sort = {
		sorter = "name",
	},
	sync_root_with_cwd = true,
	respect_buf_cwd = true,
	view = {
		width = 22,
	},
	actions = {
		change_dir = {
			enable = true,
			global = true,
		},
	},
	renderer = {
		group_empty = true,
	},
	filters = {
		dotfiles = false,
	},
})

vim.api.nvim_set_keymap("n", "<leader>e", ":NvimTreeToggle<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>t", ":ToggleTerm<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>q", ":qa<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>w", ":w<CR>", { noremap = true, silent = true })
-- vim.keymap.set("n", "<leader>u", vim.cmd.UndotreeToggle)
vim.keymap.set("n", "<leader>u", require("undotree").toggle, { noremap = true, silent = true })

vim.o.sessionoptions = "blank,buffers,curdir,folds,help,tabpages,winsize,winpos,terminal,localoptions"

local auto_session = require("auto-session")

auto_session.setup({
	log_level = "error",
	root_dir = vim.fn.stdpath("data") .. "/sessions/",
	enabled = true,
	auto_save = true,
	auto_restore = true,
	suppressed_dirs = { "~/", "~/dev", "~/Downloads", "/" },
	git_use_branch_name = false,
	cwd_change_handling = {
		restore_upcoming_session = true,
	},
})

vim.cmd([[highlight IndentBlanklineIndent1 guifg=#443838 gui=nocombine]])

vim.opt.tabstop = 4
vim.opt.softtabstop = 4
vim.opt.shiftwidth = 4
vim.opt.list = true
vim.opt.listchars:append("lead:⋅")
-- vim.opt.listchars:append("tab:▷⎯⎯")
-- vim.opt.listchars:append("tab:▸⁃ ")
-- vim.opt.listchars:append("tab:▸⁃⁃")
vim.opt.listchars:append("tab:→  ")
vim.opt.listchars:append("multispace:  ⋅ ⋅ ⋅ ⋅ ⋅ ⋅")
vim.opt.listchars:append("leadmultispace:⋅ ⋅ ")
vim.opt.listchars:append("trail:␣")

function _G.set_terminal_keymaps()
	local opts = { buffer = 0 }
	--  vim.keymap.set('t', '<esc>', [[<C-\><C-n>]], opts)
	--  vim.keymap.set('t', 'jk', [[<C-\><C-n>]], opts)
	vim.keymap.set("t", "<C-h>", [[<Cmd>wincmd h<CR>]], opts)
	vim.keymap.set("t", "<C-j>", [[<Cmd>wincmd j<CR>]], opts)
	vim.keymap.set("t", "<C-up>", [[<Cmd>wincmd k<CR>]], opts)
	vim.keymap.set("t", "<C-k>", [[<Cmd>wincmd k<CR>]], opts)
	vim.keymap.set("t", "<C-l>", [[<Cmd>wincmd l<CR>]], opts)
	vim.keymap.set("t", "<C-w>", [[<C-\><C-n><C-w>]], opts)
end

local aug = vim.api.nvim_create_augroup("user_autocmds", { clear = true })
vim.api.nvim_create_autocmd("TermOpen", {
	group = aug,
	pattern = "term://*",
	callback = set_terminal_keymaps,
})
vim.api.nvim_create_autocmd({ "BufNewFile", "BufRead" }, {
	group = aug,
	pattern = "*.tmpl",
	command = "set syntax=python",
})
