-- macOS-style Cmd+Tab across workspaces (most recently used first).
--
-- Hold Cmd and press Tab: the first Tab jumps to the previously used
-- workspace (A). Each further Tab moves to the next workspace to the right
-- (by number), wrapping from the last one back to the first. Shift+Tab moves
-- to the left instead. Releasing Cmd commits: the workspace you landed on
-- becomes the most recent.
--
-- Toshy turns Cmd+Tab / Cmd+Shift+Tab into SUPER+CTRL+ALT(+SHIFT)+TAB and keeps
-- those modifiers held while Cmd is down (see "User Omarchy globals" in
-- ~/.config/toshy/toshy_config.py). The end of a cycle is detected here by
-- watching modifier releases; nothing else about key presses is looked at.

local mru = {}          -- workspace ids, most recent first
local cycling = false
local snapshot = {}
local index = 1
local held = {}         -- modifier keycodes currently down
local commit_timer = nil

-- xkb keycodes (evdev + 8) of the modifiers
local MODIFIERS = {
  [37] = true, [105] = true,   -- Ctrl L/R
  [50] = true, [62] = true,    -- Shift L/R
  [64] = true, [108] = true,   -- Alt L/R
  [133] = true, [134] = true,  -- Super L/R
}

local function current_id()
  local ws = hl.get_active_workspace()
  if ws and ws.id and ws.id > 0 then return ws.id end
  return nil
end

local function remember(id)
  if not id then return end
  for i = #mru, 1, -1 do
    if mru[i] == id then table.remove(mru, i) end
  end
  table.insert(mru, 1, id)
end

local function existing()
  local alive = {}
  for _, ws in ipairs(hl.get_workspaces()) do
    if ws.id and ws.id > 0 then alive[ws.id] = true end
  end
  return alive
end

local function commit()
  commit_timer = nil
  if not cycling then return end
  if next(held) ~= nil then return end -- Cmd still down
  cycling = false
  remember(snapshot[index])
end

local function sorted_existing()
  local ids = {}
  for id in pairs(existing()) do table.insert(ids, id) end
  table.sort(ids)
  return ids
end

-- Workspace next to `from` in numeric order, wrapping around.
local function neighbour(ids, from, delta)
  local pos = 1
  for i, id in ipairs(ids) do
    if id == from then pos = i; break end
  end
  return ids[((pos - 1 + delta) % #ids) + 1]
end

local function step(delta)
  return function()
    if commit_timer then commit_timer:set_enabled(false); commit_timer = nil end
    local ids = sorted_existing()
    if #ids < 2 then return end
    local target
    if not cycling then
      local cur = current_id()
      remember(cur)
      cycling = true
      if delta > 0 then
        -- First Tab: previously used workspace (A).
        local alive = existing()
        for i = 2, #mru do
          if alive[mru[i]] then target = mru[i]; break end
        end
      end
      target = target or neighbour(ids, cur, delta)
    else
      target = neighbour(ids, snapshot[index], delta)
    end
    snapshot = { target }
    index = 1
    hl.dispatch(hl.dsp.focus({ workspace = target }))
  end
end

hl.on("workspace.active", function()
  if not cycling then remember(current_id()) end
end)

hl.on("input.keyboard.key", function(code, _, state)
  if not MODIFIERS[code] then return end
  if state == 1 then
    held[code] = true
  elseif state == 0 then
    held[code] = nil
    -- Wait a moment: Toshy briefly releases and re-presses modifiers while it
    -- sends a chord, and that must not end the cycle.
    if cycling and next(held) == nil and not commit_timer then
      commit_timer = hl.timer(commit, { timeout = 150, type = "oneshot" })
    end
  end
end)

remember(current_id())

o.bind("SUPER + CTRL + ALT + TAB", "Cmd+Tab: last workspace, then step right", step(1))
o.bind("SUPER + CTRL + ALT + SHIFT + TAB", "Cmd+Shift+Tab: step left", step(-1))
