--
-- ███╗   ██╗███████╗ ██████╗ ██╗   ██╗██╗███╗   ███╗
-- ████╗  ██║██╔════╝██╔═══██╗██║   ██║██║████╗ ████║
-- ██╔██╗ ██║█████╗  ██║   ██║██║   ██║██║██╔████╔██║
-- ██║╚██╗██║██╔══╝  ██║   ██║╚██╗ ██╔╝██║██║╚██╔╝██║
-- ██║ ╚████║███████╗╚██████╔╝ ╚████╔╝ ██║██║ ╚═╝ ██║
-- ╚═╝  ╚═══╝╚══════╝ ╚═════╝   ╚═══╝  ╚═╝╚═╝     ╚═╝
--
-- File: plugins/init.lua
-- Description: init plugins config

-- Built-in plugins
local builtin_plugins = {
  { "nvim-lua/plenary.nvim" },
  -- File explore
  -- nvim-tree.lua - A file explorer tree for neovim written in lua
  {
    "nvim-tree/nvim-tree.lua",
    dependencies = {
      "nvim-tree/nvim-web-devicons",
      opt = true,
    },
    opts = function() require "plugins.configs.tree" end,
  },
  -- Formatter
  -- Lightweight yet powerful formatter plugin for Neovim
  {
    "stevearc/conform.nvim",
    opts = {
      formatters_by_ft = { lua = { "stylua" } },
    },
  },

  {
    'kmontocam/nvim-conda',
    dependencies = { 'nvim-lua/plenary.nvim' }
  },


  -- Git integration for buffers
  {
    "lewis6991/gitsigns.nvim",
    event = { "BufReadPost", "BufNewFile", "BufWritePost" },
    opts = function() require "plugins.configs.gitsigns" end,
  },

  -- in your `plugins.lua` (lazy.nvim)
  {
    "goerz/jupytext.nvim",
    version = "0.2.0",
    opts = {
      format        = "markdown", -- or "hydrogen" style etc.
      autosync      = true,
      sync_patterns = { "*.md", "*.py" },
    }
  },



  {
    -- see the image.nvim readme for more information about configuring this plugin
    "3rd/image.nvim",
    build = false,
    opts = {
      processor = "magick_cli",
      integrations = {
        markdown = {
          enabled = true,
        }
      }
    },

    opts = function() require "plugins.configs.image" end,
  },

  {
    "benlubas/molten-nvim",
    version = "^2.0.0", -- use version <2.0.0 to avoid breaking changes
    dependencies = { "3rd/image.nvim" },
    build = ":UpdateRemotePlugins",
    init = function()
      -- these are examples, not defaults. Please see the readme
      vim.g.molten_image_provider = "image.nvim"
      vim.g.molten_output_win_max_height = 20
    end,
  },

  -- Treesitter interface
  {
    "nvim-treesitter/nvim-treesitter",
    version = false, -- last release is way too old and doesn't work on Windows
    evevent = { "BufReadPost", "BufNewFile", "BufWritePost" },
    cmd = { "TSInstall", "TSBufEnable", "TSBufDisable", "TSModuleInfo" },
    build = ":TSUpdate",
    opts = function() require "plugins.configs.treesitter" end,
  },
  -- Telescope
  -- Find, Filter, Preview, Pick. All lua, all the time.
  {
    "nvim-telescope/telescope.nvim",
    dependencies = {
      "nvim-lua/plenary.nvim",
      "nvim-treesitter/nvim-treesitter",
      {
        "nvim-telescope/telescope-fzf-native.nvim",
        build = "make",
      },
    },
    cmd = "Telescope",
    config = function(_)
      require("telescope").setup()
      -- To get fzf loaded and working with telescope, you need to call
      -- load_extension, somewhere after setup function:
      require("telescope").load_extension "fzf"
      require "plugins.configs.telescope"
    end,
  },
  -- Statusline
  -- A blazing fast and easy to configure neovim statusline plugin written in pure lua.
  {
    "nvim-lualine/lualine.nvim",
    opts = function() require "plugins.configs.lualine" end,
  },
  -- colorscheme
  {
    -- Rose-pine - Soho vibes for Neovim
    "rose-pine/neovim",
    name = "rose-pine",
    opts = {
      dark_variant = "main",
    },
  },
  -- LSP stuffs
  -- Portable package manager for Neovim that runs everywhere Neovim runs.
  -- Easily install and manage LSP servers, DAP servers, linters, and formatters.
  {
    "williamboman/mason.nvim",
    cmd = { "Mason", "MasonInstall", "MasonInstallAll", "MasonUninstall", "MasonUninstallAll", "MasonLog" },
    config = function() require "plugins.configs.mason" end,
  },
  {
    "williamboman/mason-lspconfig.nvim",
  },
  {
    "nvimtools/none-ls.nvim",
    event = { "BufReadPre", "BufNewFile" },
    dependencies = { "nvimtools/none-ls-extras.nvim" },
    lazy = true,
    config = function() require "plugins.configs.null-ls" end,
  },
  {
    "neovim/nvim-lspconfig",
    event = "VimEnter",
    lazy = false,
    config = function() require "plugins.configs.lspconfig" end,
  },
  {
    "hrsh7th/nvim-cmp",
    event = "InsertEnter",
    dependencies = {
      {
        -- snippet plugin
        "L3MON4D3/LuaSnip",
        dependencies = "rafamadriz/friendly-snippets",
        opts = { history = true, updateevents = "TextChanged,TextChangedI" },
        config = function(_, opts)
          require("luasnip").config.set_config(opts)
          require "plugins.configs.luasnip"
        end,
      },

      -- autopairing of (){}[] etc
      { "windwp/nvim-autopairs" },

      {
        "xiyaowong/transparent.nvim",
        lazy = false, -- ensure it runs at startup
        opts = {},    -- you can pass `groups` / `extra_groups` / `excludes` here
      },

      {
        'tidalcycles/vim-tidal',
        lazy = false
      },
      { 'lervag/vimtex' },
      { 'neovim/nvim-lspconfig' },
      { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' },
      { 'nvim-telescope/telescope.nvim',   dependencies = { 'nvim-lua/plenary.nvim' } },
      { 'neovim/nvim-lspconfig' },
      { 'folke/zen-mode.nvim' },




      -- cmp sources plugins
      {
        "saadparwaiz1/cmp_luasnip",
        "hrsh7th/cmp-nvim-lua",
        "hrsh7th/cmp-nvim-lsp",
        "hrsh7th/cmp-buffer",
        "hrsh7th/cmp-path",
        "onsails/lspkind.nvim",
      },
    },
    opts = function() require "plugins.configs.cmp" end,
  },
  -- Colorizer
  {
    "norcalli/nvim-colorizer.lua",
    config = function(_)
      require("colorizer").setup()

      -- execute colorizer as soon as possible
      vim.defer_fn(function() require("colorizer").attach_to_buffer(0) end, 0)
    end,
  },
  -- Keymappings
  {
    "folke/which-key.nvim",
    event = "VeryLazy",
    config = function() require("which-key").setup() end,
  },
}

local exist, custom = pcall(require, "custom")
local custom_plugins = exist and type(custom) == "table" and custom.plugins or {}

-- Check if there is any custom plugins
-- local ok, custom_plugins = pcall(require, "plugins.custom")
require("lazy").setup {
  spec = { builtin_plugins, custom_plugins },
  lockfile = vim.fn.stdpath "config" .. "/lazy-lock.json", -- lockfile generated after running update.
  defaults = {
    lazy = false,                                          -- should plugins be lazy-loaded?
    version = nil,
    -- version = "*", -- enable this to try installing the latest stable versions of plugins
  },
  ui = {
    icons = {
      ft = "",
      lazy = "󰂠",
      loaded = "",
      not_loaded = "",
    },
  },
  install = {
    -- install missing plugins on startup
    missing = true,
    -- try to load one of these colorschemes when starting an installation during startup
    colorscheme = { "rose-pine", "habamax" },
  },
  checker = {
    -- automatically check for plugin updates
    enabled = true,
    -- get a notification when new updates are found
    -- disable it as it's too annoying
    notify = false,
    -- check for updates every day
    frequency = 86400,
  },
  change_detection = {
    -- automatically check for config file changes and reload the ui
    enabled = true,
    -- get a notification when changes are found
    -- disable it as it's too annoying
    notify = false,
  },
  performance = {
    cache = {
      enabled = true,
    },
  },
  state = vim.fn.stdpath "state" .. "/lazy/state.json", -- state info for checker and other things
}



require('nvim-treesitter.configs').setup {
  ensure_installed = { 'latex', 'bibtex', 'comment' },
  highlight = { enable = true },
}


local nvim_lsp = require('lspconfig')
nvim_lsp.texlab.setup {
  settings = {
    texlab = {
      auxDirectory = "", -- optionally set build dir
      build = {
        executable = "latexmk",
        args = { "-pdf", "-interaction=nonstopmode", "-synctex=1", "%f" },
        onSave = true, -- build on save
      },
      forwardSearch = {
        executable = "zathura",
        args = { "--synctex-forward", "%l:1:%f", "%p" },
      },
      chktex = { onOpen = false, onEdit = false }, -- optional lint settings
    }
  }
}

-- Basic nvim-cmp setup (LSP completion)
local cmp = require('cmp')
cmp.setup({
  snippet = {
    expand = function(args) require('luasnip').lsp_expand(args.body) end,
  },
  sources = {
    { name = 'nvim_lsp' },
    { name = 'luasnip' },
  },
  mapping = require('cmp').mapping.preset.insert({
    ['<C-Space>'] = require('cmp').mapping.complete(),
    ['<CR>'] = require('cmp').mapping.confirm({ select = true }),
  })
})


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

-- configuration: change these to taste
M.zen_ratio = 0.90 -- try to use 80% of the editor width
M.zen_max   = 100  -- 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 })
