-- lua/plugins/dap.lua
return {
  { "mfussenegger/nvim-dap" },               -- core debugger client
  { "rcarriga/nvim-dap-ui", dependencies = { "mfussenegger/nvim-dap" } },

  -- Adapter bridge (Mason downloads the compiled server for us)
  {
    "mxsdev/nvim-dap-vscode-js",
    dependencies = { "mfussenegger/nvim-dap" },
    config = function()
      local mason_js = vim.fn.stdpath "data"
                   .. "/mason/packages/js-debug-adapter"  -- Mason path
      require("dap-vscode-js").setup {
        node_path     = "node",                            -- node binary
        debugger_path = mason_js,                          -- root dir of js-debug
        adapters      = { "pwa-node","pwa-chrome","pwa-msedge","node-terminal" }
      }
    end
  },

  -- Ensure js-debug-adapter is present (Mason does the download)
  {
    "williamboman/mason.nvim",
    cmd = { "Mason" },
    config = true,
  },
  {
    "williamboman/mason-lspconfig.nvim",  -- pull Mason registry
    opts = function(_, o)
      o.ensure_installed = o.ensure_installed or {}
      vim.list_extend(o.ensure_installed, { "js-debug-adapter" })
    end
  },

  -- Optional key-maps (adapt to your taste)
  {
    "mfussenegger/nvim-dap",
    keys = {
      { "<F5>",  function() require("dap").continue() end, desc="Start / Continue" },
      { "<F9>",  function() require("dap").toggle_breakpoint() end, desc="Toggle BP" },
      { "<F10>", function() require("dap").step_over() end, desc="Step over" },
      { "<F11>", function() require("dap").step_into() end, desc="Step into" },
      { "<S-F11>",function() require("dap").step_out() end, desc="Step out" },
    }
  },

  -- Debugger UI (optional)
  {
    "rcarriga/nvim-dap-ui",
    opts = {},
    keys = {
      { "<leader>du", function() require("dapui").toggle() end, desc="Dap-UI" },
    }
  }
}

-- -------------------------------------------------------------
-- Launch / attach configurations
-- -------------------------------------------------------------
local dap = require "dap"

dap.configurations.javascript = {
  -- 1. Run current file with node
  {
    name        = "Launch Node file",
    type        = "pwa-node",
    request     = "launch",
    program     = "${file}",
    cwd         = "${workspaceFolder}",
    stopOnEntry = false,
  },
  -- 2. Attach to an existing node process (started with --inspect)
  {
    name    = "Attach to node process",
    type    = "pwa-node",
    request = "attach",
    processId = require("dap.utils").pick_process
  },
  -- 3. Launch Chrome and attach to page
  {
    name    = "Launch Chrome & attach",
    type    = "pwa-chrome",
    request = "launch",
    url     = "http://localhost:8080",
    webRoot = "${workspaceFolder}",
    userDataDir = false   -- reuse your normal profile
  }
}

-- share same configs for TS
dap.configurations.typescript        = dap.configurations.javascript
dap.configurations.typescriptreact = dap.configurations.javascript
