-- Magnet (macOS) window shortcuts for Hyprland.
--
-- Magnet uses Ctrl+Option. With Toshy running, physical Ctrl reaches Hyprland
-- as SUPER (Toshy maps it back for terminals), so Ctrl+Opt = SUPER + ALT here
-- and Ctrl+Opt+Cmd = SUPER + CTRL + ALT.
--
-- Two kinds of windows meet here:
--   * Magnet windows: floated by one of these shortcuts. They carry the
--     "magnet" tag and go back into the tiling as soon as they share the
--     workspace with other windows (on a half shortcut, or when a new app
--     opens or is moved next to them).
--   * Windows you floated yourself (no tag): shortcuts just snap them.
--
-- Halves: a window alone on its workspace floats and snaps to that half; with
-- company it tiles and moves to that side, flipping the split if needed, and
-- the split is reset to an even 50/50.
-- Thirds, quarters, center and maximize always float and snap.

local TAG = "magnet"
local LEGACY_TAGS = { ["magnet-half"] = true } -- tag used by older versions
local TOL = 2 -- px tolerance for geometry comparisons (fractional scaling)

-- Run fn shortly after Hyprland has applied the dispatches before it.
local function later(fn)
  hl.timer(function() pcall(fn) end, { type = "oneshot", timeout = 20 })
end

local function target(w) return "address:" .. w.address end
local function ws_id(w) return w.workspace and tostring(w.workspace.id) end

local function snapped(w)
  for _, t in ipairs(w.tags or {}) do
    t = t:gsub("%*$", "")
    if t == TAG or LEGACY_TAGS[t] then return true end
  end
  return false
end

local function find(addr, id)
  for _, w in ipairs(hl.get_workspace_windows(id)) do
    if w.address == addr then return w end
  end
end

local function monitor_of(w)
  local ok, m = pcall(function() return w.monitor end)
  if ok and m then return m end
  return hl.get_active_monitor()
end

local function gap()
  local ok, v = pcall(hl.get_config, "general.gaps_out")
  if ok and type(v) == "table" and v.top then return v.top end
  if ok and type(v) == "number" then return v end
  return 10
end

-- Usable area of a monitor in logical pixels (minus bar and gaps).
local function area(m)
  local r = m.reserved or {}
  local g = gap()
  local w = m.width / m.scale
  local h = m.height / m.scale
  local x = m.x + (r.left or 0) + g / 2
  local y = m.y + (r.top or 0) + g / 2
  return x, y, w - (r.left or 0) - (r.right or 0) - g, h - (r.top or 0) - (r.bottom or 0) - g, g
end

-- Float a window, mark it as a Magnet window, and place it at a fraction of
-- its monitor.
local function snap_to(w, fx, fy, fw, fh)
  local t = target(w)
  local x, y, aw, ah, g = area(monitor_of(w))
  hl.dispatch(hl.dsp.window.float({ action = "on", window = t }))
  if not snapped(w) then
    hl.dispatch(hl.dsp.window.tag({ tag = "+" .. TAG, window = t }))
  end
  hl.dispatch(hl.dsp.window.resize({
    x = math.floor(aw * fw - g), y = math.floor(ah * fh - g), window = t,
  }))
  hl.dispatch(hl.dsp.window.move({
    x = math.floor(x + aw * fx + g / 2), y = math.floor(y + ah * fy + g / 2), window = t,
  }))
end

local function place(fx, fy, fw, fh)
  return function()
    local w = hl.get_active_window()
    if w then snap_to(w, fx, fy, fw, fh) end
  end
end

-- Put a Magnet window back into the tiling.
local function retile(w)
  local t = target(w)
  for _, tag in ipairs({ TAG, "magnet-half" }) do
    hl.dispatch(hl.dsp.window.tag({ tag = "-" .. tag, window = t }))
  end
  hl.dispatch(hl.dsp.window.float({ action = "off", window = t }))
end

-- Re-tile every Magnet window on a workspace, so floats can't pile up.
local function retile_all(id)
  for _, o in ipairs(hl.get_workspace_windows(id)) do
    if o.floating and snapped(o) then retile(o) end
  end
