#!/bin/bash

# omarchy:summary=Toggle the active workspace between the master layout and the layout it had before

set -uo pipefail

# Usage: omarchy-toggle-master
#
# Goes through Omarchy's o.workspace_mode and its saved-mode files, like
# omarchy-hyprland-workspace-layout-toggle (SUPER + W), so the layout survives
# a reload or login and the two keys agree on what the workspace is: SUPER + W
# on a master workspace cycles on to dwindle. The layout master replaced is
# kept under STATE_DIR and restored by the next press; without one, the
# workspace goes back to the default layout. Named workspaces are skipped for
# the same reason Omarchy skips them: their negative id is read as a relative
# selector.

STATE="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy"
MODES_DIR="$STATE/workspace-layouts"
STATE_DIR="$STATE/master-toggle"

# Same replace-in-place notification as Omarchy's layout toggle, sharing its
# id file, so switching with either key leaves one current notification.
notify_layout() {
  local state="$STATE/workspace-layout-notification"
  local last id
  [[ -r $state ]] && read -r last <"$state"
  if id=$(omarchy-notification-send -p -r "${last:-0}" -g $'\U000f10ac' "$1") && [[ $id =~ ^[0-9]+$ ]]; then
    mkdir -p "$(dirname "$state")" && printf '%s\n' "$id" >"$state"
  fi
}

WORKSPACE=$(hyprctl activeworkspace -j | jq -r '.id')
[[ $WORKSPACE =~ ^[0-9]+$ ]] || exit 1
MODE_FILE="$MODES_DIR/$WORKSPACE.lua"
PREVIOUS_FILE="$STATE_DIR/$WORKSPACE"

CURRENT=$(omarchy-hyprland-workspace-layout-current)
DEFAULT=$(omarchy-hyprland-workspace-layout-default)

if [[ $CURRENT == master ]]; then
  NEW=$(cat "$PREVIOUS_FILE" 2>/dev/null)
  [[ $NEW =~ ^(dwindle|scrolling|floating)$ ]] || NEW=$DEFAULT
else
  NEW=master
fi

APPLY="o.workspace_mode({ workspace = \"$WORKSPACE\", mode = \"$NEW\" })"
if ! hyprctl eval "$APPLY" >/dev/null 2>&1; then
  notify_layout "$(omarchy-i18n layout.needsReload)"
  exit 1
fi

if [[ $NEW == master ]]; then
  mkdir -p "$STATE_DIR" && printf '%s\n' "$CURRENT" >"$PREVIOUS_FILE"
  # A layout change fires no event, so Ghostty is made the master here
  # (hypr/master.lua).
  hyprctl eval 'require("hypr.master").enforce()' >/dev/null
else
  rm -f "$PREVIOUS_FILE"
fi

# Back on the default, the workspace follows it again (as Omarchy does).
if [[ $NEW == "$DEFAULT" ]]; then
  rm -f "$MODE_FILE"
else
  mkdir -p "$MODES_DIR" && printf '%s\n' "$APPLY" >"$MODE_FILE"
fi

notify_layout "Workspace layout: $NEW"
omarchy-shell -q omarchy.workspaces refresh
omarchy-shell -q omarchy.dock refresh
