-- disable netrw at the very start of your init.lua (strongly advised)
vim.g.loaded_netrw = 1
vim.g.loaded_netrwPlugin = 1
vim.wo.number = true
vim.wo.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

-- Loading Lazy plugin manager itself
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not vim.loop.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", run = ":TSUpdate" },
	{ "nvim-telescope/telescope.nvim", tag = "0.1.1", dependencies = { "nvim-lua/plenary.nvim" } },
	{ "ojroques/nvim-osc52" },
	{ "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",
		-- optional for floating window border decoration
		dependencies = {
			"nvim-lua/plenary.nvim",
		},
	},
	{ "rmagatti/auto-session" },
	{ "akinsho/toggleterm.nvim", version = "*", config = true },
	{ "zwhitchcox/auto-session-nvim-tree" },
	{ "jiaoshijie/undotree" },
	{
		"williamboman/mason.nvim",
		build = ":MasonUpdate", -- :MasonUpdate updates registry contents
	},
	{
		"folke/which-key.nvim",
		config = function()
			vim.o.timeout = true
			vim.o.timeoutlen = 300
			require("which-key").setup({
				-- your configuration comes here
				-- or leave it empty to use the default settings
				-- refer to the configuration section below
			})
		end,
	},
	{
		"Wansmer/treesj",
		keys = { "<space>m", "<space>j", "<space>s" },
		dependencies = { "nvim-treesitter/nvim-treesitter" },
		config = function()
			require("treesj").setup({--[[ your config ]]
		})
	end,
},
{ "williamboman/mason-lspconfig.nvim" },
{ "neovim/nvim-lspconfig" },
})

require('undotree').setup({
  float_diff = false,  -- using float window previews diff, set this `true` will disable layout option
  layout = "left_left_bottom", -- "left_bottom", "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("toggleterm").setup({})

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()


require("mason").setup({
	ui = {
		icons = {
			package_installed = "✓",
			package_pending = "➜",
			package_uninstalled = "✗",
		},
	},
})

require("mason-lspconfig").setup({
	ensure_installed = { "lua_ls", "rust_analyzer" },
})

require("lspconfig").lua_ls.setup({
	settings = {
		Lua = {
			runtime = {
				-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
				version = "LuaJIT",
			},
			diagnostics = {
				-- Get the language server to recognize the `vim` global
				globals = { "vim" },
			},
			workspace = {
				-- Make the server aware of Neovim runtime files
				library = vim.api.nvim_get_runtime_file("", true),
				checkThirdParty = false,
			},
			-- Do not send telemetry data containing a randomized but unique identifier
			telemetry = {
				enable = false,
			},
		},
	},
})

require("osc52").setup({
	max_length = 0, -- Maximum length of selection (0 for no limit)
	silent = false, -- Disable message on successful copy
	trim = false, -- Trim surrounding whitespaces before copy
})

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, {})

--- set termguicolors to enable highlight groups
vim.opt.termguicolors = true

require("nvim-tree").setup({
	sort = {
		sorter = "name",
	},
	view = {
		width = 22,
	},
	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")
local auto_session_nvim_tree = require("auto-session-nvim-tree")

auto_session.setup({
	log_level = "error",
	auto_session_root_dir = vim.fn.stdpath("data") .. "/sessions/",
	auto_session_enabled = true,
	auto_save_enabled = true,
	auto_restore_enabled = true,
	auto_session_suppress_dirs = { "~/", "~/dev", "~/Downloads", "/" },
	auto_session_use_git_branch = nil,
	cwd_change_handling = {
		restore_upcoming_session = true, -- This is necessary!!
	},
})
auto_session_nvim_tree.setup(auto_session)

require('nvim-treesitter.configs').setup {
	ensure_installed = { 'c','query','vimdoc','vim','bash', 'go', 'css', 'python', 'html', 'javascript', 'json', 'jsonc', 'lua', 'rust', 'typescript' },
	highlight = {
		enable = true,
	},
	incremental_selection = {
		enable = true,
		keymaps = {
			init_selection = "<CR>", -- set to `false` to disable one of the mappings
			node_incremental = "<TAB>",
			scope_incremental = "<CR>",
			node_decremental = "<S-TAB>",
		},
	},
}

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

-- if you only want these mappings for toggle term use term://*toggleterm#* instead
vim.cmd("autocmd! TermOpen term://* lua set_terminal_keymaps()")
vim.cmd("autocmd BufNewFile,BufRead *.tmpl set syntax=python")

vim.keymap.set("n", "<leader>c", require("osc52").copy_operator, { expr = true })
vim.keymap.set("n", "<leader>cc", "<leader>c_", { remap = true })
vim.keymap.set("v", "<leader>c", require("osc52").copy_visual)
