-- ~/.config/nvim/after/syntax/hjson.lua
-- Или путь плагина: ~/.config/nvim/plugin/hjson.lua

vim.api.nvim_create_autocmd({ "BufRead", "BufNewFile" }, {
  pattern = "*.hjson",
  callback = function()
    vim.b.current_syntax = "hjson"

    -- Очистка предыдущих правил
    vim.cmd("syntax clear")

    -- Комментарии (высший приоритет)
    vim.cmd([[ syntax match hjsonLineComment "\/\/.*" ]])
    vim.cmd([[ syntax match hjsonLineComment "#.*" ]])
    vim.cmd([[ syntax region hjsonComment start="/\*" end="\*/" ]])

    -- Строки
    vim.cmd([[ syntax region hjsonString matchgroup=hjsonQuote start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=hjsonEscape ]])
    vim.cmd([[ syntax region hjsonString matchgroup=hjsonQuote start=+'+ skip=+\\\\\|\\'+ end=+'+ contains=hjsonEscape ]])
    vim.cmd([[ syntax region hjsonMLString matchgroup=hjsonQuote start=/'''/ end=/'''/ ]])

    -- Числа
    vim.cmd([[ syntax match hjsonNumber "-\=\<\%(0\|[1-9]\d*\)\%(\.\d\+\)\=\%([eE][-+]\=\d\+\)\=\>" ]])

    -- Булевы значения и null
    vim.cmd([[ syntax keyword hjsonBoolean true false ]])
    vim.cmd([[ syntax keyword hjsonNull null ]])

    -- Ключи объектов
    vim.cmd([[ syntax match hjsonKey "[^][{}:,\"'\s]\+" contained ]])
    vim.cmd([[ syntax match hjsonKeyUnquoted "[^][{}:,\"'\s]\+:"he=e-1 contains=hjsonKey,hjsonNoise ]])

    -- Пунктуация
    vim.cmd([[ syntax match hjsonNoise "[{}\[\],:]" ]])

    -- Escape-последовательности
    vim.cmd([[ syntax match hjsonEscape "\\[\\\"'/bfnrt]" contained ]])
    vim.cmd([[ syntax match hjsonEscape "\\u\x\{4}" contained ]])

    -- Строки без кавычек (низший приоритет)
    vim.cmd([[ syntax match hjsonStringUQ "[^][{}:,\"'\s]\+" contains=@NoSpell ]])

    -- Сворачивание структур
    vim.cmd([[ syntax region hjsonObject matchgroup=hjsonBraces start="{" end="}" transparent fold ]])
    vim.cmd([[ syntax region hjsonArray matchgroup=hjsonBraces start="\[" end="\]" transparent fold ]])

    -- Подсветка
    vim.cmd([[ highlight default link hjsonComment Comment ]])
    vim.cmd([[ highlight default link hjsonLineComment Comment ]])
    vim.cmd([[ highlight default link hjsonString String ]])
    vim.cmd([[ highlight default link hjsonMLString String ]])
    vim.cmd([[ highlight default link hjsonStringUQ String ]])
    vim.cmd([[ highlight default link hjsonEscape SpecialChar ]])
    vim.cmd([[ highlight default link hjsonNumber Number ]])
    vim.cmd([[ highlight default link hjsonBoolean Boolean ]])
    vim.cmd([[ highlight default link hjsonNull Constant ]])
    vim.cmd([[ highlight default link hjsonKey Label ]])
    vim.cmd([[ highlight default link hjsonNoise Delimiter ]])
    vim.cmd([[ highlight default link hjsonBraces Delimiter ]])
  end
})
