-- Svelte LSP configuration
-- Uses svelte-language-server installed via Mason

local status_ok, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp")
local capabilities = status_ok
    and cmp_nvim_lsp.default_capabilities(vim.lsp.protocol.make_client_capabilities())
    or vim.lsp.protocol.make_client_capabilities()

vim.lsp.config("svelte", {
    cmd = { "svelteserver", "--stdio" },
    filetypes = { "svelte" },
    capabilities = capabilities,
    root_markers = { "package.json", "svelte.config.js", ".git" },
    settings = {
        svelte = {
            enableTsPlugin = true,
            plugin = {
                svelte = {
                    enable = true,
                },
            },
        },
    },
})

-- Svelte-specific LSP attach handlers
vim.api.nvim_create_autocmd("LspAttach", {
    callback = function(args)
        local client = vim.lsp.get_client_by_id(args.data.client_id)
        if client and client.name == "svelte" then
            local bufnr = args.buf

            -- Restart Svelte language server
            vim.keymap.set("n", "<leader>sr", function()
                vim.cmd("LspRestart svelte")
            end, { buffer = bufnr, desc = "Svelte: Restart LSP" })

            -- Go to component definition (jumps to imported .svelte files)
            vim.keymap.set("n", "gD", function()
                vim.lsp.buf.declaration()
            end, { buffer = bufnr, desc = "Svelte: Go to declaration" })
        end
    end,
})

vim.lsp.enable("svelte")