end

-- Other windows on w's workspace that belong to the layout: tiled windows and
-- Magnet windows. Windows you floated yourself don't count.
local function has_company(w)
  for _, o in ipairs(hl.get_workspace_windows(ws_id(w))) do
    if o.address ~= w.address and (not o.floating or snapped(o)) then
      return true
    end
  end
  return false
end

-- Which half a floating window sits in, judged on its own monitor.
local function side_of(w)
  local m = monitor_of(w)
  local mw, mh = m.width / m.scale, m.height / m.scale
  local cx = w.at.x + w.size.x / 2 - m.x
  local cy = w.at.y + w.size.y / 2 - m.y
  if w.size.x > mw * 0.75 then
    return cy < mh / 2 and "u" or "d"
  end
  return cx < mw / 2 and "l" or "r"
end

local function tiled(addr, id)
  local me, others = nil, {}
  for _, o in ipairs(hl.get_workspace_windows(id)) do
    if not o.floating then
      if o.address == addr then me = o else others[#others + 1] = o end
    end
  end
  return me, others
end

-- True when b lies beside a (horizontal) or above/below it (vertical).
local function apart(a, b, horizontal)
  if horizontal then
    return b.at.x + b.size.x <= a.at.x + TOL or b.at.x >= a.at.x + a.size.x - TOL
  end
  return b.at.y + b.size.y <= a.at.y + TOL or b.at.y >= a.at.y + a.size.y - TOL
end

-- True when b lies further toward dir than a.
local function further(a, b, dir)
  if dir == "l" then return b.at.x < a.at.x - TOL end
  if dir == "r" then return b.at.x > a.at.x + TOL end
  if dir == "u" then return b.at.y < a.at.y - TOL end
  return b.at.y > a.at.y + TOL
end

-- Move a tiled window to side dir: flip the split first when its neighbours
-- run the other way (stacked, but Left/Right pressed), then swap toward dir.
-- Calls done() at the end, after any deferred step.
local function to_side(addr, id, dir, done)
  done = done or function() end
  local me, others = tiled(addr, id)
  if not me or #others == 0 then return done() end
  local horizontal = dir == "l" or dir == "r"
  hl.dispatch(hl.dsp.focus({ window = "address:" .. addr }))

  local function finish()
    local me2, others2 = tiled(addr, id)
    if me2 then
      for _, o in ipairs(others2) do
        if further(me2, o, dir) then
          hl.dispatch(hl.dsp.window.swap({ direction = dir }))
          break
        end
      end
    end
    done()
  end

  for _, o in ipairs(others) do
    if apart(me, o, horizontal) then return finish() end
  end
  hl.dispatch(hl.dsp.layout("togglesplit"))
  later(finish)
end

-- Halves: snap when alone; with company, tile and move to that side.
local function half(dir, fx, fy, fw, fh)
  return function()
    local w = hl.get_active_window()
    if not w then return end
    if (w.floating and not snapped(w)) or not has_company(w) then
      return snap_to(w, fx, fy, fw, fh)
    end
    local id, addr = ws_id(w), w.address
    retile_all(id)
    later(function()
      to_side(addr, id, dir, function()
        -- Make the split an even 50/50 (dwindle ratio 1.0 = equal halves).
        -- Hyprland 0.56 wants the value before "exact".
        hl.dispatch(hl.dsp.focus({ window = "address:" .. addr }))
        hl.dispatch(hl.dsp.layout("splitratio 1 exact"))
      end)
    end)
  end
end

-- A tiled window arriving next to Magnet windows (opened or moved there):
-- re-tile them so it fills the free space instead of the whole screen behind
-- them. The first Magnet window keeps its side; focus stays on the newcomer.
local function rejoin(new)
  if not new or new.floating then return end
  local id = ws_id(new)
  if not id then return end
  local first
  for _, o in ipairs(hl.get_workspace_windows(id)) do
    if o.address ~= new.address and o.floating and snapped(o) then
      first = first or o
    end
  end
  if not first then return end
  local side, addr, new_addr = side_of(first), first.address, new.address
  retile_all(id)
  later(function()
    to_side(addr, id, side, function()
      hl.dispatch(hl.dsp.focus({ window = "address:" .. new_addr }))
    end)
  end)
end

hl.on("window.open", function(window)
  later(function() rejoin(window) end)
end)
hl.on("window.move_to_workspace", function(window)
  later(function()
    local ok, addr = pcall(function() return window.address end)
    if not ok or not addr then return end
    local w = hl.get_window and hl.get_window("address:" .. addr) or window
    rejoin(w)
  end)
end)

local function maximize()
  local w = hl.get_active_window()
  if not w then return end
  if w.floating then
    snap_to(w, 0, 0, 1, 1)
  else
    hl.dispatch(hl.dsp.window.fullscreen({ mode = "maximized", action = "toggle" }))
  end
end

local function center()
  local w = hl.get_active_window()
  if not w then return end
  local t = target(w)
  local _, _, aw, ah = area(monitor_of(w))
  hl.dispatch(hl.dsp.window.float({ action = "on", window = t }))
  if not snapped(w) then
    hl.dispatch(hl.dsp.window.tag({ tag = "+" .. TAG, window = t }))
  end
  hl.dispatch(hl.dsp.window.resize({ x = math.floor(aw * 0.6), y = math.floor(ah * 0.7), window = t }))
  hl.dispatch(hl.dsp.window.center({ window = t }))
end

local function restore()
  local w = hl.get_active_window()
  if w then retile(w) end
end

local third, two_thirds = 1 / 3, 2 / 3

-- Displaced Omarchy defaults (SUPER + ALT + arrows/RETURN/F/G/K):
-- move-into-group, Tmux, full width, ungroup, Tmux keybindings.
-- Tmux moves to SUPER + SHIFT + ALT + RETURN; the rest stay reachable via
-- Super+G (grouping) and Super+F (fullscreen).
o.rebind("SUPER + ALT + LEFT", "Magnet: left half", half("l", 0, 0, 0.5, 1))
o.rebind("SUPER + ALT + RIGHT", "Magnet: right half", half("r", 0.5, 0, 0.5, 1))
o.rebind("SUPER + ALT + UP", "Magnet: top half", half("u", 0, 0, 1, 0.5))
o.rebind("SUPER + ALT + DOWN", "Magnet: bottom half", half("d", 0, 0.5, 1, 0.5))
o.rebind("SUPER + ALT + RETURN", "Magnet: maximize", maximize)
o.bind("SUPER + ALT + C", "Magnet: center", center)
o.bind("SUPER + ALT + BACKSPACE", "Magnet: restore (tile again)", restore)

o.bind("SUPER + ALT + U", "Magnet: top left quarter", place(0, 0, 0.5, 0.5))
o.bind("SUPER + ALT + I", "Magnet: top right quarter", place(0.5, 0, 0.5, 0.5))
o.bind("SUPER + ALT + J", "Magnet: bottom left quarter", place(0, 0.5, 0.5, 0.5))
o.rebind("SUPER + ALT + K", "Magnet: bottom right quarter", place(0.5, 0.5, 0.5, 0.5))

o.bind("SUPER + ALT + D", "Magnet: left third", place(0, 0, third, 1))
o.rebind("SUPER + ALT + F", "Magnet: center third", place(third, 0, third, 1))
o.rebind("SUPER + ALT + G", "Magnet: right third", place(two_thirds, 0, third, 1))
o.bind("SUPER + ALT + E", "Magnet: left two thirds", place(0, 0, two_thirds, 1))
o.bind("SUPER + ALT + T", "Magnet: right two thirds", place(third, 0, two_thirds, 1))

o.bind("SUPER + CTRL + ALT + LEFT", "Magnet: previous display", o.workspaces.move_window_to_monitor("l"))
o.bind("SUPER + CTRL + ALT + RIGHT", "Magnet: next display", o.workspaces.move_window_to_monitor("r"))

o.bind("SUPER + SHIFT + ALT + RETURN", "Tmux", { omarchy = "terminal-tmux" })
