--
-- ███╗   ██╗███████╗ ██████╗ ██╗   ██╗██╗███╗   ███╗
-- ████╗  ██║██╔════╝██╔═══██╗██║   ██║██║████╗ ████║
-- ██╔██╗ ██║█████╗  ██║   ██║██║   ██║██║██╔████╔██║
-- ██║╚██╗██║██╔══╝  ██║   ██║╚██╗ ██╔╝██║██║╚██╔╝██║
-- ██║ ╚████║███████╗╚██████╔╝ ╚████╔╝ ██║██║ ╚═╝ ██║
-- ╚═╝  ╚═══╝╚══════╝ ╚═════╝   ╚═══╝  ╚═╝╚═╝     ╚═╝
--
-- File: mappings.lua
-- Description: Key mapping configs
-- Author: Kien Nguyen-Tuan <kiennt2609@gmail.com>

-- <leader> is a space now
local map = vim.keymap.set
local cmd = vim.cmd


vim.keymap.set("n", "<leader>b", ":Telescope buffers<CR>", { noremap = true, silent = true })
map("n", "<S-Tab>", ":bprevious<CR>", { noremap = true, silent = true })
map("n", "<Tab>", ":bnext<CR>", { noremap = true, silent = true })

map("n", "<leader>q", ":qa!<CR>", {})
-- Fast saving with <leader> and s
map("n", "<leader>s", ":w<CR>", {})
-- Move around splits
map("n", "<leader>wh", "<C-w>h", { desc = "switch window left" })
map("n", "<leader>wj", "<C-w>j", { desc = "switch window right" })
map("n", "<leader>wk", "<C-w>k", { desc = "switch window up" })
map("n", "<leader>wl", "<C-w>l", { desc = "switch window down" })

-- Reload configuration without restart nvim
-- Or you don't want to use plenary.nvim, you can use this code
-- function _G.reload_config()
-- 	for name, _ in pairs(package.loaded) do
-- 		if name:match("^me") then
-- 			package.loaded[name] = nil
-- 		end
-- 	end

-- 	dofile(vim.env.MYVIMRC)
-- 	vim.notify("Nvim configuration reloaded!", vim.log.levels.INFO)
-- end
function _G.reload_config()
  local reload = require("plenary.reload").reload_module
  reload("me", false)

  dofile(vim.env.MYVIMRC)
  vim.notify("Nvim configuration reloaded!", vim.log.levels.INFO)
end

map("n", "rr", _G.reload_config, { desc = "Reload configuration without restart nvim" })

-- Telescope
local builtin = require "telescope.builtin"
map("n", "<leader>ff", builtin.find_files, { desc = "Open Telescope to find files" })
map("n", "<leader>fg", builtin.live_grep, { desc = "Open Telescope to do live grep" })
map("n", "<leader>fb", builtin.buffers, { desc = "Open Telescope to list buffers" })
map("n", "<leader>fh", builtin.help_tags, { desc = "Open Telescope to show help" })
map("n", "<leader>fo", builtin.oldfiles, { desc = "Open Telescope to list recent files" })
map("n", "<leader>cm", builtin.git_commits, { desc = "Open Telescope to list git commits" })
-- NvimTree
map("n", "<leader>n", ":NvimTreeToggle<CR>", { desc = "Toggle NvimTree sidebar" })    -- open/close
map("n", "<leader>nr", ":NvimTreeRefresh<CR>", { desc = "Refresh NvimTree" })         -- refresh
map("n", "<leader>nf", ":NvimTreeFindFile<CR>", { desc = "Search file in NvimTree" }) -- search file

-- LSP
map(
  "n",
  "<leader>gm",
  function() require("conform").format { lsp_fallback = true } end,
  { desc = "General Format file" }
)

-- global lsp mappings
map("n", "<leader>ds", vim.diagnostic.setloclist, { desc = "LSP Diagnostic loclist" })

-- Comment
map("n", "mm", "gcc", { desc = "Toggle comment", remap = true })
map("v", "mm", "gc", { desc = "Toggle comment", remap = true })

-- Terminal
map("n", "tt", function()
  local height = math.floor(vim.o.lines / 2)
  cmd("belowright split | resize " .. height .. " | terminal")
end, { noremap = true, silent = true })


-- toggle-cmp.lua
local ok, cmp = pcall(require, "cmp")
if not ok then return end

-- initial state (true = autocomplete on)
vim.g.cmp_autocomplete = vim.g.cmp_autocomplete == nil and true or vim.g.cmp_autocomplete

function _G.toggle_cmp_autocomplete()
  vim.g.cmp_autocomplete = not vim.g.cmp_autocomplete

  if vim.g.cmp_autocomplete then
    -- enable automatic completion
    cmp.setup {
      completion = {
        -- typical events to auto-open completion
        autocomplete = { cmp.TriggerEvent.TextChanged, cmp.TriggerEvent.InsertEnter }
      }
    }
    print("cmp autocomplete: ON")
  else
    -- disable automatic completion and close any open menu
    cmp.setup { completion = { autocomplete = false } }
    pcall(cmp.close)
    print("cmp autocomplete: OFF")
  end
end

-- mappings
vim.keymap.set("n", "<leader>cc", "<cmd>lua _G.toggle_cmp_autocomplete()<CR>", { noremap = true, silent = true })
vim.keymap.set("i", "<C-\\>", function() _G.toggle_cmp_autocomplete() end, { silent = true })

-- manual trigger (still works when autocomplete is off)
vim.keymap.set("i", "<C-Space>", function() require("cmp").complete() end, { silent = true })
-- quick hide/abort in insert
vim.keymap.set("i", "<C-e>", function() require("cmp").abort() end, { silent = true })


-- zen-mode max-width helper
local M     = {}

-- configuration: change these to taste
M.zen_ratio = 0.80 -- try to use 80% of the editor width
M.zen_max   = 90   -- but never wider than 100 columns
M.zen_min   = 60   -- optional: never narrower than 60 columns

function M.open_zen_with_max()
  local cols = vim.o.columns or vim.api.nvim_get_option('columns')
  local desired = math.floor(cols * M.zen_ratio)
  -- clamp between min and max (optional min)
  local width = math.max(M.zen_min, math.min(desired, M.zen_max))

  require("zen-mode").toggle({
    window = {
      width = width,
      -- keep your usual window options if you like
      options = {
        number = false,
        relativenumber = false,
      },
    },
  })
end

-- map keys (change mapping as you prefer)
vim.keymap.set("n", "<leader>z", function() M.open_zen_with_max() end, { noremap = true, silent = true })

return M
