-- 1. Configuration
vim.lsp.config('ts_ls', {
    cmd = { "typescript-language-server", "--stdio" },
    filetypes = {
        "typescript",
        "typescriptreact",
        "typescript.tsx",
        "javascript",
        "javascriptreact",
        "javascript.jsx",
    },
    -- In 0.11, root_markers replaces root_dir logic
    root_markers = { "package.json", "tsconfig.json", "jsconfig.json", ".git" },
    settings = {
        javascript = {
            format = {
                enable = true,
                insertSpaceAfterCommaDelimiter = true,
                insertSpaceAfterSemicolon = true,
                insertSpaceBeforeAndAfterOperator = true,
                indentStyle = "smart",
                indentSize = 2,
            },
        },
        typescript = {
            format = {
                enable = true,
                insertSpaceAfterCommaDelimiter = true,
                insertSpaceAfterSemicolon = true,
                insertSpaceBeforeAndAfterOperator = true,
                indentStyle = "smart",
                indentSize = 2,
            },
        },
    },
})

-- 2. Global LspAttach for Keymaps
-- This works for all servers, so you only need to define it once (e.g., in user/lsp.lua)
vim.api.nvim_create_autocmd('LspAttach', {
    group = vim.api.nvim_create_augroup('UserLspConfig', {}),
    callback = function(ev)
        local opts = { buffer = ev.buf, noremap = true, silent = true }

        -- Modern way to set keymaps using the lua function directly
        vim.keymap.set('n', 'gd', vim.lsp.buf.definition, opts)
        vim.keymap.set('n', 'K', vim.lsp.buf.hover, opts)
        vim.keymap.set('n', '<leader>rn', vim.lsp.buf.rename, opts)
    end,
})

-- 3. Enable the server
vim.lsp.enable('ts_ls')
