-- Theme state file watcher
-- Watches ~/.config/theme-state and switches between bearded-arc / bearded-arc-light

local M = {}

local state_file = vim.fn.expand("~/.config/theme-state")
local current_theme = nil

local function apply_theme(name)
  if name == current_theme then return end
  current_theme = name
  if name == "light" then
    vim.cmd("colorscheme bearded-arc-light")
  else
    vim.cmd("colorscheme bearded-arc")
  end
  -- Re-setup lualine with the new palette
  if package.loaded["configs.lualine"] then
    require("configs.lualine").setup()
  end
end

local function read_state()
  local f = io.open(state_file, "r")
  if f then
    local state = f:read("*a"):gsub("%s+", "")
    f:close()
    return state == "light" and "light" or "dark"
  end
  return "dark"
end

function M.setup()
  -- Apply initial theme on startup
  apply_theme(read_state())

  -- Watch for changes
  local uv = vim.uv or vim.loop
  local watcher = uv.new_fs_event()
  if watcher then
    watcher:start(state_file, {}, function(err, filename, events)
      if err then return end
      vim.schedule(function()
        apply_theme(read_state())
      end)
    end)
  end
end

return M
