-------------------------------------------------------------------
-- Settings
-------------------------------------------------------------------
vim.g.mapleader = " "
vim.g.maplocalleader = " "
vim.o.hlsearch = false
vim.wo.number = true
vim.o.mouse = "a"
vim.o.breakindent = true
vim.o.undofile = true
vim.o.ignorecase = true
vim.o.smartcase = true
vim.wo.signcolumn = "yes"
vim.o.termguicolors = true
vim.o.shiftwidth = 4
vim.o.smarttab = true
vim.o.tabstop = 4
vim.o.expandtab = true
vim.o.softtabstop = 4
vim.o.inccommand = "split"
vim.o.cursorline = true
vim.o.showmatch = true
vim.o.updatetime = 250
vim.o.timeoutlen = 300
vim.o.pumheight = 10
vim.o.relativenumber = true
vim.o.scrolloff = 8
vim.o.showmode = false
vim.o.showtabline = 0
vim.o.wrap = true
vim.o.foldmethod = "expr"
vim.o.foldexpr = "nvim_treesitter#foldexpr()"
vim.o.foldlevelstart = 99
vim.o.autoread = true

vim.schedule(function()
	vim.o.clipboard = "unnamedplus"
end)

-------------------------------------------------------------------
-- Autocommands
-------------------------------------------------------------------
-- Autoset current working directory based on closest git repo
vim.api.nvim_create_autocmd("BufEnter", {
	callback = function()
		local git_dir = vim.fn.finddir(".git", ".;")
		if git_dir ~= "" then
			local git_root = vim.fn.fnamemodify(git_dir, ":h")
			vim.cmd("lcd " .. git_root)
		end
	end,
})
-- show cursor line only in active window
local cursorLineGrp = vim.api.nvim_create_augroup("CursorLine", { clear = true })
vim.api.nvim_create_autocmd(
	{ "InsertLeave", "WinEnter" },
	{ pattern = "*", command = "set cursorline", group = cursorLineGrp }
)
vim.api.nvim_create_autocmd(
	{ "InsertEnter", "WinLeave" },
	{ pattern = "*", command = "set nocursorline", group = cursorLineGrp }
)
vim.api.nvim_create_autocmd(
	{ "InsertLeave", "FocusGained" },
	{ pattern = "*", command = "set cursorline", group = cursorLineGrp }
)
vim.api.nvim_create_autocmd(
	{ "InsertEnter", "FocusLost" },
	{ pattern = "*", command = "set nocursorline", group = cursorLineGrp }
)
-- Auto update on file changes
vim.api.nvim_create_autocmd({ "BufEnter", "CursorHold", "CursorHoldI", "FocusGained" }, {
	command = "if mode() != 'c' | checktime | endif",
	pattern = { "*" },
})
vim.api.nvim_create_autocmd(
	{ "FileChangedShellPost" },
	{ command = 'echohl WarningMsg | echo "File changed on disk. Buffer reloaded." | echohl None', pattern = { "*" } }
)

-------------------------------------------------------------------
-- Plugin management
-------------------------------------------------------------------
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)

