local layout = "EN"

local function update_layout()
  vim.system({ "im-select" }, { text = true }, function(result)
    if result.stdout then
      layout = result.stdout:find("Russian") and "RU" or "EN"
    end
  end)
end

-- Update layout in background every second, never blocks UI
local timer = vim.loop.new_timer()
timer:start(0, 1000, vim.schedule_wrap(update_layout))

local function keyboard_layout()
  return layout
end

local function keyboard_layout_color()
  if layout == "RU" then
    return { bg = "#f38ba8", fg = "#1e1e2e", gui = "bold" }
  end
  return { bg = "#a6e3a1", fg = "#1e1e2e", gui = "bold" }
end

return {
  "nvim-lualine/lualine.nvim",
  dependencies = { "nvim-tree/nvim-web-devicons" },
  opts = {
    options = {
      theme = "auto",
      component_separators = { left = "", right = "" },
      section_separators = { left = "", right = "" },
    },
    sections = {
      lualine_a = { "mode" },
      lualine_b = {
        { keyboard_layout, color = keyboard_layout_color },
        "branch",
        "diff",
        "diagnostics",
      },
      lualine_c = { { "filename", path = 1 } },
      lualine_x = { "encoding", "filetype" },
      lualine_y = { "progress" },
      lualine_z = { "location" },
    },
  },
}
