-- Leader key (must be set before lazy.nvim loads)
vim.g.mapleader = ","

-------------------- Options --------------------
vim.opt.number = true
vim.opt.cursorline = true
vim.opt.expandtab = true
vim.opt.tabstop = 4
vim.opt.shiftwidth = 4
vim.opt.softtabstop = 4
vim.opt.autoindent = true
vim.opt.spelllang = "vi,en"
vim.opt.foldmethod = "syntax"
vim.opt.foldlevel = 1
vim.opt.foldnestmax = 1
vim.opt.hlsearch = true
vim.opt.splitright = true
vim.opt.splitbelow = true
vim.opt.termguicolors = true
vim.opt.autoread = true

-------------------- Keymaps --------------------
-- Clear hlsearch then enter insert mode
vim.keymap.set("n", "i", ":nohls<CR>i", { silent = true })

-- Save with space
vim.keymap.set("n", "<Space>", ":w<CR>", { silent = true })

-- Window navigation
vim.keymap.set("n", "<C-h>", "<C-W>h")
vim.keymap.set("n", "<C-j>", "<C-W>j")
vim.keymap.set("n", "<C-k>", "<C-W>k")
vim.keymap.set("n", "<C-l>", "<C-W>l")
vim.keymap.set("n", "<C-Left>", "<C-W>h")
vim.keymap.set("n", "<C-Down>", "<C-W>j")
vim.keymap.set("n", "<C-Up>", "<C-W>k")
vim.keymap.set("n", "<C-Right>", "<C-W>l")

-- Tab management
vim.keymap.set("n", "<leader>to", ":tabonly<CR>", { silent = true })
vim.keymap.set("n", "<leader>o", ":only<CR>", { silent = true })
vim.keymap.set("n", "<leader><Tab>", ":tabn<CR>", { silent = true })
vim.keymap.set("n", "<S-Tab>", ":tabp<CR>", { silent = true })

-- Clipboard operations
vim.keymap.set("v", "<leader>y", '"+y')
vim.keymap.set("n", "<leader>Y", '"+yg_')
vim.keymap.set("n", "<leader>y", '"+y')
vim.keymap.set("n", "<leader>yy", '"+yy')
vim.keymap.set("n", "<leader>p", '"+p')
vim.keymap.set("n", "<leader>P", '"+P')

-- Background toogling
vim.keymap.set("n", "<leader>bg", function()
  vim.o.background = vim.o.background == "dark" and "light" or "dark"
end, { desc = "Toggle light/dark background" })

-- Join paragraph
vim.keymap.set("n", "<leader>j", "vipJ", { desc = "Join paragraph into one line" })

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

-------------------- Plugins --------------------
require("lazy").setup({

    -- Colorscheme
    {
        "ellisonleao/gruvbox.nvim",
        priority = 1000,
        config = function()
            require("gruvbox").setup({
                contrast = "soft",
            })
            vim.cmd.colorscheme("gruvbox")
            vim.o.background = "light"
        end,
    },

    -- Icons (dependency for nvim-tree and lualine)
    { "nvim-tree/nvim-web-devicons", lazy = true },

    -- File tree
    {
        "nvim-tree/nvim-tree.lua",
        dependencies = { "nvim-tree/nvim-web-devicons" },
        keys = {
            { "<F2>", "<cmd>NvimTreeToggle<CR>", desc = "Toggle file tree" },
        },
        config = function()
            require("nvim-tree").setup()
        end,
    },

    -- Comments
    {
        "numToStr/Comment.nvim",
        event = "VeryLazy",
        config = function()
            require("Comment").setup()
        end,
    },

    -- Fuzzy finder (fzf-lua with ripgrep)
    {
        "ibhagwan/fzf-lua",
        dependencies = { "nvim-tree/nvim-web-devicons" },
        keys = {
            { "<leader>b", "<cmd>FzfLua buffers<CR>", desc = "Buffers" },
            { "<leader>r", "<cmd>FzfLua live_grep<CR>", desc = "Live grep" },
            { "<leader>f", "<cmd>FzfLua files<CR>", desc = "Find files" },
            { "<leader>g", "<cmd>FzfLua git_files<CR>", desc = "Git files" },
            { "<leader>w", "<cmd>FzfLua grep_cword<CR>", desc = "Grep word under cursor" },
        },
        config = function()
            require("fzf-lua").setup({
                files = {
                    cmd = "rg --files --hidden --glob '!**/.git/*'",
                },
                grep = {
                    rg_opts = "--hidden --glob '!**/.git/*' --column --line-number --no-heading --color=always --smart-case",
                },
            })
        end,
    },

    -- Statusline
    {
        "nvim-lualine/lualine.nvim",
        dependencies = { "nvim-tree/nvim-web-devicons" },
        config = function()
            require("lualine").setup({
                options = { theme = "gruvbox" },
            })
        end,
    },

    -- Autopairs
    {
        "windwp/nvim-autopairs",
        event = "InsertEnter",
        opts = {},
    },

    -- Surround
    { "4ree/viml-surround", event = "VeryLazy" },

    -- LSP
    {
        "neovim/nvim-lspconfig",
        config = function()
            vim.lsp.config("clangd", {})
            vim.lsp.config("pyright", {})
            vim.lsp.config("rust_analyzer", {})
            vim.lsp.config("julials", {})
            vim.lsp.enable({ "clangd", "pyright", "rust_analyzer", "julials" })

            vim.api.nvim_create_autocmd("LspAttach", {
                callback = function(args)
                    local opts = { buffer = args.buf }
                    vim.keymap.set("n", "gd", vim.lsp.buf.definition, opts)
                    vim.keymap.set("n", "gr", vim.lsp.buf.references, opts)
                    vim.keymap.set("n", "K", vim.lsp.buf.hover, opts)
                    vim.keymap.set("n", "<leader>rn", vim.lsp.buf.rename, opts)
                    vim.keymap.set("n", "<leader>ca", vim.lsp.buf.code_action, opts)
                end,
            })
        end,
    },

    -- Completion (coq_nvim)
    {
        "ms-jpq/coq_nvim",
        branch = "coq",
        dependencies = {
            { "ms-jpq/coq.artifacts", branch = "artifacts" },
            { "ms-jpq/coq.thirdparty", branch = "3p" },
        },
        init = function()
            vim.g.coq_settings = { auto_start = "shut-up" }
        end,
    },

    -- Quickfix enhancements
    { "kevinhwang91/nvim-bqf", ft = "qf" },

    -- Git
    { "tpope/vim-fugitive" },

    -- IME support
    {
        "4ree/vim-ime",
        event = "VeryLazy",
        opts = {},
    },

    -- LaTeX
    {
        "lervag/vimtex",
        config = function()
            vim.g.vimtex_view_method = "zathura"
            vim.g.vimtex_compiler_latexmk = {
                options = {
                    "-verbose",
                    "-file-line-error",
                    "-synctex=1",
                    "-interaction=nonstopmode",
                    "-shell-escape",
                    "-output-directory=./output",
                    "-aux-directory=./",
                },
            }
        end,
    },

    -- Julia
    { "JuliaEditorSupport/julia-vim" },
})