-------------------------------------------------------------------
-- Plugin installation
-------------------------------------------------------------------
require("lazy").setup({

	{
		dir = "~/linuxbox/nightly_cm.nvim",
		lazy = false,
		priority = 1000,
		config = function()
			vim.cmd.colorscheme("nightly_cm")
		end,
	},

	{
		"folke/lazydev.nvim",
		ft = "lua", -- only load on lua files
		opts = {
			library = {
				{ path = "${3rd}/luv/library", words = { "vim%.uv" } },
			},
		},
	},

	{
		"neovim/nvim-lspconfig",
		dependencies = {
			{ "j-hui/fidget.nvim", opts = {} },
		},
		config = function()
			vim.api.nvim_create_autocmd("LspAttach", {
				group = vim.api.nvim_create_augroup("kickstart-lsp-attach", { clear = true }),
				callback = function(event)
					local map = function(keys, func, desc, mode)
						mode = mode or "n"
						vim.keymap.set(mode, keys, func, { buffer = event.buf, desc = "LSP: " .. desc })
					end

					map("grn", vim.lsp.buf.rename, "[R]e[n]ame")
					map("gra", vim.lsp.buf.code_action, "[G]oto Code [A]ction", { "n", "x" })
					map("grr", require("fzf-lua").lsp_references, "[G]oto [R]eferences")
					map("gri", require("fzf-lua").lsp_implementations, "[G]oto [I]mplementation")
					map("grd", require("fzf-lua").lsp_definitions, "[G]oto [D]efinition")

					-- WARN: This is not Goto Definition, this is Goto Declaration.
					--  For example, in C this would take you to the header.
					map("grD", vim.lsp.buf.declaration, "[G]oto [D]eclaration")
					map("gO", require("fzf-lua").lsp_document_symbols, "Open Document Symbols")
					map("gW", require("fzf-lua").lsp_live_workspace_symbols, "Open Workspace Symbols")
					map("grt", require("fzf-lua").lsp_typedefs, "[G]oto [T]ype Definition")

					-- This function resolves a difference between neovim nightly (version 0.11) and stable (version 0.10)
					---@param client vim.lsp.Client
					---@param method vim.lsp.protocol.Method
					---@param bufnr? integer some lsp support methods only in specific files
					---@return boolean
					local function client_supports_method(client, method, bufnr)
						if vim.fn.has("nvim-0.11") == 1 then
							return client:supports_method(method, bufnr)
						else
							return client.supports_method(method, { bufnr = bufnr })
						end
					end
				end,
			})

			vim.diagnostic.config({
				severity_sort = true,
				float = { border = "rounded", source = "if_many" },
				underline = { severity = vim.diagnostic.severity.ERROR },
				signs = {
					text = {
						[vim.diagnostic.severity.ERROR] = "󰅚 ",
						[vim.diagnostic.severity.WARN] = "󰀪 ",
						[vim.diagnostic.severity.INFO] = "󰋽 ",
						[vim.diagnostic.severity.HINT] = "󰌶 ",
					},
				} or {},
				virtual_text = {
					source = "if_many",
					spacing = 2,
					format = function(diagnostic)
						local diagnostic_message = {
							[vim.diagnostic.severity.ERROR] = diagnostic.message,
							[vim.diagnostic.severity.WARN] = diagnostic.message,
							[vim.diagnostic.severity.INFO] = diagnostic.message,
							[vim.diagnostic.severity.HINT] = diagnostic.message,
						}
						return diagnostic_message[diagnostic.severity]
					end,
				},
			})

			local capabilities = require("blink.cmp").get_lsp_capabilities()

			local servers = {
				clangd = {},
				html = {},
				yamlls = {},
				bashls = {},
				pyright = {},
				marksman = {},
				rust_analyzer = {},
				lua_ls = {
					settings = {
						Lua = {
							completion = {
								callSnippet = "Replace",
							},
						},
					},
				},
			}

			for server_name, server in pairs(servers) do
				server.capabilities = vim.tbl_deep_extend("force", {}, capabilities, server.capabilities or {})
				require("lspconfig")[server_name].setup(server)
			end
		end,
	},

	{
		"stevearc/conform.nvim",
		opts = {
			formatters_by_ft = {
				lua = { "stylua" },
				python = { "isort", "black" },
				rust = { "rustfmt", lsp_format = "fallback" },
				c = { "clang_format" },
				cpp = { "clang_format" },
				javascript = { "prettier" },
				typescript = { "prettier" },
				javascriptreact = { "prettier" },
				typescriptreact = { "prettier" },
				css = { "prettier" },
				html = { "prettier" },
				json = { "prettier" },
				yaml = { "prettier" },
				markdown = { "prettier" },
				sh = { "shfmt" },
			},
			formatters = {
				clang_format = {
					prepend_args = { "--style={BasedOnStyle: LLVM, IndentWidth: 4, TabWidth: 4, UseTab: Never}" },
				},
				shfmt = {
					prepend_args = { "-i", "4" },
				},
			},
			format_on_save = {
				timeout_ms = 3000,
				lsp_format = "fallback",
			},
		},
	},

	{
		"saghen/blink.cmp",
		event = "VimEnter",
		version = "1.*",
		dependencies = {
			-- Snippet Engine
			{
				"L3MON4D3/LuaSnip",
				version = "2.*",
				build = (function()
					if vim.fn.has("win32") == 1 or vim.fn.executable("make") == 0 then
						return
					end
					return "make install_jsregexp"
				end)(),
				dependencies = {},
				opts = {},
			},
			"folke/lazydev.nvim",
		},
		--- @module 'blink.cmp'
		--- @type blink.cmp.Config
		opts = {
			keymap = {
				preset = "default",
			},

			appearance = {
				nerd_font_variant = "mono",
			},

			completion = {
				documentation = { auto_show = false, auto_show_delay_ms = 500 },
			},

			sources = {
				default = { "lsp", "buffer", "path", "snippets", "lazydev" },
				providers = {
					lazydev = { module = "lazydev.integrations.blink", score_offset = 100 },
				},
			},

			snippets = { preset = "luasnip" },
			fuzzy = { implementation = "prefer_rust_with_warning" },
			signature = { enabled = true },
		},
	},

	{
		"nvim-treesitter/nvim-treesitter",
		build = ":TSUpdate",
		main = "nvim-treesitter.configs", -- Sets main module to use for opts
		opts = {
			ensure_installed = {
				"bash",
				"c",
				"diff",
				"html",
				"lua",
				"luadoc",
				"markdown",
				"markdown_inline",
				"query",
				"vim",
				"vimdoc",
				"rust",
				"python",
			},
			auto_install = true,
			highlight = {
				enable = true,
				additional_vim_regex_highlighting = { "ruby" },
			},
			indent = { enable = true, disable = { "ruby" } },
		},
	},

	{
		"ibhagwan/fzf-lua",
		dependencies = { "echasnovski/mini.icons" },
		opts = {
			"fzf-tmux",
			fzf_opts = { ["--tmux"] = "center,80%,80%" },
			fzf_colors = {
				true, -- inherit fzf colors that aren't specified below from
				-- the auto-generated theme similar to `fzf_colors=true`
				["fg"] = { "fg", "CursorLine" },
				["bg"] = { "bg", "Black" },
				["hl"] = { "fg", "Comment" },
				["fg+"] = { "fg", "Normal", "underline" },
				["bg+"] = { "bg", { "CursorLine", "Normal" } },
				["hl+"] = { "fg", "Statement" },
				["info"] = { "fg", "PreProc" },
				["prompt"] = { "fg", "Conditional" },
				["pointer"] = { "fg", "Exception" },
				["marker"] = { "fg", "Keyword" },
				["spinner"] = { "fg", "Label" },
				["header"] = { "fg", "Comment" },
				["gutter"] = "-1",
			},
			files = {
				git_icons = true, -- show git icons?
				file_icons = true, -- show file icons (true|"devicons"|"mini")?
				color_icons = true, -- colorize file|git icons
			},
		},
	},

	{
		"mrjones2014/smart-splits.nvim",
		lazy = false,
		opts = {
			at_edge = "stop",
		},
	},

	{
		"nvim-lualine/lualine.nvim",
		opts = {
			options = {
				icons_enabled = true,
				theme = "nightly_cm",
				component_separators = "",
				section_separators = "",
				globalstatus = true,
			},
			sections = {
				lualine_a = { "mode" },
				lualine_b = { "branch", "diff" },
				lualine_c = { "diagnostics", "filename" },
				lualine_x = {
					{
						-- Lsp server name .
						function()
							local msg = ""
							local clients = vim.lsp.get_clients({ bufnr = 0 })
							if next(clients) == nil then
								return msg
							end
							for _, client in ipairs(clients) do
								msg = msg .. client.name .. ", "
							end
							if msg == "" then
								return msg
							end
							return msg:sub(1, -3)
						end,
						color = { fg = "#c6c6c6" },
					},
				},
				lualine_y = { "filetype" },
				lualine_z = { "progress" },
			},
		},
	},

	{ "echasnovski/mini.icons", version = "*", opts = {} },
	{ "echasnovski/mini.pairs", version = "*", opts = {} },
	{ "echasnovski/mini.surround", version = "*", opts = {} },
	{
		"echasnovski/mini.files",
		version = "*",
		opts = { mappings = {
			go_n_plus = "l",
			go_out = "h",
			go_out_plus = "H",
		} },
	},

	{
		"karb94/neoscroll.nvim",
		opts = { duration_multiplier = 0.5 },
	},

	{
		"folke/flash.nvim",
		event = "VeryLazy",
		---@type Flash.Config
		opts = {},
          -- stylua: ignore
        keys = {
            { "s", mode = { "n", "x", "o" }, function() require("flash").jump() end, desc = "Flash" },
            { "S", mode = { "n", "x", "o" }, function() require("flash").treesitter() end, desc = "Flash Treesitter" },
            { "r", mode = "o", function() require("flash").remote() end, desc = "Remote Flash" },
            { "R", mode = { "o", "x" }, function() require("flash").treesitter_search() end, desc = "Treesitter Search" },
            { "<c-s>", mode = { "c" }, function() require("flash").toggle() end, desc = "Toggle Flash Search" },
        },
	},

	{
		"lewis6991/gitsigns.nvim",
		opts = {
			signs = {
				add = { text = "▎" },
				change = { text = "▎" },
				delete = { text = "▎" },
				topdelete = { text = "▎" },
				changedelete = { text = "▎" },
				untracked = { text = "▎" },
			},
			preview_config = {
				-- Options passed to nvim_open_win
				border = "solid",
				style = "minimal",
				relative = "cursor",
				row = 0,
				col = 1,
			},
		},
	},

	{
		"lukas-reineke/indent-blankline.nvim",
		main = "ibl",
		---@module "ibl"
		---@type ibl.config
		opts = {
			scope = {
				show_end = false,
			},
		},
	},

	{
		"norcalli/nvim-colorizer.lua",
		opts = { "*" },
	},

	{
		"folke/which-key.nvim",
		event = "VeryLazy",
		init = function()
			vim.o.timeout = true
			vim.o.timeoutlen = 300
		end,
		opts = {},
	},

	{
		"stevearc/dressing.nvim",
		opts = {},
	},

	{
		"max397574/better-escape.nvim",
		opts = { timeout = 300 },
	},

	{ "numToStr/Comment.nvim", opts = {} },

	{
		"folke/todo-comments.nvim",
		dependencies = { "nvim-lua/plenary.nvim" },
		opts = {},
	},
}, {})

