-- Standalone autocmds (migrated from NvChad)

local autocmd = vim.api.nvim_create_autocmd

autocmd({ "BufRead", "BufNewFile" }, { pattern = "*.wesl",  command = "setfiletype wesl" })

-- Start treesitter highlighting for any buffer with an available parser
autocmd("FileType", {
  callback = function(args)
    local lang = vim.treesitter.language.get_lang(args.match)
    if lang and vim.treesitter.language.add(lang) then
      vim.treesitter.start(args.buf, lang)
    end
  end,
})

-- Register wgsl as the treesitter language for wesl files
vim.treesitter.language.register("wgsl", "wesl")

-- Terminal group
local terminal_group = vim.api.nvim_create_augroup("terminal", { clear = true })

-- Auto-close terminal buffers on exit
autocmd("TermClose", {
  group = terminal_group,
  command = "bdelete!"
})

-- Start terminal in insert mode for autoscroll
autocmd("TermOpen", {
  group = terminal_group,
  command = "startinsert"
})

-- User event that loads after UIEnter + only if file buf is there
-- This is used by plugins for lazy loading via "User FilePost" event
autocmd({ "UIEnter", "BufReadPost", "BufNewFile" }, {
  group = vim.api.nvim_create_augroup("FilePost", { clear = true }),
  callback = function(args)
    local file = vim.api.nvim_buf_get_name(args.buf)
    local buftype = vim.api.nvim_get_option_value("buftype", { buf = args.buf })

    if not vim.g.ui_entered and args.event == "UIEnter" then
      vim.g.ui_entered = true
    end

    if file ~= "" and buftype ~= "nofile" and vim.g.ui_entered then
      vim.api.nvim_exec_autocmds("User", { pattern = "FilePost", modeline = false })
      vim.api.nvim_del_augroup_by_name "FilePost"

      vim.schedule(function()
        vim.api.nvim_exec_autocmds("FileType", {})

        if vim.g.editorconfig then
          require("editorconfig").config(args.buf)
        end
      end)
    end
  end,
})