-- resizing splits
vim.keymap.set({ "n", "t" }, "<A-h>", require("smart-splits").resize_left, { desc = "Resize left" })
vim.keymap.set({ "n", "t" }, "<A-j>", require("smart-splits").resize_down, { desc = "Resize down" })
vim.keymap.set({ "n", "t" }, "<A-k>", require("smart-splits").resize_up, { desc = "Resize up" })
vim.keymap.set({ "n", "t" }, "<A-l>", require("smart-splits").resize_right, { desc = "Resize right" })
-- moving between splits
vim.keymap.set({ "n", "t" }, "<C-h>", require("smart-splits").move_cursor_left, { desc = "Move cursor left" })
vim.keymap.set({ "n", "t" }, "<C-j>", require("smart-splits").move_cursor_down, { desc = "Move cursor down" })
vim.keymap.set({ "n", "t" }, "<C-k>", require("smart-splits").move_cursor_up, { desc = "Move cursor up" })
vim.keymap.set({ "n", "t" }, "<C-l>", require("smart-splits").move_cursor_right, { desc = "Move cursor right" })
-- swapping buffers between windows
vim.keymap.set("n", "<leader><leader>h", require("smart-splits").swap_buf_left, { desc = "Swap buffer left" })
vim.keymap.set("n", "<leader><leader>j", require("smart-splits").swap_buf_down, { desc = "Swap buffer down" })
vim.keymap.set("n", "<leader><leader>k", require("smart-splits").swap_buf_up, { desc = "Swap buffer up" })
vim.keymap.set("n", "<leader><leader>l", require("smart-splits").swap_buf_right, { desc = "Swap buffer right" })
-- Yank, delete, and paste always use system clipboard
vim.keymap.set({ "n", "v" }, "y", '"+y', { noremap = true, silent = true })
vim.keymap.set({ "n", "v" }, "Y", '"+Y', { noremap = true, silent = true })
vim.keymap.set({ "n", "v" }, "d", '"+d', { noremap = true, silent = true })
-- vim.keymap.set({ 'n', 'v' }, 'x', '"+x', { noremap = true, silent = true })
vim.keymap.set({ "n", "v" }, "p", '"+p', { noremap = true, silent = true })
vim.keymap.set({ "n", "v" }, "P", '"+P', { noremap = true, silent = true })
-- Other
vim.keymap.set("n", "<Esc>", "<cmd>nohlsearch<CR>")
vim.keymap.set("n", "<tab>", ":tabNext<cr>", { desc = "Next tab", silent = true })
vim.keymap.set("n", "<C-s>", ":write<cr>", { desc = "Save", silent = true })
vim.keymap.set("n", "<C-q>", ":quit<cr>", { desc = "Quit", silent = true })
vim.keymap.set("n", "<leader>e", ":e .<cr>", { desc = "File explorer", silent = true })
vim.keymap.set("n", "<leader>f", ":FzfLua files<cr>", { desc = "Find file in cwd", silent = true })
vim.keymap.set("n", "<leader>F", ":FzfLua files cwd=~/<cr>", { desc = "Find file in root", silent = true })
vim.keymap.set("n", "<leader>b", ":FzfLua buffers<cr>", { desc = "Buffers", silent = true })
vim.keymap.set("n", "<leader>d", ":FzfLua lsp_document_diagnostics<cr>", { desc = "Diagnostics", silent = true })
vim.keymap.set("n", "<leader>o", ":FzfLua oldfiles<cr>", { desc = "Old file", silent = true })
vim.keymap.set("n", "<leader>g", ":FzfLua git_status<cr>", { desc = "Git status", silent = true })
