#!/usr/bin/env bash
# ==============================================================================
# gamectl - Sovereign TUI Game Manager & Launcher (Standalone Bundle)
# Auto-generated by scripts/build.sh. Do not edit directly.
# Edit modular sources under src/ and run ./scripts/build.sh to recompile.
# ==============================================================================

# --- [MODULE] src/core/00_header.sh ---
# ==============================================================================
# GAMECTL - SOVEREIGN TUI GAME MANAGER & LAUNCHER (ZERO-BLOAT)
# ==============================================================================
# Lightweight, native Linux gaming hub:
# - Library scanner for local/standalone games
# - Automatic GBE Fork / runner inspection
# - Savegame snapshot rotation (auto-backup before launch)
# - Performance profile wrapper (Mesa GL thread, CPU governor)
# - 1-key sync to remote companion host via rsync over SSH
# - Live Steam Store search + ProtonDB rating via fzf
# ==============================================================================

set -uo pipefail

SELF_BIN="$(readlink -f "${BASH_SOURCE[0]}")"
GBE_X64="${GAMECTL_GBE_X64:-$HOME/.local/share/gbe-fork/regular/x64/libsteam_api.so}"
GBE_X86="${GAMECTL_GBE_X86:-$HOME/.local/share/gbe-fork/regular/x86/libsteam_api.so}"
GBE_WIN_X64="${GAMECTL_GBE_WIN_X64:-$HOME/.local/share/gbe-fork/windows/release/regular/x64/steam_api64.dll}"
GBE_WIN_X86="${GAMECTL_GBE_WIN_X86:-$HOME/.local/share/gbe-fork/windows/release/regular/x86/steam_api.dll}"

# ANSI Styling Tokens (Gamer Dark / Tokyo Night Theme)
UI_RST=$'\033[0m'
UI_BOLD=$'\033[1m'
UI_DIM=$'\033[38;5;244m'
UI_CYAN=$'\033[1;38;5;117m'
UI_ICE=$'\033[1;38;5;153m'
UI_PURPLE=$'\033[1;38;5;141m'
UI_GREEN=$'\033[1;38;5;120m'
UI_AMBER=$'\033[1;38;5;221m'
UI_RED=$'\033[1;38;5;203m'
UI_BOX=$'\033[38;5;60m'

# Pill badges for hotkeys
UI_PILL_ENTER=$'\033[1;38;5;232;48;5;117m ENTER \033[0m'
UI_PILL_CTRLI=$'\033[1;38;5;232;48;5;141m CTRL-I \033[0m'
UI_PILL_CTRLO=$'\033[1;38;5;232;48;5;221m CTRL-O \033[0m'
UI_PILL_CTRLP=$'\033[1;38;5;232;48;5;120m CTRL-P \033[0m'
UI_PILL_CTRLF=$'\033[1;38;5;232;48;5;153m CTRL-F \033[0m'
UI_PILL_CTRLD=$'\033[1;38;5;232;48;5;141m CTRL-D \033[0m'
UI_PILL_CTRLS=$'\033[1;38;5;232;48;5;117m CTRL-S \033[0m'
UI_PILL_CTRLB=$'\033[1;38;5;232;48;5;221m CTRL-B \033[0m'
UI_PILL_CTRLK=$'\033[1;38;5;232;48;5;203m CTRL-K \033[0m'
UI_PILL_ESC=$'\033[1;38;5;232;48;5;248m ESC \033[0m'

# Central Modern FZF Configuration (Seamless transparent theme with rounded borders)
export FZF_DEFAULT_OPTS="--ansi --layout=reverse --border=rounded --info=inline-right --scrollbar=│ --prompt=' > ' --pointer='▶' --marker='*' --color='bg+:#282a36,bg:-1,spinner:#bd93f9,hl:#ff79c6' --color='fg:#f8f8f2,header:#8be9fd,info:#bd93f9,pointer:#50fa7b' --color='marker:#50fa7b,fg+:#ffffff,prompt:#bd93f9,hl+:#ff79c6' --color='border:#6272a4,label:#bd93f9,header-border:#6272a4,preview-border:#6272a4'"


# --- [MODULE] src/core/10_utils.sh ---
# Resolve GBE template file based on platform and architecture
get_gbe_template() {
    local platform="${1:-linux}" # "linux" or "windows"
    local arch="${2:-x64}"       # "x64" or "x86"
    local p=""
    if [ "$platform" = "windows" ]; then
        if [ "$arch" = "x64" ]; then
            for p in "${GAMECTL_GBE_WIN_X64:-}" \
                     "$HOME/.local/share/gbe-fork/windows/release/regular/x64/steam_api64.dll" \
                     "$HOME/.local/share/gbe-fork/windows/regular/x64/steam_api64.dll" \
                     "$HOME/.local/share/gbe-fork/regular/x64/steam_api64.dll" \
                     "$HOME/.local/share/gbe-fork/windows/release/experimental/x64/steam_api64.dll"; do
                [ -n "$p" ] && [ -f "$p" ] && echo "$p" && return 0
            done
        else
            for p in "${GAMECTL_GBE_WIN_X86:-}" \
                     "$HOME/.local/share/gbe-fork/windows/release/regular/x86/steam_api.dll" \
                     "$HOME/.local/share/gbe-fork/windows/regular/x86/steam_api.dll" \
                     "$HOME/.local/share/gbe-fork/regular/x86/steam_api.dll" \
                     "$HOME/.local/share/gbe-fork/windows/release/experimental/x86/steam_api.dll"; do
                [ -n "$p" ] && [ -f "$p" ] && echo "$p" && return 0
            done
        fi
    else
        if [ "$arch" = "x64" ]; then
            for p in "${GAMECTL_GBE_X64:-}" \
                     "$HOME/.local/share/gbe-fork/regular/x64/libsteam_api.so" \
                     "$HOME/.local/share/gbe-fork/experimental/x64/libsteam_api.so"; do
                [ -n "$p" ] && [ -f "$p" ] && echo "$p" && return 0
            done
        else
            for p in "${GAMECTL_GBE_X86:-}" \
                     "$HOME/.local/share/gbe-fork/regular/x86/libsteam_api.so" \
                     "$HOME/.local/share/gbe-fork/experimental/x86/libsteam_api.so"; do
                [ -n "$p" ] && [ -f "$p" ] && echo "$p" && return 0
            done
        fi
    fi
    return 1
}

# Resolve remote sync host (optional)
get_remote_host() {
    local host="${GAMECTL_REMOTE_HOST:-${GAMECTL_COMPANION_HOST:-${GAMECTL_SYNC_HOST:-${GAMECTL_TUF_HOST:-}}}}"
    if [ -z "$host" ] && [ -f "$HOME/.config/gamectl/remote_host" ]; then
        host=$(head -n 1 "$HOME/.config/gamectl/remote_host" | tr -d '[:space:]')
    fi
    echo "$host"
}

# Pre-flight cleanup of orphaned sockets and locks
clean_stale_locks() {
    local run_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$UID}"
    rm -f /tmp/SteaMidra-* /tmp/steam_chrome_shmem_* /tmp/steam_chrome_overlay_* 2>/dev/null || true
    rm -f "$run_dir"/SteaMidra-* "$run_dir"/steam_chrome_* 2>/dev/null || true
    rm -f "$HOME/.config/SLSsteam/cache/.picsbuffer.lock" 2>/dev/null || true
}

# Ephemeral cache tier for JSON APIs (Steam Store & ProtonDB) with TTL
fetch_cached_json() {
    local url="${1:-}"
    local cache_key="${2:-}"
    local ttl="${3:-3600}"

    if [ -z "$url" ] || [ -z "$cache_key" ]; then
        return 1
    fi

    local cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/gamectl"
    mkdir -p "$cache_dir" 2>/dev/null || true

    local safe_key
    safe_key=$(echo "$cache_key" | tr -cd '[:alnum:]_-')
    local cache_file="$cache_dir/${safe_key}.json"

    local now
    now=$(date +%s)

    # 1. Check existing cache validity against TTL
    if [ -f "$cache_file" ]; then
        local mtime
        mtime=$(stat -c %Y "$cache_file" 2>/dev/null || stat -f %m "$cache_file" 2>/dev/null || echo 0)
        local age=$(( now - mtime ))
        if [ "$age" -ge 0 ] && [ "$age" -lt "$ttl" ] && [ -s "$cache_file" ]; then
            cat "$cache_file"
            return 0
        fi
    fi

    # 2. Fetch fresh content with timeout and atomic replacement
    local tmp_file="${cache_file}.tmp.$$"
    local fetched
    fetched=$(curl -s --connect-timeout 2 --max-time 4 "$url" 2>/dev/null || true)

    if [ -n "$fetched" ] && [ "$fetched" != "null" ]; then
        # Ensure it contains valid JSON before caching
        if echo "$fetched" | jq . >/dev/null 2>&1; then
            echo "$fetched" > "$tmp_file" 2>/dev/null && mv -f "$tmp_file" "$cache_file" 2>/dev/null || rm -f "$tmp_file" 2>/dev/null
            echo "$fetched"
            return 0
        fi
    fi
    rm -f "$tmp_file" 2>/dev/null || true

    # 3. Fallback to stale cache if network/API failed
    if [ -s "$cache_file" ]; then
        cat "$cache_file"
        return 0
    fi

    return 1
}

# Auto-backup savegame (Rolling 3 snapshots)
backup_save() {
    local game_dir="$1"
    local is_quiet="${2:-false}"
    local save_dir="$game_dir/saves"
    if [ -d "$save_dir" ]; then
        local snap_dir="$game_dir/.save_snapshots"
        mkdir -p "$snap_dir"
        [ -d "$snap_dir/slot2" ] && rm -rf "$snap_dir/slot3" && mv "$snap_dir/slot2" "$snap_dir/slot3"
        [ -d "$snap_dir/slot1" ] && mv "$snap_dir/slot1" "$snap_dir/slot2"
        cp -a "$save_dir" "$snap_dir/slot1"
        echo "[INFO] Save snapshot created successfully in slot1 ($snap_dir/slot1)"
    else
        if [ "$is_quiet" = true ]; then
            return 0
        fi
        echo "[WARN] Portable saves directory ($save_dir) not found." >&2
        echo "       Game has not been injected with GBE Fork or lacks an isolated save directory." >&2
        echo "       Press <CTRL-I> first to enable portable saves." >&2
        return 1
    fi
}

# Dynamic executable finder for game directory
find_game_binary() {
    local dir="$1"
    local base
    base=$(basename "$dir")
    local clean_base="${base// /}"
    local lower_base="${base,,}"
    local lower_clean="${clean_base,,}"

    # Priority 1: Common launch scripts or matching names
    local candidates=(
        "start.sh" "run.sh" "launch.sh" "start" "run"
        "$base" "$clean_base" "$lower_base" "$lower_clean"
    )
    for c in "${candidates[@]}"; do
        if [ -x "$dir/$c" ] && [ ! -d "$dir/$c" ]; then
            echo "$c"
            return 0
        fi
    done

    # Priority 2: Any root executable file excluding assets/libs/runtime dumps
    local f fname
    for f in "$dir"/*; do
        if [ -x "$f" ] && [ ! -d "$f" ]; then
            fname=$(basename "$f")
            case "$fname" in
                *.so|*.so.*|*.dll|*.dylib|installscript.vdf|*.png|*.bmp|*.txt|*.pkg|createdump|monoconfig|monomachineconfig)
                    continue
                    ;;
                *)
                    echo "$fname"
                    return 0
                    ;;
            esac
        fi
    done

    # Priority 3: Windows executables matching title/folder name
    local win_candidates=(
        "$base.exe" "$clean_base.exe" "$lower_base.exe" "$lower_clean.exe"
    )
    for c in "${win_candidates[@]}"; do
        if [ -f "$dir/$c" ] && [ ! -d "$dir/$c" ]; then
            chmod +x "$dir/$c" 2>/dev/null || true
            echo "$c"
            return 0
        fi
    done

    # Priority 4: Any root .exe excluding setup/redist/crash handlers
    for f in "$dir"/*.exe "$dir"/*.EXE; do
        [ -f "$f" ] || continue
        fname=$(basename "$f")
        case "$fname" in
            UnityCrashHandler*|*unins*|*setup*|*installer*|*redist*|DXSETUP*|vcredist*|dotnet*|vc_redist*|*CrashReport*)
                continue
                ;;
            *)
                chmod +x "$f" 2>/dev/null || true
                echo "$fname"
                return 0
                ;;
        esac
    done

    # Priority 5: Subdirectory .exe in standard game binary folders
    for sub in "bin" "bin/x64" "bin/Win64" "Binaries/Win64" "Binaries/Win32" "x64"; do
        if [ -d "$dir/$sub" ]; then
            for f in "$dir/$sub"/*.exe "$dir/$sub"/*.EXE; do
                [ -f "$f" ] || continue
                fname=$(basename "$f")
                case "$fname" in
                    UnityCrashHandler*|*unins*|*setup*|*installer*|*redist*|DXSETUP*|vcredist*|dotnet*|vc_redist*|*CrashReport*)
                        continue
                        ;;
                    *)
                        chmod +x "$f" 2>/dev/null || true
                        echo "$sub/$fname"
                        return 0
                        ;;
                esac
            done
        fi
    done

    return 1
}

# --- [MODULE] src/steam/20_discovery.sh ---

# Discover active Steam root directory across standard, custom, Flatpak, and Snap installations
get_steam_root() {
    if [ -n "${STEAM_ROOT:-}" ] && [ -d "$STEAM_ROOT" ]; then
        echo "$STEAM_ROOT"
        return 0
    fi

    local candidate
    for candidate in \
        "$HOME/.local/share/Steam" \
        "$HOME/.steam/steam" \
        "$HOME/.steam/root" \
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam" \
        "$HOME/snap/steam/common/.local/share/Steam"; do
        if [ -d "$candidate" ]; then
            echo "$candidate"
            return 0
        fi
    done

    return 1
}

# Discover active primary steamapps directory
get_steam_primary_apps() {
    local s_root
    s_root="$(get_steam_root 2>/dev/null || true)"
    if [ -n "$s_root" ] && [ -d "$s_root/steamapps" ]; then
        echo "$s_root/steamapps"
        return 0
    fi

    local first_lib
    first_lib="$(get_steam_libraries 2>/dev/null | head -n 1 || true)"
    if [ -n "$first_lib" ] && [ -d "$first_lib" ]; then
        echo "$first_lib"
        return 0
    fi

    echo "$HOME/.local/share/Steam/steamapps"
}

# Discover all configured Steam library paths with deduplication
get_steam_libraries() {
    declare -A seen_libs=()
    local candidate_roots=(
        "${STEAM_ROOT:-}"
        "$HOME/.local/share/Steam"
        "$HOME/.steam/steam"
        "$HOME/.steam/root"
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam"
        "$HOME/snap/steam/common/.local/share/Steam"
    )

    for root in "${candidate_roots[@]}"; do
        [ -n "$root" ] && [ -d "$root" ] || continue

        local primary="$root/steamapps"
        if [ -d "$primary" ]; then
            local real_primary
            real_primary="$(realpath "$primary" 2>/dev/null || echo "$primary")"
            if [ -z "${seen_libs["$real_primary"]:-}" ]; then
                seen_libs["$real_primary"]=1
                echo "$primary"
            fi
        fi

        # Check libraryfolders.vdf
        local vdf_candidates=(
            "$root/steamapps/libraryfolders.vdf"
            "$root/config/libraryfolders.vdf"
        )
        for vdf in "${vdf_candidates[@]}"; do
            [ -f "$vdf" ] || continue
            local line p_path
            while read -r line; do
                p_path=$(echo "$line" | sed -E 's/.*"path"[[:space:]]+"([^"]+)".*/\1\/steamapps/')
                if [ -d "$p_path" ]; then
                    local real_p
                    real_p="$(realpath "$p_path" 2>/dev/null || echo "$p_path")"
                    if [ -z "${seen_libs["$real_p"]:-}" ]; then
                        seen_libs["$real_p"]=1
                        echo "$p_path"
                    fi
                fi
            done < <(grep -E '^\s*"path"' "$vdf" 2>/dev/null || true)
        done
    done
}

# Scan installed games dynamically in standard & custom paths
scan_installed_games() {
    local is_formatted=false
    local force_refresh=false

    for arg in "$@"; do
        case "$arg" in
            --formatted|-f) is_formatted=true ;;
            --refresh|--no-cache|-r) force_refresh=true ;;
        esac
    done

    local run_uid="${UID:-$(id -u)}"
    local cache_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$run_uid}"
    mkdir -p -m 700 "$cache_dir" 2>/dev/null || true
    local cache_file="$cache_dir/scancache.tab"

    # Fast-path: Check cache validity (TTL: 60s, invalidated if candidate library directories are newer)
    local use_cached=false
    if [ "$force_refresh" = false ] && [ -f "$cache_file" ]; then
        local now mtime
        now=$(date +%s)
        mtime=$(stat -c%Y "$cache_file" 2>/dev/null || echo 0)
        if [ $((now - mtime)) -lt 60 ]; then
            use_cached=true
            local lib_check
            for lib_check in "$HOME/Games" "$HOME/.local/share/Steam/steamapps" "$HOME/.local/share/lutris/games"; do
                if [ -d "$lib_check" ] && [ "$lib_check" -nt "$cache_file" ]; then
                    use_cached=false
                    break
                fi
            done
        fi
    fi

    if [ "$use_cached" = false ]; then
        : > "$cache_file.tmp"
        declare -A seen_dirs=()

        # 1. Scan Steam Libraries
        local steam_lib
        while read -r steam_lib; do
            [ -d "$steam_lib" ] || continue
            for acf in "$steam_lib"/appmanifest_*.acf; do
                [ -f "$acf" ] || continue

                # Single-pass regex parse of ACF manifest without subshell forks
                local appid="" name="" installdir=""
                while IFS= read -r acf_line; do
                    if [[ "$acf_line" =~ \"appid\"[[:space:]]+\"([0-9]+)\" ]]; then
                        appid="${BASH_REMATCH[1]}"
                    elif [[ "$acf_line" =~ \"name\"[[:space:]]+\"([^\"]+)\" ]]; then
                        name="${BASH_REMATCH[1]}"
                    elif [[ "$acf_line" =~ \"installdir\"[[:space:]]+\"([^\"]+)\" ]]; then
                        installdir="${BASH_REMATCH[1]}"
                    fi
                    [ -n "$appid" ] && [ -n "$name" ] && [ -n "$installdir" ] && break
                done < "$acf"

                # Filter out Proton, Steam Linux Runtimes, and tools
                [[ "$name" =~ ^(Steam Linux Runtime|Proton|Steamworks) ]] && continue
                [ -z "$installdir" ] && continue

                local gdir="$steam_lib/common/$installdir"
                [ -d "$gdir" ] || continue
                [[ -v seen_dirs["$gdir"] ]] && continue
                seen_dirs["$gdir"]=1

                local gbin
                gbin=$(find_game_binary "$gdir") || continue
                [ -z "$gbin" ] && continue

                local is_win_bin=false
                case "$gbin" in
                    *.exe|*.EXE) is_win_bin=true ;;
                esac

                local status="STANDALONE"
                local api_file=""
                if [ "$is_win_bin" = true ]; then
                    if [ -f "$gdir/steam_api64.dll" ]; then
                        api_file="$gdir/steam_api64.dll"
                    elif [ -f "$gdir/steam_api.dll" ]; then
                        api_file="$gdir/steam_api.dll"
                    elif [ -f "$gdir/libsteam_api.so" ]; then
                        api_file="$gdir/libsteam_api.so"
                    elif [ -f "$gdir/lib64/libsteam_api.so" ]; then
                        api_file="$gdir/lib64/libsteam_api.so"
                    else
                        api_file=$(find "$gdir" -maxdepth 3 \( -name "steam_api64.dll" -o -name "steam_api.dll" -o -name "libsteam_api.so" \) 2>/dev/null | head -n 1)
                    fi
                else
                    if [ -f "$gdir/libsteam_api.so" ]; then
                        api_file="$gdir/libsteam_api.so"
                    elif [ -f "$gdir/lib64/libsteam_api.so" ]; then
                        api_file="$gdir/lib64/libsteam_api.so"
                    elif [ -f "$gdir/steam_api64.dll" ]; then
                        api_file="$gdir/steam_api64.dll"
                    elif [ -f "$gdir/steam_api.dll" ]; then
                        api_file="$gdir/steam_api.dll"
                    else
                        api_file=$(find "$gdir" -maxdepth 3 \( -name "libsteam_api.so" -o -name "steam_api64.dll" -o -name "steam_api.dll" \) 2>/dev/null | head -n 1)
                    fi
                fi

                if [ -n "$api_file" ]; then
                    local sz
                    sz=$(stat -c%s "$api_file" 2>/dev/null || echo 0)
                    if [ "$sz" -gt 7000000 ]; then
                        status="GBE_FORK"
                    else
                        case "$api_file" in
                            *.dll) status="VALVE_DLL" ;;
                            *)     status="VALVE_SO" ;;
                        esac
                    fi
                fi

                printf "%s\t%s\t%s\t%s\t%s\n" "$appid" "$name" "$status" "$gdir" "$gbin" >> "$cache_file.tmp"
            done
        done < <(get_steam_libraries)

        # 2. Scan Custom & Standalone Directories
        local custom_search_dirs=(
            "$HOME/Games"
            "$HOME/.local/share/lutris/games"
        )

        # Allow extending library directories via ~/.config/gamectl/libraries or env
        if [ -f "$HOME/.config/gamectl/libraries" ]; then
            while IFS= read -r line || [ -n "$line" ]; do
                line="${line#"${line%%[![:space:]]*}"}" # trim leading
                line="${line%"${line##*[![:space:]]}"}" # trim trailing
                [ -z "$line" ] && continue
                [[ "$line" =~ ^# ]] && continue
                custom_search_dirs+=("${line/#\~/$HOME}")
            done < "$HOME/.config/gamectl/libraries"
        fi

        if [ -n "${GAMECTL_LIBRARY_DIRS:-}" ]; then
            IFS=":" read -r -a extra_dirs <<< "$GAMECTL_LIBRARY_DIRS"
            custom_search_dirs+=("${extra_dirs[@]}")
        fi

        for base_dir in "${custom_search_dirs[@]}"; do
            [ -d "$base_dir" ] || continue
            for gdir in "$base_dir"/*; do
                [ -d "$gdir" ] || continue
                [[ -v seen_dirs["$gdir"] ]] && continue
                seen_dirs["$gdir"]=1

                local folder_name="${gdir##*/}"
                [[ "$folder_name" =~ ^\. ]] && continue

                local gbin
                gbin=$(find_game_binary "$gdir") || continue
                [ -z "$gbin" ] && continue

                local appid="STANDALONE"
                if [ -f "$gdir/steam_appid.txt" ]; then
                    local raw_id=""
                    read -r raw_id < "$gdir/steam_appid.txt" 2>/dev/null || true
                    appid="${raw_id//[!0-9]/}"
                    [ -z "$appid" ] && appid="STANDALONE"
                elif [ -f "$gdir/.gamectl_appid" ]; then
                    local raw_id=""
                    read -r raw_id < "$gdir/.gamectl_appid" 2>/dev/null || true
                    appid="${raw_id//[!0-9]/}"
                    [ -z "$appid" ] && appid="STANDALONE"
                fi

                local title="$folder_name"
                if [ -f "$gdir/.gamectl_title" ]; then
                    read -r title < "$gdir/.gamectl_title" 2>/dev/null || title="$folder_name"
                fi

                local is_win_bin=false
                case "$gbin" in
                    *.exe|*.EXE) is_win_bin=true ;;
                esac

                local status="STANDALONE"
                local api_file=""
                if [ "$is_win_bin" = true ]; then
                    if [ -f "$gdir/steam_api64.dll" ]; then
                        api_file="$gdir/steam_api64.dll"
                    elif [ -f "$gdir/steam_api.dll" ]; then
                        api_file="$gdir/steam_api.dll"
                    elif [ -f "$gdir/libsteam_api.so" ]; then
                        api_file="$gdir/libsteam_api.so"
                    elif [ -f "$gdir/lib64/libsteam_api.so" ]; then
                        api_file="$gdir/lib64/libsteam_api.so"
                    else
                        api_file=$(find "$gdir" -maxdepth 3 \( -name "steam_api64.dll" -o -name "steam_api.dll" -o -name "libsteam_api.so" \) 2>/dev/null | head -n 1)
                    fi
                else
                    if [ -f "$gdir/libsteam_api.so" ]; then
                        api_file="$gdir/libsteam_api.so"
                    elif [ -f "$gdir/lib64/libsteam_api.so" ]; then
                        api_file="$gdir/lib64/libsteam_api.so"
                    elif [ -f "$gdir/steam_api64.dll" ]; then
                        api_file="$gdir/steam_api64.dll"
                    elif [ -f "$gdir/steam_api.dll" ]; then
                        api_file="$gdir/steam_api.dll"
                    else
                        api_file=$(find "$gdir" -maxdepth 3 \( -name "libsteam_api.so" -o -name "steam_api64.dll" -o -name "steam_api.dll" \) 2>/dev/null | head -n 1)
                    fi
                fi

                if [ -n "$api_file" ]; then
                    local sz
                    sz=$(stat -c%s "$api_file" 2>/dev/null || echo 0)
                    if [ "$sz" -gt 7000000 ]; then
                        status="GBE_FORK"
                    else
                        case "$api_file" in
                            *.dll) status="VALVE_DLL" ;;
                            *)     status="VALVE_SO" ;;
                        esac
                    fi
                fi

                printf "%s\t%s\t%s\t%s\t%s\n" "$appid" "$title" "$status" "$gdir" "$gbin" >> "$cache_file.tmp"
            done
        done
        mv -f "$cache_file.tmp" "$cache_file"
    fi

    # Render formatted or raw tab entries
    if [ "$is_formatted" = true ]; then
        while IFS=$'\t' read -r c_appid c_title c_status c_gdir c_gbin; do
            [ -z "$c_gdir" ] && continue
            local c_badge=""
            case "$c_status" in
                *GBE_FORK*)   c_badge="${UI_GREEN}[GBE_FORK]  ${UI_RST}" ;;
                *VALVE_SO*)   c_badge="${UI_AMBER}[VALVE_SO]  ${UI_RST}" ;;
                *VALVE_DLL*)  c_badge="${UI_CYAN}[VALVE_DLL] ${UI_RST}" ;;
                *)            c_badge="${UI_ICE}[STANDALONE]${UI_RST}" ;;
            esac
            printf "%b\t%b\t%b\t%s\t%s\n" "${UI_DIM}${c_appid}${UI_RST}" "${UI_BOLD}${c_title}${UI_RST}" "$c_badge" "$c_gdir" "$c_gbin"
        done < "$cache_file"
    else
        while IFS=$'\t' read -r c_appid c_title c_status c_gdir c_gbin; do
            [ -z "$c_gdir" ] && continue
            local clean_stat="$c_status"
            [[ "$clean_stat" != \[*\] ]] && clean_stat="[$clean_stat]"
            printf "%-8s\t%-22s\t%-12s\t%s\t%s\n" "$c_appid" "$c_title" "$clean_stat" "$c_gdir" "$c_gbin"
        done < "$cache_file"
    fi
}

# Generate FreeDesktop .desktop application shortcut (Chunk 5)
create_desktop_entry() {
    local game_dir="${1:-}"
    local title="${2:-}"

    if [ -z "$game_dir" ] || [ ! -d "$game_dir" ]; then
        echo "[ERROR] Game directory not found or invalid: $game_dir" >&2
        echo "Usage: gamectl make-desktop <game_dir> [title]" >&2
        return 1
    fi

    game_dir="$(cd "$game_dir" 2>/dev/null && pwd || echo "$game_dir")"

    # Attempt to resolve title if not supplied
    if [ -z "$title" ]; then
        local base_dir
        base_dir="$(basename "$game_dir")"
        local parent_apps
        parent_apps="$(dirname "$game_dir")"
        if [ "$(basename "$parent_apps")" = "common" ]; then
            local steamapps_dir
            steamapps_dir="$(dirname "$parent_apps")"
            local acf
            for acf in "$steamapps_dir"/appmanifest_*.acf; do
                [ -f "$acf" ] || continue
                local installdir
                installdir=$(grep -E '^\s*"installdir"' "$acf" | head -n 1 | sed -E 's/.*"installdir"[[:space:]]+"([^"]+)".*/\1/')
                if [ "$installdir" = "$base_dir" ]; then
                    title=$(grep -E '^\s*"name"' "$acf" | head -n 1 | sed -E 's/.*"name"[[:space:]]+"([^"]+)".*/\1/')
                    break
                fi
            done
        fi
        [ -z "$title" ] && title="$base_dir"
    fi

    # Locate game binary
    local gbin
    gbin="$(find_game_binary "$game_dir" 2>/dev/null || true)"
    if [ -z "$gbin" ]; then
        echo "[WARN] Game executable binary not detected automatically in $game_dir" >&2
    fi

    # Locate game icon (prefer icon.png, icon.ico, logo.png, or any png/ico)
    local icon_path="applications-games"
    local found_icon=""
    for candidate in "icon.png" "icon.ico" "logo.png" "app.png" "banner.png"; do
        if [ -f "$game_dir/$candidate" ]; then
            found_icon="$game_dir/$candidate"
            break
        fi
    done
    if [ -z "$found_icon" ]; then
        found_icon=$(find "$game_dir" -maxdepth 2 \( -name "*.ico" -o -name "*.png" \) 2>/dev/null | head -n 1 || true)
    fi
    [ -n "$found_icon" ] && icon_path="$found_icon"

    # Resolve gamectl binary
    local gamectl_bin
    gamectl_bin="$(command -v gamectl 2>/dev/null || true)"
    if [ -z "$gamectl_bin" ]; then
        if [ -x "$HOME/.local/bin/gamectl" ]; then
            gamectl_bin="$HOME/.local/bin/gamectl"
        elif [ -x "/usr/local/bin/gamectl" ]; then
            gamectl_bin="/usr/local/bin/gamectl"
        else
            gamectl_bin="gamectl"
        fi
    fi

    # Sanitize title for desktop entry file name
    local safe_title
    safe_title=$(echo "$title" | tr -dc '[:alnum:]_-' | tr '[:upper:]' '[:lower:]')
    [ -z "$safe_title" ] && safe_title="game"

    local desk_dir="$HOME/.local/share/applications"
    mkdir -p "$desk_dir"
    local desk_file="$desk_dir/gamectl-${safe_title}.desktop"

    cat <<EOF > "$desk_file"
[Desktop Entry]
Type=Application
Name=$title
Comment=Launched via gamectl
Exec=$gamectl_bin launch "$game_dir" --hud
Icon=$icon_path
Terminal=false
Categories=Game;
Path=$game_dir
StartupNotify=true
EOF

    chmod +x "$desk_file"
    if command -v update-desktop-database >/dev/null 2>&1; then
        update-desktop-database "$desk_dir" 2>/dev/null || true
    fi

    echo "[VERIFIED] Desktop entry created successfully: $desk_file"
    echo "[INFO] Title    : $title"
    echo "[INFO] Exec     : $gamectl_bin launch \"$game_dir\" --hud"
    echo "[INFO] Icon     : $icon_path"
    return 0
}

# Resolve active Steam user grid directory (~/.local/share/Steam/userdata/<account_id>/config/grid)
get_steam_grid_dir() {
    if [ -n "${GAMECTL_GRID_DIR:-}" ]; then
        echo "$GAMECTL_GRID_DIR"
        return 0
    fi

    local s_roots=(
        "$HOME/.local/share/Steam"
        "$HOME/.steam/steam"
        "$HOME/.steam/root"
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam"
        "$HOME/snap/steam/common/.local/share/Steam"
    )
    for s_root in "${s_roots[@]}"; do
        if [ -d "$s_root/userdata" ]; then
            for udir in "$s_root/userdata"/*; do
                [ -d "$udir" ] || continue
                local u_id
                u_id=$(basename "$udir")
                if [[ "$u_id" =~ ^[0-9]+$ ]] && [ "$u_id" -gt 0 ] 2>/dev/null; then
                    echo "$udir/config/grid"
                    return 0
                fi
            done
        fi
    done

    # Fallback to default
    echo "$HOME/.local/share/Steam/userdata/0/config/grid"
}

# Fetch official artwork (portrait, banner, hero, logo) from Steam CDN
fetch_steam_artwork() {
    local target="${1:-}"
    local appid="${2:-}"

    if [ -z "$target" ]; then
        echo "Usage: gamectl fetch-art <game_dir|appid> [appid]" >&2
        return 1
    fi

    local game_dir=""
    if [[ "$target" =~ ^[0-9]+$ ]] && [ -z "$appid" ]; then
        appid="$target"
    elif [ -d "$target" ]; then
        game_dir="$target"
    elif [ -f "$target" ]; then
        game_dir="$(dirname "$target")"
    fi

    # Resolve AppID from directory if not explicitly provided
    if [ -z "$appid" ] && [ -n "$game_dir" ]; then
        if [ -f "$game_dir/steam_appid.txt" ]; then
            appid=$(grep -oE '^[0-9]+' "$game_dir/steam_appid.txt" 2>/dev/null | head -n 1 || true)
        elif [ -f "$game_dir/steam_settings/steam_appid.txt" ]; then
            appid=$(grep -oE '^[0-9]+' "$game_dir/steam_settings/steam_appid.txt" 2>/dev/null | head -n 1 || true)
        fi
    fi

    if [ -z "$appid" ]; then
        echo "[ERROR] Cannot resolve Steam AppID for target: $target" >&2
        echo "        Provide a numeric AppID: gamectl fetch-art <dir> <appid>" >&2
        return 1
    fi

    local grid_dir
    grid_dir=$(get_steam_grid_dir)
    mkdir -p "$grid_dir"

    # Identify target shortcut and artwork IDs
    local target_ids=("$appid")
    if [ -n "$game_dir" ]; then
        local g_bin
        g_bin=$(find_game_binary "$game_dir" 2>/dev/null || true)
        local g_title
        g_title=$(basename "$game_dir")
        if [ -n "$g_bin" ]; then
            local sc_id
            sc_id=$(python3 -c "import binascii, sys; p = sys.argv[1]; t = sys.argv[2]; print((binascii.crc32((p + t).encode('utf-8')) | 0x80000000))" "$game_dir/$g_bin" "$g_title" 2>/dev/null || true)
            if [ -n "$sc_id" ] && [ "$sc_id" != "$appid" ]; then
                target_ids+=("$sc_id")
            fi
        fi
    fi

    echo "[INFO] Fetching Steam artwork for AppID: $appid"
    echo "[INFO] Destination Steam grid directory: $grid_dir"

    local tmp_dir
    tmp_dir=$(mktemp -d)
    local downloaded_count=0

    # Helper function to download and convert image to PNG
    _download_asset() {
        local asset_type="$1"
        local asset_suffix="$2"
        shift 2
        local urls=("$@")

        local tmp_file="$tmp_dir/${asset_type// /_}.raw"
        rm -f "$tmp_file"

        local url
        for url in "${urls[@]}"; do
            if curl -fsSL --connect-timeout 5 --max-time 15 "$url" -o "$tmp_file" 2>/dev/null && [ -s "$tmp_file" ]; then
                break
            fi
        done

        if [ ! -s "$tmp_file" ]; then
            echo "    • $(printf '%-18s' "$asset_type") : [WARN] Not available on CDN"
            return 1
        fi

        local tid
        for tid in "${target_ids[@]}"; do
            local dest_png="$grid_dir/${tid}${asset_suffix}.png"
            if command -v magick >/dev/null 2>&1; then
                magick "$tmp_file" "$dest_png" 2>/dev/null || cp "$tmp_file" "$dest_png"
            elif command -v convert >/dev/null 2>&1; then
                convert "$tmp_file" "$dest_png" 2>/dev/null || cp "$tmp_file" "$dest_png"
            elif command -v ffmpeg >/dev/null 2>&1; then
                ffmpeg -v error -y -i "$tmp_file" "$dest_png" 2>/dev/null || cp "$tmp_file" "$dest_png"
            else
                cp "$tmp_file" "$dest_png"
            fi
        done

        echo "    • $(printf '%-18s' "$asset_type") : [VERIFIED] Saved as <id>${asset_suffix}.png"
        downloaded_count=$((downloaded_count + 1))
        return 0
    }

    # 1. Portrait capsule (600x900) -> <shortcut_id>p.png
    _download_asset "Portrait Capsule" "p" \
        "https://cdn.akamai.steamstatic.com/steam/apps/$appid/library_600x900_2x.jpg" \
        "https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/$appid/library_600x900_2x.jpg" \
        "https://cdn.cloudflare.steamstatic.com/steam/apps/$appid/library_600x900_2x.jpg" \
        "https://cdn.akamai.steamstatic.com/steam/apps/$appid/library_600x900.jpg" || true

    # 2. Horizontal banner (920x430 or 460x215) -> <shortcut_id>.png
    _download_asset "Horizontal Banner" "" \
        "https://cdn.akamai.steamstatic.com/steam/apps/$appid/header.jpg" \
        "https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/$appid/header.jpg" \
        "https://cdn.cloudflare.steamstatic.com/steam/apps/$appid/header.jpg" || true

    # 3. Hero background (1920x620) -> <shortcut_id>_hero.png
    _download_asset "Hero Background" "_hero" \
        "https://cdn.akamai.steamstatic.com/steam/apps/$appid/library_hero.jpg" \
        "https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/$appid/library_hero.jpg" \
        "https://cdn.cloudflare.steamstatic.com/steam/apps/$appid/library_hero.jpg" || true

    # 4. Logo transparent overlay -> <shortcut_id>_logo.png
    _download_asset "Logo Overlay" "_logo" \
        "https://cdn.akamai.steamstatic.com/steam/apps/$appid/logo.png" \
        "https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/$appid/logo.png" \
        "https://cdn.cloudflare.steamstatic.com/steam/apps/$appid/logo.png" || true

    rm -rf "$tmp_dir"

    if [ "$downloaded_count" -gt 0 ]; then
        echo "[VERIFIED] Successfully fetched $downloaded_count artwork asset(s) for AppID: $appid"
        return 0
    else
        echo "[ERROR] Failed to fetch any artwork assets for AppID: $appid" >&2
        return 1
    fi
}

# Resolve active Steam user shortcuts.vdf path (~/.local/share/Steam/userdata/<account_id>/config/shortcuts.vdf)
get_steam_shortcuts_vdf() {
    if [ -n "${GAMECTL_SHORTCUTS_VDF:-}" ]; then
        echo "$GAMECTL_SHORTCUTS_VDF"
        return 0
    fi

    local s_roots=(
        "$HOME/.local/share/Steam"
        "$HOME/.steam/steam"
        "$HOME/.steam/root"
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam"
        "$HOME/snap/steam/common/.local/share/Steam"
    )
    for s_root in "${s_roots[@]}"; do
        if [ -d "$s_root/userdata" ]; then
            for udir in "$s_root/userdata"/*; do
                [ -d "$udir" ] || continue
                local u_id
                u_id=$(basename "$udir")
                if [[ "$u_id" =~ ^[0-9]+$ ]] && [ "$u_id" -gt 0 ] 2>/dev/null; then
                    echo "$udir/config/shortcuts.vdf"
                    return 0
                fi
            done
        fi
    done

    # Default fallback
    echo "$HOME/.local/share/Steam/userdata/0/config/shortcuts.vdf"
}

# Check if Steam client process is actively running and warn about memory lock
check_steam_active() {
    local context="${1:-Steam operations}"
    if pgrep -x steam >/dev/null 2>&1; then
        echo "[WARN] Steam client is currently running! $context while Steam is active may cause file lock conflicts or get overwritten upon client exit." >&2
        echo "[WARN] Recommendation: Exit Steam or restart it after this operation to reload shortcuts and manifests cleanly." >&2
        return 0
    fi
    return 1
}

# Add or update a non-Steam shortcut in Steam Deck Game Mode (binary shortcuts.vdf)
add_steam_shortcut() {
    local game_dir="${1:-}"
    local title="${2:-}"

    if [ -z "$game_dir" ]; then
        echo "Usage: gamectl add-to-steam <game_dir> [title]" >&2
        return 1
    fi

    if [ ! -d "$game_dir" ]; then
        echo "[ERROR] Game directory does not exist: $game_dir" >&2
        return 1
    fi

    # Guard against concurrent Steam client memory lock on shortcuts.vdf
    check_steam_active "Registering non-Steam shortcut in shortcuts.vdf" || true

    game_dir="$(cd "$game_dir" && pwd)"

    if [ -z "$title" ]; then
        title="$(basename "$game_dir")"
    fi

    # Locate game icon
    local icon_path=""
    for candidate in "icon.png" "icon.ico" "logo.png" "app.png" "banner.png"; do
        if [ -f "$game_dir/$candidate" ]; then
            icon_path="$game_dir/$candidate"
            break
        fi
    done
    if [ -z "$icon_path" ]; then
        icon_path=$(find "$game_dir" -maxdepth 2 \( -name "*.ico" -o -name "*.png" \) 2>/dev/null | head -n 1 || true)
    fi

    # Resolve gamectl binary
    local gamectl_bin
    gamectl_bin="$(command -v gamectl 2>/dev/null || true)"
    if [ -z "$gamectl_bin" ]; then
        if [ -x "$HOME/.local/bin/gamectl" ]; then
            gamectl_bin="$HOME/.local/bin/gamectl"
        elif [ -x "/usr/local/bin/gamectl" ]; then
            gamectl_bin="/usr/local/bin/gamectl"
        elif [ -x "$REPO_ROOT/bin/gamectl" ]; then
            gamectl_bin="$REPO_ROOT/bin/gamectl"
        else
            gamectl_bin="gamectl"
        fi
    fi

    local shortcuts_file
    shortcuts_file="$(get_steam_shortcuts_vdf)"
    local vdf_dir
    vdf_dir="$(dirname "$shortcuts_file")"
    mkdir -p "$vdf_dir"

    # Create atomic backup if file already exists
    if [ -f "$shortcuts_file" ]; then
        cp -f "$shortcuts_file" "${shortcuts_file}.bak"
    fi

    python3 - "$shortcuts_file" "$title" "$game_dir" "$gamectl_bin" "$icon_path" << 'PYEOF'
import sys, os, struct, binascii

shortcuts_path = sys.argv[1]
title = sys.argv[2]
game_dir = os.path.abspath(sys.argv[3])
gamectl_bin = sys.argv[4]
icon_path = sys.argv[5]

exe_field = f'"{gamectl_bin}"'
startdir_field = f'"{game_dir}"'
launch_opts = f'launch "{game_dir}" --hud'

raw_crc = (binascii.crc32((exe_field + title).encode('utf-8')) | 0x80000000) & 0xffffffff
signed_appid = struct.unpack('<i', struct.pack('<I', raw_crc))[0]

def parse_binary_vdf(data):
    pos = 0
    def read_str():
        nonlocal pos
        end = data.find(b'\x00', pos)
        if end == -1: return ''
        s = data[pos:end].decode('utf-8', errors='replace')
        pos = end + 1
        return s
    def parse_map():
        nonlocal pos
        res = {}
        while pos < len(data):
            b = data[pos]
            pos += 1
            if b == 8: break
            key = read_str()
            if b == 0: res[key] = parse_map()
            elif b == 1: res[key] = read_str()
            elif b == 2:
                if pos + 4 <= len(data):
                    val = struct.unpack('<i', data[pos:pos+4])[0]
                    pos += 4
                    res[key] = val
        return res
    if data.startswith(b'\x00shortcuts\x00'):
        pos = len(b'\x00shortcuts\x00')
        root = parse_map()
        shortcuts = []
        for k in sorted(root.keys(), key=lambda x: int(x) if x.isdigit() else 9999):
            if isinstance(root[k], dict): shortcuts.append(root[k])
        return shortcuts
    return []

def serialize_shortcuts(shortcuts):
    buf = bytearray(b'\x00shortcuts\x00')
    for idx, s in enumerate(shortcuts):
        buf.append(0)
        buf.extend(str(idx).encode('utf-8') + b'\x00')
        for k, v in s.items():
            if isinstance(v, int):
                buf.append(2)
                buf.extend(k.encode('utf-8') + b'\x00')
                buf.extend(struct.pack('<i', v))
            elif isinstance(v, str):
                buf.append(1)
                buf.extend(k.encode('utf-8') + b'\x00')
                buf.extend(v.encode('utf-8') + b'\x00')
            elif isinstance(v, dict):
                buf.append(0)
                buf.extend(k.encode('utf-8') + b'\x00')
                for tk, tv in v.items():
                    buf.append(1)
                    buf.extend(str(tk).encode('utf-8') + b'\x00')
                    buf.extend(str(tv).encode('utf-8') + b'\x00')
                buf.append(8)
        buf.append(8)
    buf.append(8)
    buf.append(8)
    return bytes(buf)

shortcuts = []
if os.path.exists(shortcuts_path):
    try:
        with open(shortcuts_path, 'rb') as f:
            shortcuts = parse_binary_vdf(f.read())
    except Exception:
        shortcuts = []

existing_idx = -1
for i, sc in enumerate(shortcuts):
    if sc.get('AppName') == title or sc.get('StartDir', '').strip('"') == game_dir:
        existing_idx = i
        break

new_entry = {
    'appid': signed_appid,
    'AppName': title,
    'Exe': exe_field,
    'StartDir': startdir_field,
    'icon': icon_path,
    'ShortcutPath': '',
    'LaunchOptions': launch_opts,
    'IsHidden': 0,
    'AllowDesktopConfig': 1,
    'AllowOverlay': 1,
    'OpenVR': 0,
    'Devkit': 0,
    'DevkitGameID': '',
    'DevkitOverrideAppID': 0,
    'LastPlayTime': 0,
    'FlatpakAppID': '',
    'tags': {}
}

if existing_idx >= 0:
    shortcuts[existing_idx] = new_entry
    action = "updated"
else:
    shortcuts.append(new_entry)
    action = "registered"

out_data = serialize_shortcuts(shortcuts)
tmp_path = shortcuts_path + f'.tmp.{os.getpid()}'
with open(tmp_path, 'wb') as f:
    f.write(out_data)
os.replace(tmp_path, shortcuts_path)

print(f'[VERIFIED] Steam shortcut {action} successfully: {title}')
print(f'[INFO] Target 32-bit AppID : {raw_crc}')
print(f'[INFO] Shortcuts file      : {shortcuts_path}')
print(f'[INFO] Launch Options      : {launch_opts}')
PYEOF

    # Optionally attempt artwork synchronization if an AppID is available
    if [ -f "$game_dir/steam_appid.txt" ] || [ -f "$game_dir/steam_settings/steam_appid.txt" ]; then
        fetch_steam_artwork "$game_dir" >/dev/null 2>&1 || true
    fi

    return 0
}


# --- [MODULE] src/steam/25_identity.sh ---
# Generate a valid 17-digit SteamID64 for individual accounts (76561197960265728 + 31-bit random int)
generate_steamid64() {
    local base=76561197960265728
    local rand=""
    if [ -r /dev/urandom ] && command -v od >/dev/null 2>&1; then
        local raw
        raw=$(od -An -N4 -tu4 /dev/urandom 2>/dev/null | tr -d ' ')
        if [ -n "$raw" ] && [ "$raw" -gt 0 ] 2>/dev/null; then
            rand=$(( raw % 2000000000 + 100000 ))
        fi
    fi
    if [ -z "$rand" ]; then
        local r1=$(( (RANDOM << 16) | RANDOM ))
        rand=$(( (r1 & 0x7FFFFFFF) % 2000000000 + 100000 ))
    fi
    echo $(( base + rand ))
}

# Hierarchical SteamID64 resolver (Env -> Persona -> Steam client active user -> random SteamID64)
resolve_active_steamid() {
    # Priority 1: Environment override
    if [ -n "${GAMECTL_STEAMID:-}" ] && [[ "$GAMECTL_STEAMID" =~ ^7656119[0-9]{10}$ ]]; then
        echo "$GAMECTL_STEAMID"
        return 0
    fi

    # Priority 2: Global persona configuration
    if [ -f "$HOME/.config/gamectl/persona" ]; then
        local p_id
        p_id=$(grep -E '^[[:space:]]*account_steamid[[:space:]]*=' "$HOME/.config/gamectl/persona" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_steamid[[:space:]]*=[[:space:]]*//' | tr -d '\r[:space:]')
        if [ -n "$p_id" ] && [[ "$p_id" =~ ^7656119[0-9]{10}$ ]]; then
            echo "$p_id"
            return 0
        fi
    fi

    # Priority 3: Active Steam client login
    local s_roots=(
        "$HOME/.local/share/Steam"
        "$HOME/.steam/steam"
        "$HOME/.steam/root"
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam"
        "$HOME/snap/steam/common/.local/share/Steam"
    )
    for s_root in "${s_roots[@]}"; do
        local vdf="$s_root/config/loginusers.vdf"
        if [ -f "$vdf" ]; then
            local sid
            sid=$(grep -E '^[[:space:]]*"7656119[0-9]{10}"' "$vdf" 2>/dev/null | head -n 1 | tr -dc '0-9')
            if [ -n "$sid" ] && [ ${#sid} -eq 17 ]; then
                echo "$sid"
                return 0
            fi
        fi

        if [ -d "$s_root/userdata" ]; then
            local udir
            for udir in "$s_root/userdata"/*; do
                [ -d "$udir" ] || continue
                local u_id
                u_id=$(basename "$udir")
                if [[ "$u_id" =~ ^[0-9]+$ ]] && [ "$u_id" -gt 0 ] 2>/dev/null; then
                    local sid64=$(( 76561197960265728 + u_id ))
                    if [[ "$sid64" =~ ^7656119[0-9]{10}$ ]]; then
                        echo "$sid64"
                        return 0
                    fi
                fi
            done
        fi
    done

    # Priority 4: Dynamic random SteamID64
    generate_steamid64
}

# Resolve game LAN persona (account_name, account_steamid, language)
get_game_persona() {
    local gdir="$1"
    local p_name=""
    local p_id=""
    local p_lang="english"

    if [ -f "$gdir/steam_settings/configs.user.ini" ]; then
        p_name=$(grep -E '^[[:space:]]*account_name[[:space:]]*=' "$gdir/steam_settings/configs.user.ini" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_name[[:space:]]*=[[:space:]]*//' | tr -d '\r')
        p_id=$(grep -E '^[[:space:]]*account_steamid[[:space:]]*=' "$gdir/steam_settings/configs.user.ini" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_steamid[[:space:]]*=[[:space:]]*//' | tr -d '\r')
        p_lang=$(grep -E '^[[:space:]]*language[[:space:]]*=' "$gdir/steam_settings/configs.user.ini" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*language[[:space:]]*=[[:space:]]*//' | tr -d '\r')
    fi

    if [ -z "$p_name" ] && [ -f "$HOME/.config/gamectl/persona" ]; then
        p_name=$(grep -E '^[[:space:]]*account_name[[:space:]]*=' "$HOME/.config/gamectl/persona" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_name[[:space:]]*=[[:space:]]*//' | tr -d '\r')
    fi
    if [ -z "$p_id" ] && [ -f "$HOME/.config/gamectl/persona" ]; then
        p_id=$(grep -E '^[[:space:]]*account_steamid[[:space:]]*=' "$HOME/.config/gamectl/persona" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_steamid[[:space:]]*=[[:space:]]*//' | tr -d '\r')
    fi

    [ -z "$p_name" ] && p_name="${USER:-Player}"
    [ -z "$p_id" ] && p_id=$(resolve_active_steamid)
    [ -z "$p_lang" ] && p_lang="english"

    echo "$p_name|$p_id|$p_lang"
}


# Set LAN Player Name, SteamID, and broadcast IPs for GBE Fork co-op
set_id() {
    local player_name="${1:-}"
    shift || true

    if [ -z "$player_name" ]; then
        echo "Usage: gamectl set-id <player_name> [steamid] [target_dir] [--broadcast <ip>] [--global]" >&2
        return 1
    fi

    local steamid=""
    local target_dir=""
    local broadcast_ips=()
    local save_global=false

    while [ $# -gt 0 ]; do
        case "$1" in
            --global)
                save_global=true
                shift
                ;;
            --broadcast)
                if [ -n "${2:-}" ]; then
                    broadcast_ips+=("$2")
                    shift 2
                else
                    shift
                fi
                ;;
            --broadcast=*)
                broadcast_ips+=("${1#*=}")
                shift
                ;;
            *)
                if [ -z "$steamid" ] && { [[ "$1" =~ ^7656119[0-9]{10}$ ]] || [ "$1" = "auto" ] || [ "$1" = "random" ]; }; then
                    if [ "$1" = "auto" ] || [ "$1" = "random" ]; then
                        steamid=$(generate_steamid64)
                    else
                        steamid="$1"
                    fi
                elif [ -z "$target_dir" ] && [ -d "$1" ]; then
                    target_dir="$1"
                elif [ -z "$steamid" ] && [[ "$1" =~ ^[0-9]+$ ]] && [ ${#1} -eq 17 ]; then
                    steamid="$1"
                else
                    if [ -z "$target_dir" ]; then
                        target_dir="$1"
                    fi
                fi
                shift
                ;;
        esac
    done

    # Generate steamid if still empty
    if [ -z "$steamid" ]; then
        steamid=$(generate_steamid64)
    fi

    # Determine target directory
    if [ -z "$target_dir" ]; then
        if [ -d "./steam_settings" ] || [ -f "./steam_appid.txt" ]; then
            target_dir="."
        else
            save_global=true
        fi
    fi

    # Save to global config if requested or if no game directory identified
    if [ "$save_global" = true ]; then
        mkdir -p "$HOME/.config/gamectl"
        cat <<EOF > "$HOME/.config/gamectl/persona"
# gamectl global persona
account_name=$player_name
account_steamid=$steamid
language=english
EOF
        echo "[INFO] Global persona saved to ~/.config/gamectl/persona ($player_name | $steamid)"
    fi

    if [ -n "$target_dir" ] && [ -d "$target_dir" ]; then
        target_dir="$(cd "$target_dir" && pwd)"
        mkdir -p "$target_dir/steam_settings"

        local ini_file="$target_dir/steam_settings/configs.user.ini"
        if [ -f "$ini_file" ]; then
            if grep -q -E '^[[:space:]]*account_name[[:space:]]*=' "$ini_file"; then
                sed -i -E "s/^[[:space:]]*account_name[[:space:]]*=.*/account_name=$player_name/" "$ini_file"
            else
                echo "account_name=$player_name" >> "$ini_file"
            fi
            if grep -q -E '^[[:space:]]*account_steamid[[:space:]]*=' "$ini_file"; then
                sed -i -E "s/^[[:space:]]*account_steamid[[:space:]]*=.*/account_steamid=$steamid/" "$ini_file"
            else
                echo "account_steamid=$steamid" >> "$ini_file"
            fi
        else
            cat <<EOF > "$ini_file"
[user::general]
account_name=$player_name
account_steamid=$steamid
language=english

[user::saves]
local_save_path=./saves
EOF
        fi

        # Handle custom_broadcasts.txt
        local bc_file="$target_dir/steam_settings/custom_broadcasts.txt"
        if [ ! -f "$bc_file" ]; then
            cat <<EOF > "$bc_file"
# GBE Fork LAN Custom Broadcast IP list
# Add peer IPs or broadcast subnets (one IP per line)
127.0.0.1
255.255.255.255
EOF
        fi

        if [ ${#broadcast_ips[@]} -gt 0 ]; then
            for ip in "${broadcast_ips[@]}"; do
                IFS=',' read -ra split_ips <<< "$ip"
                for s_ip in "${split_ips[@]}"; do
                    s_ip=$(echo "$s_ip" | tr -d ' ')
                    [ -z "$s_ip" ] && continue
                    if ! grep -q -F "$s_ip" "$bc_file" 2>/dev/null; then
                        echo "$s_ip" >> "$bc_file"
                        echo "[INFO] Added broadcast IP: $s_ip"
                    fi
                done
            done
        fi

        # Ensure symlinks to subfolders if shim exists in subdirectory
        for shim_candidate in "$target_dir"/*/*.dll "$target_dir"/*/*/*.dll "$target_dir"/*/*.so "$target_dir"/*/*/*.so; do
            if [ -f "$shim_candidate" ]; then
                local s_dir
                s_dir="$(dirname "$shim_candidate")"
                if [ "$s_dir" != "$target_dir" ] && [ -d "$s_dir" ]; then
                    ln -sfn "$target_dir/steam_settings" "$s_dir/steam_settings" 2>/dev/null || true
                fi
            fi
        done

        echo "[VERIFIED] Game LAN identity updated in $target_dir:"
        echo "           Player Name : $player_name"
        echo "           SteamID64   : $steamid"
        echo "           Config File : $ini_file"
        local is_gbe_check=false
        for api_c in "$target_dir/libsteam_api.so" "$target_dir/lib64/libsteam_api.so" "$target_dir/steam_api64.dll" "$target_dir/steam_api.dll"; do
            if [ -f "$api_c" ]; then
                local sz
                sz=$(stat -c%s "$api_c" 2>/dev/null || echo 0)
                [ "$sz" -gt 7000000 ] && is_gbe_check=true && break
            fi
        done
        if [ "$is_gbe_check" = false ]; then
            echo "           Note        : Game is not injected with GBE Fork yet. Press <CTRL-I> to enable."
        fi
    fi
}

# Interactive TUI configurator for LAN persona & SteamID
set_id_interactive() {
    local target_dir="${1:-}"
    local title="${2:-}"
    if [ -z "$target_dir" ] || [ ! -d "$target_dir" ]; then
        echo "[ERROR] Invalid game directory: $target_dir" >&2
        return 1
    fi
    target_dir="$(cd "$target_dir" && pwd)"
    [ -z "$title" ] && title="$(basename "$target_dir")"

    local p_info
    p_info=$(get_game_persona "$target_dir")
    local cur_name cur_id cur_lang
    cur_name=$(echo "$p_info" | cut -d'|' -f1)
    cur_id=$(echo "$p_info" | cut -d'|' -f2)
    cur_lang=$(echo "$p_info" | cut -d'|' -f3)

    local is_gbe=false
    local api_cand
    for api_cand in "$target_dir/libsteam_api.so" "$target_dir/lib64/libsteam_api.so" "$target_dir/steam_api64.dll" "$target_dir/steam_api.dll"; do
        if [ -f "$api_cand" ]; then
            local sz
            sz=$(stat -c%s "$api_cand" 2>/dev/null || echo 0)
            if [ "$sz" -gt 7000000 ]; then
                is_gbe=true
                break
            fi
        fi
    done
    if [ "$is_gbe" = false ]; then
        local deep_api
        deep_api=$(find "$target_dir" -maxdepth 3 \( -name "libsteam_api.so" -o -name "steam_api64.dll" -o -name "steam_api.dll" \) 2>/dev/null | head -n 1)
        if [ -n "$deep_api" ]; then
            local sz
            sz=$(stat -c%s "$deep_api" 2>/dev/null || echo 0)
            [ "$sz" -gt 7000000 ] && is_gbe=true
        fi
    fi

    echo
    echo "${UI_BOX}╭─ CONFIGURE LAN IDENTITY & STEAMID (GBE FORK) ───────────────╮${UI_RST}"
    echo "│ ${UI_CYAN}Target Game  ${UI_RST}: ${UI_BOLD}$title${UI_RST}"
    echo "│ ${UI_CYAN}Directory    ${UI_RST}: ${UI_DIM}$target_dir${UI_RST}"
    echo "│ ${UI_CYAN}Player Name  ${UI_RST}: ${UI_BOLD}${cur_name:-[Unset]}${UI_RST}"
    echo "│ ${UI_CYAN}SteamID64    ${UI_RST}: ${UI_BOLD}${cur_id:-[Unset]}${UI_RST}"
    echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"

    if [ "$is_gbe" = false ]; then
        echo "  ${UI_AMBER}[NOTE] This game is not injected with GBE Fork yet.${UI_RST}"
        echo "         Persona will be saved to steam_settings/configs.user.ini"
        echo "         and activates automatically once injected (<CTRL-I>)."
        echo
    fi

    echo -n "  Player Name [${cur_name:-Player}]: "; read -r in_name
    [ -z "$in_name" ] && in_name="$cur_name"
    [ -z "$in_name" ] && in_name="${USER:-Player}"

    local suggested_id
    suggested_id=$(generate_steamid64)
    echo -n "  SteamID64 ('gen' or 'random' to generate) [${cur_id:-$suggested_id}]: "; read -r in_id
    [ -z "$in_id" ] && in_id="${cur_id:-$suggested_id}"
    if [ "$in_id" = "random" ] || [ "$in_id" = "auto" ] || [ "$in_id" = "gen" ]; then
        in_id=$(generate_steamid64)
    fi

    echo
    echo "  LAN Custom Broadcast Peers (Optional):"
    echo "  Enter friend's LAN IP (e.g. 192.168.1.50) or press Enter to skip."
    echo -n "  Peer/Broadcast IP: "; read -r in_bc

    echo -n "  Also save as global default persona? (y/N): "; read -r in_glob

    local extra_args=()
    [ -n "$in_bc" ] && extra_args+=(--broadcast "$in_bc")
    case "$in_glob" in
        y|Y|yes|YES) extra_args+=(--global) ;;
    esac

    set_id "$in_name" "$in_id" "$target_dir" "${extra_args[@]}"
    echo
    read -r -p "Press [ENTER] to return to Library..."
}


# --- [MODULE] src/steam/30_downloader.sh ---
# Fetch and generate steam_settings/DLC.txt for GBE Fork
fetch_dlc() {
    local target_dir="$1"
    local appid="${2:-}"

    if [ ! -d "$target_dir" ]; then
        echo "[ERROR] Target directory not found: $target_dir" >&2
        return 1
    fi

    target_dir="$(cd "$target_dir" && pwd)"

    # Resolve AppID if not provided
    if [ -z "$appid" ]; then
        if [ -f "$target_dir/steam_appid.txt" ]; then
            appid=$(tr -dc '0-9' < "$target_dir/steam_appid.txt")
        fi
    fi

    if [ -z "$appid" ] || [ "$appid" = "STANDALONE" ]; then
        echo "[WARN] Numeric AppID not found. Skipping DLC.txt generation."
        return 0
    fi

    echo "[INFO] Fetching DLC list for AppID $appid from Steam API..."
    local dlc_file="$target_dir/steam_settings/DLC.txt"
    mkdir -p "$target_dir/steam_settings"

    # Primary: dlcforapp endpoint (names & IDs in single call)
    local dlc_data=""
    dlc_data=$(curl -s --connect-timeout 4 "https://store.steampowered.com/api/dlcforapp/?appid=${appid}" | jq -r '.dlc[]? | "\(.id)=\(.name)"' 2>/dev/null || true)

    # Fallback: appdetails basic,dlc
    if [ -z "$dlc_data" ]; then
        local dlc_ids
        dlc_ids=$(curl -s --connect-timeout 4 "https://store.steampowered.com/api/appdetails?appids=${appid}&filters=basic,dlc" | jq -r ".\"${appid}\".data.dlc[]?" 2>/dev/null || true)
        if [ -n "$dlc_ids" ]; then
            dlc_data=""
            while read -r did; do
                [ -n "$did" ] && dlc_data+="${did}=DLC_${did}"$'\n'
            done <<< "$dlc_ids"
        fi
    fi

    if [ -n "$dlc_data" ]; then
        echo -n "$dlc_data" > "$dlc_file"
        # Ensure trailing newline
        [ -s "$dlc_file" ] && echo "" >> "$dlc_file"
        local count
        count=$(grep -c "=" "$dlc_file" || echo 0)
        echo "[VERIFIED] Successfully wrote $count DLC(s) to: $dlc_file"
    else
        touch "$dlc_file"
        echo "[INFO] No DLC found in Steam API. Created empty file: $dlc_file"
    fi
}

# Ensure DepotDownloader runtime is available
ensure_downloader() {
    local depot_bin=""
    if command -v depotdownloader >/dev/null 2>&1; then
        depot_bin="$(command -v depotdownloader)"
    elif [ -x "$HOME/.local/share/gamectl/bin/DepotDownloader" ]; then
        depot_bin="$HOME/.local/share/gamectl/bin/DepotDownloader"
    elif [ -x "$HOME/.local/bin/depotdownloader" ]; then
        depot_bin="$HOME/.local/bin/depotdownloader"
    else
        local u_arch
        u_arch=$(uname -m 2>/dev/null || echo "x86_64")
        local dl_arch="linux-x64"
        case "$u_arch" in
            aarch64|arm64)
                dl_arch="linux-arm64"
                ;;
            armv7*|armhf)
                dl_arch="linux-arm"
                ;;
            x86_64|amd64)
                dl_arch="linux-x64"
                ;;
            *)
                dl_arch="linux-x64"
                ;;
        esac

        echo "[INFO] Downloading DepotDownloader standalone binary ($dl_arch)..." >&2
        mkdir -p "$HOME/.local/share/gamectl/bin" "$HOME/.local/bin"
        local dl_url="https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-${dl_arch}.zip"
        local run_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$UID}"
        mkdir -p -m 700 "$run_dir"
        local dl_zip="$run_dir/depotdownloader.zip"
        if curl -sL "$dl_url" -o "$dl_zip" 2>/dev/null; then
            unzip -q -o "$dl_zip" -d "$HOME/.local/share/gamectl/bin/"
            chmod +x "$HOME/.local/share/gamectl/bin/DepotDownloader"
            ln -sf "$HOME/.local/share/gamectl/bin/DepotDownloader" "$HOME/.local/bin/depotdownloader"
            rm -f "$dl_zip"
            depot_bin="$HOME/.local/share/gamectl/bin/DepotDownloader"
            echo "[VERIFIED] DepotDownloader installed at: $depot_bin" >&2
        else
            echo "[ERROR] Failed to download DepotDownloader from GitHub." >&2
            return 1
        fi
    fi
    echo "$depot_bin"
}

# Resolve optimal destination directory based on configured libraries and available disk space
resolve_target_library_dir() {
    local safe_title="${1:-game}"
    local candidate_dirs=()

    # 1. Custom libraries from config
    local cfg_libs="$HOME/.config/gamectl/libraries"
    if [ -f "$cfg_libs" ]; then
        while IFS= read -r line || [ -n "$line" ]; do
            line="${line#"${line%%[![:space:]]*}"}" # trim leading
            line="${line%"${line##*[![:space:]]}"}" # trim trailing
            [ -z "$line" ] && continue
            [[ "$line" =~ ^# ]] && continue
            candidate_dirs+=("${line/#\~/$HOME}")
        done < "$cfg_libs"
    fi

    # 2. Extra libraries from environment
    if [ -n "${GAMECTL_LIBRARY_DIRS:-}" ]; then
        local extra_dirs=()
        IFS=":" read -r -a extra_dirs <<< "$GAMECTL_LIBRARY_DIRS"
        candidate_dirs+=("${extra_dirs[@]}")
    fi

    # 3. Default fallback directory
    candidate_dirs+=("$HOME/Games")

    local best_dir="$HOME/Games"
    local max_free=0
    declare -A seen_candidates=()

    for d in "${candidate_dirs[@]}"; do
        [ -n "$d" ] || continue
        [[ -v seen_candidates["$d"] ]] && continue
        seen_candidates["$d"]=1

        # If dir doesn't exist yet, probe parent dir
        local probe_target="$d"
        while [ ! -d "$probe_target" ] && [ "$probe_target" != "/" ] && [ "$probe_target" != "." ]; do
            probe_target="$(dirname "$probe_target")"
        done

        if [ -d "$probe_target" ]; then
            local free_space
            free_space=$(df -PB 1M "$probe_target" 2>/dev/null | awk 'NR==2 {print $4}' || echo "0")
            if [[ "$free_space" =~ ^[0-9]+$ ]] && [ "$free_space" -gt "$max_free" ]; then
                max_free="$free_space"
                best_dir="$d"
            fi
        fi
    done

    echo "$best_dir/$safe_title"
}

# Detect primary OS platform for AppID via Steam API (returns "windows" or "linux")
detect_app_platform_os() {
    local appid="${1:-}"
    [ -z "$appid" ] && echo "linux" && return 0

    local det_json
    det_json=$(fetch_cached_json "https://store.steampowered.com/api/appdetails?appids=${appid}&filters=platforms" "steam_platforms_${appid}" 3600 2>/dev/null || true)
    local is_linux is_win
    is_linux=$(echo "$det_json" | jq -r ".\"${appid}\".data.platforms.linux // false" 2>/dev/null || echo "false")
    is_win=$(echo "$det_json" | jq -r ".\"${appid}\".data.platforms.windows // false" 2>/dev/null || echo "false")
    if [ "$is_linux" != "true" ] && [ "$is_win" = "true" ]; then
        echo "windows"
    else
        echo "linux"
    fi
}

# Headless Game Downloader (Standalone CLI Engine)
download_game() {
    local appid="${1:-}"
    if [ -z "$appid" ]; then
        echo "Usage: gamectl download <appid> [target_dir] [title] [--raw|--inject-only|--all] [--foreground|-f] [--os <linux|windows|all>]" >&2
        return 1
    fi
    shift

    local target_dir=""
    local title=""
    local action="all"     # "all", "inject", "raw"
    local exec_mode="bg"   # "bg" or "fg"
    local target_os=""

    while [ $# -gt 0 ]; do
        case "$1" in
            --raw|--download-only|--no-inject)
                action="raw"
                ;;
            --inject-only|--standalone|--no-sync)
                action="inject"
                ;;
            --all)
                action="all"
                ;;
            --foreground|-f|foreground)
                exec_mode="fg"
                ;;
            --background|-b|background)
                exec_mode="bg"
                ;;
            --os)
                shift
                target_os="${1:-linux}"
                ;;
            --os=*)
                target_os="${1#--os=}"
                ;;
            *)
                if [ -z "$target_dir" ]; then
                    target_dir="$1"
                elif [ -z "$title" ]; then
                    title="$1"
                fi
                ;;
        esac
        shift
    done

    local depot_bin
    depot_bin=$(ensure_downloader) || return 1

    if [ -z "$title" ]; then
        title=$(curl -s --connect-timeout 4 "https://store.steampowered.com/api/appdetails?appids=${appid}&filters=basic" | jq -r ".\"${appid}\".data.name // empty" 2>/dev/null || true)
        [ -z "$title" ] && title="AppID_${appid}"
    fi

    local safe_title
    safe_title=$(echo "$title" | tr -cd '[:alnum:] _-')
    [ -z "$safe_title" ] && safe_title="$appid"

    if [ -z "$target_os" ]; then
        target_os="$(detect_app_platform_os "$appid")"
    fi

    if [ -z "$target_dir" ]; then
        target_dir="$(resolve_target_library_dir "$safe_title")"
    fi

    mkdir -p "$target_dir"
    target_dir="$(cd "$target_dir" && pwd)"
    local run_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$UID}"
    mkdir -p -m 700 "$run_dir"
    local log_file="$run_dir/gamectl_dl_${appid}.log"

    local extra_args=()
    local user_cfg="$HOME/.config/gamectl/steam_user"
    local steam_user="${GAMECTL_STEAM_USER:-}"
    if [ -z "$steam_user" ] && [ -f "$user_cfg" ]; then
        steam_user=$(head -n 1 "$user_cfg" | tr -d '[:space:]')
    fi
    if [ -n "$steam_user" ]; then
        extra_args+=("-username" "$steam_user" "-remember-password")
    fi

    echo "=========================================="
    echo " HEADLESS GAME DOWNLOADER (DepotDownloader)"
    echo "=========================================="
    echo " AppID      : $appid"
    echo " Title      : $title"
    echo " Target Dir : $target_dir"
    echo " Target OS  : $target_os"
    echo " Package    : $action (raw / inject / all)"
    echo " Log Stream : $log_file"
    [ -n "$steam_user" ] && echo " Steam User : $steam_user"
    echo "=========================================="

    if [ "$exec_mode" = "fg" ]; then
        echo "[INFO] Running download in foreground..."
        echo "[INFO] Starting download of AppID $appid ($target_os) to $target_dir at $(date)" > "$log_file"
        "$depot_bin" -app "$appid" -os "$target_os" "${extra_args[@]}" -dir "$target_dir" 2>&1 | tee -a "$log_file"
        local dl_status="${PIPESTATUS[0]}"
        if [ "$dl_status" -eq 0 ]; then
            case "$action" in
                raw)
                    echo "[SUCCESS] Raw asset download completed for $title ($appid)."
                    ;;
                inject)
                    echo "[INFO] Executing standalone GBE Fork injection..."
                    "$SELF_BIN" inject "$target_dir" "$appid" --no-sync
                    echo "[SUCCESS] Download and standalone injection completed for $title ($appid)."
                    ;;
                all|*)
                    echo "[INFO] Executing GBE Fork injection and Steam Client synchronization..."
                    "$SELF_BIN" inject "$target_dir" "$appid"
                    echo "[SUCCESS] All-in-One installation completed for $title ($appid)."
                    ;;
            esac
        else
            echo "[ERROR] Download failed (exit code: $dl_status). See: $log_file" >&2
            return "$dl_status"
        fi
    else
        echo "[INFO] Spawning download process in background..."
        (
            echo "[INFO] Starting download of AppID $appid ($target_os) to $target_dir at $(date)" > "$log_file"
            "$depot_bin" -app "$appid" -os "$target_os" "${extra_args[@]}" -dir "$target_dir" >> "$log_file" 2>&1
            local bg_status=$?
            if [ $bg_status -eq 0 ]; then
                case "$action" in
                    raw)
                        echo "[SUCCESS] Raw asset download completed for $title ($appid) at $(date)." >> "$log_file"
                        ;;
                    inject)
                        echo "[INFO] Executing standalone GBE Fork injection..." >> "$log_file"
                        "$SELF_BIN" inject "$target_dir" "$appid" --no-sync >> "$log_file" 2>&1
                        echo "[SUCCESS] Download and standalone injection completed for $title ($appid) at $(date)." >> "$log_file"
                        ;;
                    all|*)
                        echo "[INFO] Executing auto-injection and Steam Client synchronization..." >> "$log_file"
                        "$SELF_BIN" inject "$target_dir" "$appid" >> "$log_file" 2>&1
                        echo "[SUCCESS] All-in-One complete installation finished for $title ($appid) at $(date)." >> "$log_file"
                        ;;
                esac
            else
                echo "[ERROR] Download failed (exit code: $bg_status) at $(date)." >> "$log_file"
            fi
        ) &
        local pid=$!
        echo "[VERIFIED] Download running in background (PID: $pid)."
        echo "Monitor progress: tail -f $log_file"
    fi
}

# List active and recent downloads
list_downloads() {
    echo "=========================================="
    echo " GAMECTL DOWNLOAD STATUS (DepotDownloader)"
    echo "=========================================="
    local run_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$UID}"
    local count=0
    declare -A seen_logs=()
    for log in "$run_dir"/gamectl_dl_*.log /tmp/gamectl_dl_*.log; do
        [ -f "$log" ] || continue
        [[ -v seen_logs["$log"] ]] && continue
        seen_logs["$log"]=1
        count=$((count + 1))
        local appid
        appid=$(basename "$log" | sed -E 's/gamectl_dl_([0-9]+)\.log/\1/')
        local status="[COMPLETED/STOPPED]"
        if pgrep -f "DepotDownloader.*-app[[:space:]]+${appid}([[:space:]]|$)" >/dev/null 2>&1; then
            status="[DOWNLOADING]"
        fi
        echo "$status AppID: $appid | Log: $log"
        tail -n 2 "$log" 2>/dev/null | sed 's/^/  > /'
        echo "------------------------------------------"
    done
    if [ $count -eq 0 ]; then
        echo "[INFO] No active or recent download tasks in $run_dir."
    fi
}

# Interactive Download Monitor TUI
list_downloads_interactive() {
    local run_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$UID}"
    mkdir -p -m 700 "$run_dir"
    while true; do
        local valid_logs=()
        declare -A seen_logs=()
        for l in "$run_dir"/gamectl_dl_*.log /tmp/gamectl_dl_*.log; do
            [ -f "$l" ] || continue
            [[ -v seen_logs["$l"] ]] && continue
            seen_logs["$l"]=1
            valid_logs+=("$l")
        done

        if [ ${#valid_logs[@]} -eq 0 ]; then
            clear
            echo "${UI_BOX}╭─ DOWNLOAD MANAGER (DepotDownloader) ────────────────────────╮${UI_RST}"
            echo "│ ${UI_CYAN}No active or recent download tasks found in $run_dir${UI_RST}"
            echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
            read -r -p "Press [ENTER] to return to Dashboard..."
            return 0
        fi

        local entries=""
        for log in "${valid_logs[@]}"; do
            local appid
            appid=$(basename "$log" | sed -E 's/gamectl_dl_([0-9]+)\.log/\1/')
            local pid
            pid=$(pgrep -f "DepotDownloader.*-app[[:space:]]+${appid}([[:space:]]|$)" 2>/dev/null | head -n 1 || true)
            local status="${UI_ICE}[COMPLETED]${UI_RST}"
            [ -n "$pid" ] && status="${UI_GREEN}[RUNNING PID:$pid]${UI_RST}"
            local last_line
            last_line=$(tail -n 1 "$log" 2>/dev/null | tr -d '\r\n\t' | cut -c1-60)
            [ -z "$last_line" ] && last_line="Waiting for output..."
            entries+="${appid}\t${status}\t${log}\t${last_line}\n"
        done

        local selection
        selection=$(printf "%b" "$entries" | fzf \
            --delimiter=$'\t' \
            --with-nth=1,2,4 \
            --border-label="  ╢ gamectl :: Download Manager ╟  " \
            --border-label-pos=2 \
            --header="ACTIVE DOWNLOADS (Enter: Actions & Stream │ Ctrl-K: Stop │ Esc: Back)" \
            --prompt="Downloads > " \
            --preview="echo -e '\033[38;5;60mLog: {3}\033[0m\n──────────────────────────────────────────'; tail -n 30 {3}" \
            --preview-window=right:60%:border-rounded:wrap \
            --bind="ctrl-k:execute(appid={1}; pid=\$(pgrep -f \"DepotDownloader.*-app[[:space:]]+\${appid}([[:space:]]|$)\" 2>/dev/null | head -n 1); if [ -n \"\$pid\" ]; then kill \"\$pid\" 2>/dev/null && echo \"[INFO] AppID \$appid (PID \$pid) terminated.\"; else echo \"[INFO] AppID \$appid not active.\"; fi; bash -c 'read -n 1 -s -r -p \"Press any key to continue...\"')" \
        ) || break

        if [ -n "$selection" ]; then
            local sel_appid sel_log sel_status
            sel_appid=$(echo "$selection" | awk -F'\t' '{print $1}')
            sel_log=$(echo "$selection" | awk -F'\t' '{print $3}')
            sel_status=$(echo "$selection" | awk -F'\t' '{print $2}')

            clear
            echo "${UI_BOX}╭─ DOWNLOAD ACTIONS: AppID ${UI_BOLD}$sel_appid${UI_RST} $sel_status ─────────────╮${UI_RST}"
            echo "│ ${UI_CYAN}Log file${UI_RST}: ${UI_DIM}$sel_log${UI_RST}"
            echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
            echo "  ${UI_PURPLE}1)${UI_RST} Stream live output (tail -f)"
            echo "  ${UI_PURPLE}2)${UI_RST} Terminate this process (Kill task)"
            echo "  ${UI_PURPLE}3)${UI_RST} Remove this log history file"
            echo "  ${UI_DIM}4)${UI_RST} Return to download list"
            echo
            read -r -p "Select option [1-4]: " dl_opt

            case "$dl_opt" in
                1)
                    clear
                    echo "${UI_BOX}╭─ LIVE STREAM: AppID $sel_appid ─────────────────────────────╮${UI_RST}"
                    echo "│ ${UI_CYAN}Press Ctrl-C when done to return${UI_RST}"
                    echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
                    tail -f "$sel_log" || true
                    read -r -p "Press [ENTER] to return..."
                    ;;
                2)
                    local k_pid
                    k_pid=$(pgrep -f "DepotDownloader.*-app[[:space:]]+${sel_appid}([[:space:]]|$)" 2>/dev/null | head -n 1 || true)
                    if [ -n "$k_pid" ]; then
                        kill "$k_pid" 2>/dev/null && echo "  ${UI_GREEN}[SUCCESS] Download process AppID $sel_appid (PID $k_pid) stopped.${UI_RST}"
                    else
                        echo "  [INFO] AppID $sel_appid is not currently running."
                    fi
                    read -r -p "Press [ENTER] to continue..."
                    ;;
                3)
                    rm -f "$sel_log"
                    echo "  [INFO] Log file $sel_log deleted."
                    read -r -p "Press [ENTER] to continue..."
                    ;;
                *)
                    ;;
            esac
        fi
    done
}

# Dual-Mode Steam Client & SLSsteam Full DLC Sync
sync_steam() {
    local appid="$1"
    local title="${2:-}"
    local game_dir="${3:-}"

    if [ -z "$appid" ] || [ "$appid" = "STANDALONE" ]; then
        echo "[WARN] Invalid numeric AppID. Skipping Steam synchronization." >&2
        return 0
    fi

    if [ -z "$title" ]; then
        title="AppID_${appid}"
    fi

    local safe_title
    safe_title=$(echo "$title" | tr -cd '[:alnum:] _-')
    [ -z "$safe_title" ] && safe_title="$appid"

    echo "[INFO] Synchronizing Steam Client & SLSsteam for: $title ($appid)..."

    # 1. Fetch DLC mapping via Steam API
    local dlc_json
    dlc_json=$(curl -s --connect-timeout 4 "https://store.steampowered.com/api/dlcforapp/?appid=${appid}" 2>/dev/null || echo "{}")

    # 2. Update ~/.config/SLSsteam/config.yaml using ruamel.yaml
    local sls_cfg="$HOME/.config/SLSsteam/config.yaml"
    if [ -f "$sls_cfg" ]; then
        python3 -c "
import sys, json

cfg_path = sys.argv[1]
appid = int(sys.argv[2])
dlc_raw = sys.argv[3]

has_ruamel = False
try:
    from ruamel.yaml import YAML
    yaml_engine = YAML()
    yaml_engine.preserve_quotes = True
    has_ruamel = True
except Exception:
    try:
        import yaml as pyyaml
    except Exception:
        print('[ERROR] No YAML library found in Python (ruamel.yaml or pyyaml)', file=sys.stderr)
        sys.exit(1)

try:
    with open(cfg_path, 'r') as f:
        if has_ruamel:
            data = yaml_engine.load(f) or {}
        else:
            data = pyyaml.safe_load(f) or {}

    if 'AppIds' not in data or data['AppIds'] is None:
        data['AppIds'] = []
    if appid not in data['AppIds']:
        data['AppIds'].append(appid)

    if 'AdditionalApps' not in data or data['AdditionalApps'] is None:
        data['AdditionalApps'] = []
    if appid not in data['AdditionalApps']:
        data['AdditionalApps'].append(appid)

    dlc_obj = json.loads(dlc_raw)
    dlc_list = dlc_obj.get('dlc', [])
    if dlc_list:
        if 'DlcData' not in data or data['DlcData'] is None:
            data['DlcData'] = {}
        if appid not in data['DlcData'] or data['DlcData'][appid] is None:
            data['DlcData'][appid] = {}
        for item in dlc_list:
            d_id = int(item['id'])
            d_name = item.get('name', f'DLC {d_id}')
            data['DlcData'][appid][d_id] = d_name

    with open(cfg_path, 'w') as f:
        if has_ruamel:
            yaml_engine.dump(data, f)
        else:
            pyyaml.dump(data, f, default_flow_style=False, sort_keys=False)
    engine_name = 'ruamel.yaml' if has_ruamel else 'pyyaml (fallback)'
    print(f'[VERIFIED] SLSsteam config.yaml: AppID {appid} and {len(dlc_list)} DLC(s) registered ({engine_name}).')
except Exception as e:
    print(f'[WARN] SLSsteam config sync notice: {e}', file=sys.stderr)
" "$sls_cfg" "$appid" "$dlc_json" 2>/dev/null || true
    fi

    # 3. Create appmanifest_<appid>.acf in Steam steamapps
    local steam_apps
    steam_apps="$(get_steam_primary_apps)"
    if [ -d "$steam_apps" ]; then
        # Guard against concurrent Steam client memory lock on manifests
        check_steam_active "Writing appmanifest_${appid}.acf" || true

        local acf_file="$steam_apps/appmanifest_${appid}.acf"
        local install_name="$safe_title"
        local size_bytes="1000000000"
        local steamid
        steamid=$(resolve_active_steamid)

        if [ -n "$game_dir" ] && [ -d "$game_dir" ]; then
            install_name="$(basename "$game_dir")"
            local calc_sz
            calc_sz=$(du -sb "$game_dir" 2>/dev/null | awk '{print $1}')
            [ -n "$calc_sz" ] && [ "$calc_sz" -gt 0 ] && size_bytes="$calc_sz"
        fi

        cat <<ACF > "$acf_file"
"AppState"
{
	"appid"		"$appid"
	"Universe"		"1"
	"name"		"$safe_title"
	"StateFlags"		"4"
	"installdir"		"$install_name"
	"LastUpdated"		"$(date +%s)"
	"SizeOnDisk"		"$size_bytes"
	"buildid"		"1"
	"LastOwner"		"$steamid"
	"UserConfig"
	{
		"language"		"english"
	}
	"MountedConfig"
	{
		"language"		"english"
	}
}
ACF
        # Symlink in steamapps/common if game_dir is external, or ensure install dir exists
        mkdir -p "$steam_apps/common"
        if [ -n "$game_dir" ] && [ -d "$game_dir" ]; then
            local common_target="$steam_apps/common/$install_name"
            if [ ! -e "$common_target" ]; then
                ln -sf "$game_dir" "$common_target"
                echo "[INFO] Created common symlink: $common_target -> $game_dir"
            fi
        else
            mkdir -p "$steam_apps/common/$install_name"
        fi
        echo "[VERIFIED] appmanifest_${appid}.acf registered (Status: Installed in Steam, Size: $size_bytes bytes)."
    fi
}

# Entitle game and adopt assets in official Steam client without downloading
unlock_game() {
    local appid="${1:-}"
    local title="${2:-}"

    if [ -z "$appid" ]; then
        echo "Usage: gamectl entitle <appid> [title] (aliases: unlock, adopt-steam)" >&2
        return 1
    fi

    if [ -z "$title" ]; then
        echo "[INFO] Fetching game title for AppID $appid from Steam Store API..."
        title=$(curl -s --connect-timeout 4 "https://store.steampowered.com/api/appdetails?appids=${appid}&filters=basic" | jq -r ".\"${appid}\".data.name // empty" 2>/dev/null || true)
        [ -z "$title" ] && title="AppID_${appid}"
    fi

    echo "${UI_BOX}╭─ STEAM ENTITLEMENT & ACF ADOPTION ENGINE ───────────────────╮${UI_RST}"
    echo "│ ${UI_CYAN}Target Game${UI_RST}: ${UI_BOLD}$title${UI_RST} ${UI_DIM}(AppID: $appid)${UI_RST}"
    echo "│ ${UI_DIM}Adopts local files, community Steam Input & Vulkan shader caching${UI_RST}"
    echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"

    sync_steam "$appid" "$title" ""
    echo "  ${UI_GREEN}[SUCCESS] Game '$title' ($appid) entitled in Steam Client with Full DLC & ACF manifest.${UI_RST}"
}

# Aliases for entitlement engine
entitle_game() { unlock_game "$@"; }
adopt_steam() { unlock_game "$@"; }

# Interactive Steam Entitlement & ACF Adoption Wizard
unlock_interactive() {
    local u_appid_raw=""
    u_appid_raw=$(echo "Enter Steam AppID (e.g. 105600, 48000, 730) and press ENTER" | fzf \
        --print-query \
        --border-label="  ╢ Steam Entitlement & ACF Adoption Wizard ╟  " \
        --border-label-pos=2 \
        --header="Enter numeric AppID (Enter: Adopt │ Esc: Cancel)" \
        --prompt="Steam AppID > " \
        --height=20% \
        --reverse 2>/dev/null) || return 0

    local u_appid
    u_appid=$(echo "$u_appid_raw" | head -n 1 | tr -d '[:space:]')
    [ -z "$u_appid" ] && return 0

    if [[ ! "$u_appid" =~ ^[0-9]+$ ]]; then
        echo "  ${UI_RED}[ERROR] AppID must be numeric characters (e.g. 105600).${UI_RST}"
        sleep 1.5
        return 1
    fi

    echo "  [INFO] Fetching title from Steam Store API for AppID $u_appid..."
    local u_title
    u_title=$(curl -s --connect-timeout 4 "https://store.steampowered.com/api/appdetails?appids=${u_appid}&filters=basic" | jq -r ".\"${u_appid}\".data.name // empty" 2>/dev/null || true)
    [ -z "$u_title" ] && u_title="AppID_${u_appid}"

    echo "  Registering: $u_title ($u_appid)..."
    unlock_game "$u_appid" "$u_title"
    sleep 1.2
}

entitle_interactive() { unlock_interactive "$@"; }


# --- [MODULE] src/runners/40_wrappers.sh ---
# Detect P2P multiplayer compatibility hooks, mod loaders, and custom DLL overrides for a game directory
detect_dll_overrides() {
    local gdir="${1:-}"
    [ -n "$gdir" ] && [ -d "$gdir" ] || return 0

    local has_onlinefix=0
    local has_bepinex=0
    local has_ue4ss=0
    local has_reframework=0
    local has_reshade=0
    local custom_overrides=""

    # 1. Check custom declarative .dll_overrides file
    if [ -f "$gdir/.dll_overrides" ]; then
        custom_overrides=$(grep -v -E '^[[:space:]]*(#|$)' "$gdir/.dll_overrides" 2>/dev/null | tr '\n' ';' || true)
    fi

    # 2. Scan root and subdirectories (up to depth 3) excluding runtime/save folders
    local found_signatures
    found_signatures=$(find "$gdir" -maxdepth 3 \( \
        -name "pfx" -o -name ".git" -o -name ".save_snapshots" -o -name "saves" \
    \) -prune -o \( \
        -iname "OnlineFix64.dll" -o -iname "OnlineFix.dll" -o -iname "dnet.dll" -o \
        -iname "SteamOverlay64.dll" -o -iname "winmm.dll" -o -iname "version.dll" -o \
        -iname "BepInEx" -o -iname "doorstop_config.ini" -o -iname "winhttp.dll" -o \
        -iname "ue4ss" -o -iname "UE4SS.dll" -o -iname "dwmapi.dll" -o \
        -iname "dinput8.dll" -o \
        -iname "ReShade.ini" -o -iname "dxgi.dll" \
    \) -print 2>/dev/null || true)

    if [ -n "$found_signatures" ]; then
        while IFS= read -r item; do
            [ -z "$item" ] && continue
            local base
            base=$(basename "$item")
            case "${base,,}" in
                onlinefix64.dll|onlinefix.dll|dnet.dll|steamoverlay64.dll|winmm.dll|version.dll)
                    has_onlinefix=1 ;;
                bepinex|doorstop_config.ini|winhttp.dll)
                    has_bepinex=1 ;;
                ue4ss|ue4ss.dll|dwmapi.dll)
                    has_ue4ss=1 ;;
                dinput8.dll)
                    has_reframework=1 ;;
                reshade.ini|dxgi.dll)
                    has_reshade=1 ;;
            esac
        done <<< "$found_signatures"
    fi

    # Return empty string if no mod/OnlineFix signatures or custom overrides found
    if [ "$has_onlinefix" -eq 0 ] && [ "$has_bepinex" -eq 0 ] && \
       [ "$has_ue4ss" -eq 0 ] && [ "$has_reframework" -eq 0 ] && \
       [ "$has_reshade" -eq 0 ] && [ -z "$custom_overrides" ]; then
        return 0
    fi

    local detected_tokens=""
    if [ "$has_onlinefix" -eq 1 ]; then
        detected_tokens="${detected_tokens:+${detected_tokens};}onlinefix=n;onlinefix64=n;steamoverlay64=n;dnet=n;winmm=n,b;version=n,b;steam_api64=n;steam_api=n"
    fi
    if [ "$has_bepinex" -eq 1 ]; then
        detected_tokens="${detected_tokens:+${detected_tokens};}winhttp=n,b"
    fi
    if [ "$has_ue4ss" -eq 1 ]; then
        detected_tokens="${detected_tokens:+${detected_tokens};}dwmapi=n,b"
    fi
    if [ "$has_reframework" -eq 1 ]; then
        detected_tokens="${detected_tokens:+${detected_tokens};}dinput8=n,b"
    fi
    if [ "$has_reshade" -eq 1 ]; then
        detected_tokens="${detected_tokens:+${detected_tokens};}dxgi=n,b"
    fi
    if [ -n "$custom_overrides" ]; then
        detected_tokens="${detected_tokens:+${detected_tokens};}${custom_overrides}"
    fi

    local user_env_overrides="${2:-${WINEDLLOVERRIDES:-}}"
    declare -A seen=()
    declare -A values=()
    local ordered_keys=()

    # 1. Process user environment overrides first to preserve user precedence
    if [ -n "$user_env_overrides" ]; then
        local u_arr=()
        IFS=';' read -r -a u_arr <<< "$user_env_overrides"
        for item in "${u_arr[@]}"; do
            [ -z "$item" ] && continue
            local k="${item%%=*}"
            local v="${item#*=}"
            [ "$item" = "$k" ] && v="n"
            k=$(echo "$k" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')
            v=$(echo "$v" | tr -d '[:space:]')
            [ -z "$k" ] && continue
            if [ -z "${seen["$k"]:-}" ]; then
                seen["$k"]=1
                ordered_keys+=("$k")
                values["$k"]="$v"
            fi
        done
    fi

    # 2. Process detected mod tokens (add only if not overridden by user)
    local d_arr=()
    IFS=';' read -r -a d_arr <<< "$detected_tokens"
    for item in "${d_arr[@]}"; do
        [ -z "$item" ] && continue
        local k="${item%%=*}"
        local v="${item#*=}"
        [ "$item" = "$k" ] && v="n"
        k=$(echo "$k" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')
        v=$(echo "$v" | tr -d '[:space:]')
        [ -z "$k" ] && continue
        if [ -z "${seen["$k"]:-}" ]; then
            seen["$k"]=1
            ordered_keys+=("$k")
            values["$k"]="$v"
        fi
    done

    # 3. Format normalized semicolon-separated output
    local result=""
    for k in "${ordered_keys[@]}"; do
        local entry="${k}=${values["$k"]}"
        result="${result:+${result};}${entry}"
    done
    echo "$result"
}

# Discover runner for Windows games (priority: umu-run -> GE-Proton / Proton Steam -> wine)
find_runner() {
    local target_dir="${1:-}"

    # Priority 0: Per-game runner override or environment override
    if [ -n "$target_dir" ] && [ -f "$target_dir/.runner" ]; then
        local g_runner
        g_runner=$(head -n 1 "$target_dir/.runner" | tr -d '[:space:]')
        if [ -n "$g_runner" ] && { [ -x "$g_runner" ] || command -v "$g_runner" >/dev/null 2>&1; }; then
            echo "$g_runner"
            return 0
        fi
    fi
    if [ -n "${GAMECTL_RUNNER:-}" ]; then
        if [ -x "$GAMECTL_RUNNER" ] || command -v "$GAMECTL_RUNNER" >/dev/null 2>&1; then
            echo "$GAMECTL_RUNNER"
            return 0
        fi
    fi
    if [ -f "$HOME/.config/gamectl/runner" ]; then
        local user_runner
        user_runner=$(head -n 1 "$HOME/.config/gamectl/runner" | tr -d '[:space:]')
        if [ -n "$user_runner" ] && { [ -x "$user_runner" ] || command -v "$user_runner" >/dev/null 2>&1; }; then
            echo "$user_runner"
            return 0
        fi
    fi

    # Priority 1: umu-run
    if command -v umu-run >/dev/null 2>&1; then
        echo "umu-run"
        return 0
    fi

    # Priority 2: GE-Proton / Proton in Steam compatibilitytools.d or common
    local s_dyn_root
    s_dyn_root="$(get_steam_root 2>/dev/null || true)"
    local compat_dirs=(
        "$s_dyn_root/compatibilitytools.d"
        "$HOME/.local/share/Steam/compatibilitytools.d"
        "$HOME/.steam/root/compatibilitytools.d"
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam/compatibilitytools.d"
    )
    for cdir in "${compat_dirs[@]}"; do
        [ -d "$cdir" ] || continue
        local p
        while read -r p; do
            [ -z "$p" ] && continue
            if [ -x "$p/proton" ]; then
                echo "$p/proton"
                return 0
            fi
        done < <(find "$cdir" -mindepth 1 -maxdepth 1 -type d -name "*Proton*" 2>/dev/null | sort -Vr)
    done

    # Check Proton in Steam common libraries
    local steam_lib
    while read -r steam_lib; do
        [ -d "$steam_lib/common" ] || continue
        local p
        while read -r p; do
            [ -z "$p" ] && continue
            if [ -x "$p/proton" ]; then
                echo "$p/proton"
                return 0
            fi
        done < <(find "$steam_lib/common" -mindepth 1 -maxdepth 1 -type d -name "Proton*" 2>/dev/null | sort -Vr)
    done < <(get_steam_libraries 2>/dev/null || true)

    # Priority 3: System Wine
    if command -v wine64 >/dev/null 2>&1; then
        echo "wine64"
        return 0
    elif command -v wine >/dev/null 2>&1; then
        echo "wine"
        return 0
    fi

    # Priority 4: Internal wine binary inside GE-Proton files/bin
    for cdir in "${compat_dirs[@]}"; do
        [ -d "$cdir" ] || continue
        local w
        w=$(find "$cdir" -type f -name "wine64" -o -name "wine" 2>/dev/null | head -n 1)
        if [ -n "$w" ] && [ -x "$w" ]; then
            echo "$w"
            return 0
        fi
    done

    return 1
}

# Resolve wineserver binary matching active runner or system/Proton installation
get_wineserver_bin() {
    local runner="${1:-}"

    # 1. If runner points directly to a Proton executable or runner string contains proton
    if [ -n "$runner" ]; then
        if [[ "$runner" =~ proton ]] || [ -f "$runner" ]; then
            local p_base
            p_base="$(dirname "$runner")"
            for sub in "files/bin/wineserver" "dist/bin/wineserver" "bin/wineserver"; do
                if [ -x "$p_base/$sub" ]; then
                    echo "$p_base/$sub"
                    return 0
                fi
            done
        fi
    fi

    # 2. Check system PATH for wineserver
    if command -v wineserver >/dev/null 2>&1; then
        command -v wineserver
        return 0
    fi

    # 3. Fallback: Search Steam compatibility tools for highest GE-Proton wineserver
    local s_dyn_root
    s_dyn_root="$(get_steam_root 2>/dev/null || true)"
    local compat_dirs=(
        "$s_dyn_root/compatibilitytools.d"
        "$HOME/.local/share/Steam/compatibilitytools.d"
        "$HOME/.steam/root/compatibilitytools.d"
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam/compatibilitytools.d"
    )
    for cdir in "${compat_dirs[@]}"; do
        [ -n "$cdir" ] && [ -d "$cdir" ] || continue
        local p
        while read -r p; do
            [ -z "$p" ] && continue
            for sub in "files/bin/wineserver" "dist/bin/wineserver" "bin/wineserver"; do
                if [ -x "$p/$sub" ]; then
                    echo "$p/$sub"
                    return 0
                fi
            done
        done < <(find "$cdir" -mindepth 1 -maxdepth 1 -type d -name "*Proton*" 2>/dev/null | sort -Vr)
    done

    # 4. Check system wine64 / wine adjacent wineserver
    for w in "$(command -v wine64 2>/dev/null || true)" "$(command -v wine 2>/dev/null || true)"; do
        [ -n "$w" ] || continue
        local w_dir
        w_dir="$(dirname "$w")"
        if [ -x "$w_dir/wineserver" ]; then
            echo "$w_dir/wineserver"
            return 0
        fi
    done

    return 1
}

# Resolve active Steam compatibility tools directory
get_compat_dir() {
    local s_dyn_root
    s_dyn_root="$(get_steam_root 2>/dev/null || true)"
    if [ -n "$s_dyn_root" ] && [ -d "$s_dyn_root" ]; then
        echo "$s_dyn_root/compatibilitytools.d"
    elif [ -d "$HOME/.steam/root" ]; then
        echo "$HOME/.steam/root/compatibilitytools.d"
    else
        echo "$HOME/.local/share/Steam/compatibilitytools.d"
    fi
}

# List local and latest upstream GE-Proton releases
proton_list() {
    local s_dyn_root
    s_dyn_root="$(get_steam_root 2>/dev/null || true)"
    local compat_dirs=(
        "$s_dyn_root/compatibilitytools.d"
        "$HOME/.local/share/Steam/compatibilitytools.d"
        "$HOME/.steam/root/compatibilitytools.d"
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam/compatibilitytools.d"
    )

    declare -A local_installs=()
    for cdir in "${compat_dirs[@]}"; do
        [ -n "$cdir" ] && [ -d "$cdir" ] || continue
        for d in "$cdir"/*; do
            [ -d "$d" ] || continue
            local t_name
            t_name=$(basename "$d")
            local_installs["$t_name"]="$d"
        done
    done

    echo "${UI_BOX}╭─ GE-PROTON RELEASE MANAGER (HEADLESS) ───────────────────────╮${UI_RST}"
    echo "│ ${UI_CYAN}Target Path${UI_RST}: $(get_compat_dir)"
    echo "│ ${UI_CYAN}Installed  ${UI_RST}: ${#local_installs[@]} version(s) detected locally"
    echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"

    # 1. Show local versions
    echo
    echo "  ${UI_PURPLE}[LOCAL VERSIONS]${UI_RST}"
    if [ ${#local_installs[@]} -gt 0 ]; then
        for v in "${!local_installs[@]}"; do
            local v_path="${local_installs["$v"]}"
            local v_sz
            v_sz=$(du -sh "$v_path" 2>/dev/null | awk '{print $1}')
            echo "    • ${UI_BOLD}$(printf '%-22s' "$v")${UI_RST} : ${UI_GREEN}[INSTALLED]${UI_RST} ${UI_DIM}(Size: $v_sz | $v_path)${UI_RST}"
        done
    else
        echo "    ${UI_DIM}(No GE-Proton versions installed in compatibilitytools.d/)${UI_RST}"
    fi

    # 2. Query GitHub Releases upstream
    echo
    echo "  ${UI_PURPLE}[UPSTREAM RELEASES (GitHub: GloriousEggroll/proton-ge-custom)]${UI_RST}"
    local arch_pat="x86_64\\.tar\\.gz$"
    case "$(uname -m 2>/dev/null || echo "x86_64")" in
        aarch64|arm64) arch_pat="aarch64\\.tar\\.gz$" ;;
        *) arch_pat="x86_64\\.tar\\.gz$" ;;
    esac

    local raw_json=""
    raw_json=$(curl -s --connect-timeout 5 --max-time 10 "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases?per_page=5" 2>/dev/null || echo "")

    local parsed_releases=""
    if [ -n "$raw_json" ] && echo "$raw_json" | jq -e 'if type=="array" then true else false end' >/dev/null 2>&1; then
        parsed_releases=$(echo "$raw_json" | jq -r --arg pat "$arch_pat" '
            .[] | {
                tag: .tag_name,
                asset: ([.assets[] | select(.name | test($pat))] | first)
            } | select(.asset != null) | [
                .tag,
                .asset.name,
                ((.asset.size // 0) / 1048576 | floor | tostring + " MB"),
                .asset.browser_download_url
            ] | @tsv
        ' 2>/dev/null || true)
    fi

    if [ -n "$parsed_releases" ]; then
        local idx=0
        while IFS=$'\t' read -r r_tag r_asset r_size r_url; do
            [ -z "$r_tag" ] && continue
            idx=$((idx + 1))
            local status_badge="${UI_CYAN}[AVAILABLE]${UI_RST}"
            [ -n "${local_installs["$r_tag"]:-}" ] && status_badge="${UI_GREEN}[INSTALLED]${UI_RST}"
            [ "$idx" -eq 1 ] && status_badge="${status_badge} ${UI_AMBER}(Latest)${UI_RST}"
            echo "    • ${UI_BOLD}$(printf '%-22s' "$r_tag")${UI_RST} : $status_badge ${UI_DIM}(Download Size: $r_size)${UI_RST}"
        done <<< "$parsed_releases"
        echo
        echo "  ${UI_DIM}Install command: gamectl proton-install [tag|latest]${UI_RST}"
    else
        echo "    ${UI_AMBER}[WARN]${UI_RST} ${UI_DIM}Unable to fetch upstream release list (Offline or GitHub API rate-limited).${UI_RST}"
        echo "    ${UI_DIM}You can still install directly via: gamectl proton-install <tag_name>${UI_RST}"
    fi
    echo
}

# Headless GE-Proton installer
proton_install() {
    local target_tag="${1:-latest}"
    local auto_yes=false
    shift || true
    while [ $# -gt 0 ]; do
        case "$1" in
            -y|--yes) auto_yes=true; shift ;;
            *) shift ;;
        esac
    done

    local compat_dir
    compat_dir="$(get_compat_dir)"
    mkdir -p "$compat_dir"

    local arch_suffix="x86_64"
    case "$(uname -m 2>/dev/null || echo "x86_64")" in
        aarch64|arm64) arch_suffix="aarch64" ;;
        *) arch_suffix="x86_64" ;;
    esac

    echo "[INFO] Preparing GE-Proton installation ($target_tag) for architecture $arch_suffix..."

    local resolved_tag=""
    local download_url=""

    if [ "$target_tag" = "latest" ]; then
        local latest_json
        latest_json=$(curl -s --connect-timeout 5 --max-time 10 "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases/latest" 2>/dev/null || echo "")
        if [ -n "$latest_json" ] && echo "$latest_json" | jq -e '.tag_name' >/dev/null 2>&1; then
            resolved_tag=$(echo "$latest_json" | jq -r '.tag_name')
            local pat="${arch_suffix}\\.tar\\.gz$"
            download_url=$(echo "$latest_json" | jq -r --arg pat "$pat" '
                [.assets[] | select(.name | test($pat))] | first | .browser_download_url
            ' 2>/dev/null || echo "")
        fi
        if [ -z "$resolved_tag" ] || [ -z "$download_url" ] || [ "$download_url" = "null" ]; then
            echo "[ERROR] Failed to obtain latest release URL from GitHub API." >&2
            echo "        Specify target tag explicitly: gamectl proton-install <tag_name>" >&2
            return 1
        fi
    else
        resolved_tag="$target_tag"
        local tag_json
        tag_json=$(curl -s --connect-timeout 5 --max-time 10 "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases/tags/${resolved_tag}" 2>/dev/null || echo "")
        if [ -n "$tag_json" ] && echo "$tag_json" | jq -e '.tag_name' >/dev/null 2>&1; then
            local pat="${arch_suffix}\\.tar\\.gz$"
            download_url=$(echo "$tag_json" | jq -r --arg pat "$pat" '
                [.assets[] | select(.name | test($pat))] | first | .browser_download_url
            ' 2>/dev/null || echo "")
        fi
        if [ -z "$download_url" ] || [ "$download_url" = "null" ]; then
            # Direct asset fallback pattern
            download_url="https://github.com/GloriousEggroll/proton-ge-custom/releases/download/${resolved_tag}/${resolved_tag}-${arch_suffix}.tar.gz"
        fi
    fi

    echo "[INFO] Target version : $resolved_tag"
    echo "[INFO] Download URL   : $download_url"
    echo "[INFO] Target Dir     : $compat_dir/"

    if [ -d "$compat_dir/$resolved_tag" ] && [ "$auto_yes" = false ]; then
        if [ -t 0 ]; then
            echo -n "[WARN] Directory $resolved_tag already exists. Overwrite installation? [y/N]: "
            local confirm=""
            read -t 10 -r confirm || confirm="n"
            if [[ ! "$confirm" =~ ^[yY] ]]; then
                echo "[INFO] Installation canceled."
                return 0
            fi
        fi
    fi

    echo "[INFO] Downloading and streaming tarball extraction..."
    if curl -# -fL "$download_url" | tar -xz -C "$compat_dir/"; then
        local installed_folder="$compat_dir/$resolved_tag"
        if [ ! -d "$installed_folder" ]; then
            installed_folder=$(find "$compat_dir" -mindepth 1 -maxdepth 1 -type d -name "*${resolved_tag}*" 2>/dev/null | head -n 1)
        fi
        if [ -n "$installed_folder" ] && [ -f "$installed_folder/compatibilitytool.vdf" ]; then
            [ -f "$installed_folder/proton" ] && chmod +x "$installed_folder/proton"
            echo "[VERIFIED] GE-Proton $resolved_tag installed successfully in: $installed_folder"
            return 0
        else
            echo "[ERROR] Extraction completed but compatibilitytool.vdf not found in $installed_folder." >&2
            return 1
        fi
    else
        echo "[ERROR] Failed to download or extract $resolved_tag from $download_url" >&2
        return 1
    fi
}

# Safely remove an installed GE-Proton version
proton_remove() {
    local tag="${1:-}"
    local auto_yes=false
    shift || true
    while [ $# -gt 0 ]; do
        case "$1" in
            -y|--yes) auto_yes=true; shift ;;
            *) shift ;;
        esac
    done

    if [ -z "$tag" ]; then
        echo "Usage: gamectl proton-remove <tag> [-y|--yes]" >&2
        return 1
    fi

    # Path traversal protection
    if [[ "$tag" =~ (\.\.|\/|\\) ]]; then
        echo "[ERROR] Invalid tag (path traversal sequence detected): $tag" >&2
        return 1
    fi

    local s_dyn_root
    s_dyn_root="$(get_steam_root 2>/dev/null || true)"
    local compat_dirs=(
        "$s_dyn_root/compatibilitytools.d"
        "$HOME/.local/share/Steam/compatibilitytools.d"
        "$HOME/.steam/root/compatibilitytools.d"
        "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam/compatibilitytools.d"
    )

    local target_dir=""
    for cdir in "${compat_dirs[@]}"; do
        [ -n "$cdir" ] && [ -d "$cdir" ] || continue
        if [ -d "$cdir/$tag" ]; then
            target_dir="$cdir/$tag"
            break
        fi
    done

    if [ -z "$target_dir" ] || [ ! -d "$target_dir" ]; then
        echo "[ERROR] GE-Proton version '$tag' not found in compatibilitytools.d/" >&2
        return 1
    fi

    # Canonical path traversal assertion
    local real_target
    real_target="$(realpath "$target_dir" 2>/dev/null || echo "")"
    if [[ "$real_target" != *"compatibilitytools.d"* ]]; then
        echo "[ERROR] Path traversal guard failed for: $target_dir" >&2
        return 1
    fi

    local sz
    sz=$(du -sh "$target_dir" 2>/dev/null | awk '{print $1}')

    if [ "$auto_yes" = false ] && [ -t 0 ]; then
        echo -n "Delete GE-Proton directory '$tag' (Size: $sz)? [y/N]: "
        local confirm=""
        read -t 10 -r confirm || confirm="n"
        echo
        if [[ ! "$confirm" =~ ^[yY] ]]; then
            echo "[INFO] Removal of $tag canceled."
            return 0
        fi
    fi

    rm -rf "$target_dir"
    echo "[VERIFIED] GE-Proton '$tag' removed successfully ($sz disk space freed)."
    return 0
}

# Wine Prefix Swiss Army Knife & Wineserver Lifecycle Guard (Chunk 4)
manage_prefix() {
    local game_dir="${1:-}"
    local action="${2:-}"
    shift 2 2>/dev/null || shift $# 2>/dev/null || true

    if [ -z "$game_dir" ] || [ ! -d "$game_dir" ]; then
        echo "[ERROR] Game directory not found or invalid: $game_dir" >&2
        echo "Usage: gamectl pfx <game_dir> [winecfg|regedit|cmd|shell|kill|clean|winetricks] [args...]" >&2
        return 1
    fi

    # Canonicalize game_dir path
    game_dir="$(cd "$game_dir" 2>/dev/null && pwd || echo "$game_dir")"
    local pfx_dir="$game_dir/pfx"
    local runner_bin
    runner_bin="$(find_runner "$game_dir" 2>/dev/null || true)"
    [ -z "$runner_bin" ] && runner_bin="wine"

    # AppID resolution
    local appid="0"
    if [ -f "$game_dir/steam_appid.txt" ]; then
        appid=$(tr -dc '0-9' < "$game_dir/steam_appid.txt")
        [ -z "$appid" ] && appid="0"
    fi

    # Wineserver resolution
    local ws_bin
    ws_bin="$(get_wineserver_bin "$runner_bin" 2>/dev/null || echo "")"

    # Interactive menu if action is empty and stdin is terminal
    if [ -z "$action" ]; then
        if [ -t 0 ]; then
            clear
            echo "${UI_BOX}╭─ WINE PREFIX SWISS ARMY KNIFE ──────────────────────────────╮${UI_RST}"
            echo "│ ${UI_CYAN}Game Directory${UI_RST} : ${UI_BOLD}$game_dir${UI_RST}"
            echo "│ ${UI_CYAN}Prefix Path   ${UI_RST} : ${UI_BOLD}$pfx_dir${UI_RST}"
            echo "│ ${UI_CYAN}Active Runner ${UI_RST} : ${UI_GREEN}$runner_bin${UI_RST}"
            echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
            echo "  ${UI_PURPLE}1)${UI_RST} winecfg      ${UI_DIM}(Wine Audio, Graphics & Windows Version Config)${UI_RST}"
            echo "  ${UI_PURPLE}2)${UI_RST} regedit      ${UI_DIM}(Windows Registry Editor)${UI_RST}"
            echo "  ${UI_PURPLE}3)${UI_RST} cmd          ${UI_DIM}(Windows Command Prompt)${UI_RST}"
            echo "  ${UI_PURPLE}4)${UI_RST} shell        ${UI_DIM}(Host Bash Subshell with active WINEPREFIX)${UI_RST}"
            echo "  ${UI_PURPLE}5)${UI_RST} winetricks   ${UI_DIM}(Winetricks GUI / Package Manager)${UI_RST}"
            echo "  ${UI_AMBER}6)${UI_RST} kill         ${UI_DIM}(Terminate locked / hung Wineserver)${UI_RST}"
            echo "  ${UI_RED}7)${UI_RST} clean        ${UI_DIM}(Backup Saves & Wipe Entire Wine Prefix)${UI_RST}"
            echo "  ${UI_CYAN}8)${UI_RST} Exit"
            echo
            local choice=""
            read -t 15 -r -p "Select action [1-8]: " choice || choice="8"
            case "$choice" in
                1) action="winecfg" ;;
                2) action="regedit" ;;
                3) action="cmd" ;;
                4) action="shell" ;;
                5) action="winetricks" ;;
                6) action="kill" ;;
                7) action="clean" ;;
                *) echo "[INFO] Operation canceled."; return 0 ;;
            esac
        else
            echo "Usage: gamectl pfx <game_dir> [winecfg|regedit|cmd|shell|kill|clean|winetricks] [args...]" >&2
            return 1
        fi
    fi

    case "$action" in
        kill)
            echo "[INFO] Sending force termination signal (wineserver -k) to prefix: $pfx_dir"
            if [ -d "$pfx_dir" ]; then
                if [ -n "$ws_bin" ]; then
                    WINEPREFIX="$pfx_dir" "$ws_bin" -k 2>/dev/null || true
                elif command -v wineserver >/dev/null 2>&1; then
                    WINEPREFIX="$pfx_dir" wineserver -k 2>/dev/null || true
                fi
            fi
            echo "[VERIFIED] Wineserver for prefix $pfx_dir has been stopped."
            return 0
            ;;
        clean)
            echo "[INFO] Starting Wine prefix cleanup: $pfx_dir"
            if [ ! -d "$pfx_dir" ]; then
                echo "[INFO] Prefix directory $pfx_dir does not exist, nothing to clean."
                return 0
            fi

            # 1. Create save snapshot backup
            backup_save "$game_dir" true || true

            # 2. Kill running wineserver
            if [ -n "$ws_bin" ]; then
                WINEPREFIX="$pfx_dir" "$ws_bin" -k 2>/dev/null || true
            elif command -v wineserver >/dev/null 2>&1; then
                WINEPREFIX="$pfx_dir" wineserver -k 2>/dev/null || true
            fi
            sleep 0.2

            # 3. Confirmation check
            local auto_yes=false
            for arg in "$@"; do
                if [ "$arg" = "-y" ] || [ "$arg" = "--yes" ]; then
                    auto_yes=true
                fi
            done

            if [ "$auto_yes" = false ] && [ -t 0 ]; then
                echo -n "[WARN] Wipe entire Wine prefix ($pfx_dir)? Registry and Wine configuration will be reset. [y/N]: "
                local confirm=""
                read -t 10 -r confirm || confirm="n"
                echo
                if [[ ! "$confirm" =~ ^[yY] ]]; then
                    echo "[INFO] Prefix cleanup canceled."
                    return 0
                fi
            fi

            # 4. Remove pfx folder safely
            rm -rf "$pfx_dir"
            echo "[VERIFIED] Wine prefix wiped successfully ($pfx_dir removed)."
            return 0
            ;;
        shell)
            echo "[INFO] Spawning interactive bash subshell inside prefix environment: $pfx_dir"
            echo "[INFO] Active environment: WINEPREFIX=$pfx_dir, RUNNER=$runner_bin"
            echo "[INFO] Type 'exit' to return to gamectl."
            (
                export WINEPREFIX="$pfx_dir"
                export GAMECTL_RUNNER="$runner_bin"
                if [[ "$runner_bin" =~ proton ]]; then
                    export STEAM_COMPAT_CLIENT_INSTALL_PATH="${STEAM_CLIENT_INSTALL_PATH:-$(get_steam_root 2>/dev/null || echo "$HOME/.local/share/Steam")}"
                    export STEAM_COMPAT_DATA_PATH="$game_dir"
                    export STEAM_COMPAT_APP_ID="$appid"
                    local p_bin_dir
                    p_bin_dir="$(dirname "$runner_bin")/files/bin"
                    [ -d "$p_bin_dir" ] && export PATH="$p_bin_dir:$PATH"
                fi
                cd "$game_dir" || true
                exec bash -i
            )
            return 0
            ;;
        winecfg|regedit|cmd)
            mkdir -p "$pfx_dir"
            echo "[INFO] Executing $action inside prefix: $pfx_dir (Runner: $runner_bin)..."
            local target_exec="$action"
            [ "$action" = "cmd" ] && target_exec="cmd.exe"

            local s_root
            s_root="$(get_steam_root 2>/dev/null || echo "$HOME/.local/share/Steam")"

            case "$runner_bin" in
                umu-run)
                    WINEPREFIX="$pfx_dir" GAMEID="$appid" umu-run "$target_exec" "$@"
                    ;;
                *proton*)
                    STEAM_COMPAT_CLIENT_INSTALL_PATH="${STEAM_CLIENT_INSTALL_PATH:-$s_root}" \
                    STEAM_COMPAT_DATA_PATH="$game_dir" \
                    STEAM_COMPAT_APP_ID="$appid" \
                    WINEPREFIX="$pfx_dir" \
                    "$runner_bin" run "$target_exec" "$@"
                    ;;
                *)
                    WINEPREFIX="$pfx_dir" "$runner_bin" "$target_exec" "$@"
                    ;;
            esac
            ;;
        winetricks)
            if ! command -v winetricks >/dev/null 2>&1; then
                echo "[ERROR] 'winetricks' binary not found on host system." >&2
                echo "[INFO] Install winetricks via your distribution package manager (e.g. pacman -S winetricks / apt install winetricks)." >&2
                return 1
            fi
            mkdir -p "$pfx_dir"
            echo "[INFO] Launching winetricks inside prefix: $pfx_dir"
            WINEPREFIX="$pfx_dir" winetricks "$@"
            ;;
        *)
            echo "[ERROR] Unknown prefix action: '$action'" >&2
            echo "Supported actions: winecfg, regedit, cmd, shell, kill, clean, winetricks" >&2
            return 1
            ;;
    esac
}

# Check if host GPU is Intel Haswell / 4th Gen Core (prone to Mesa GL threaded asset decompression crashes)
is_haswell_gpu() {
    local gpu_info=""
    if command -v lspci >/dev/null 2>&1; then
        gpu_info=$(lspci 2>/dev/null | grep -E "VGA|3D" || true)
    fi
    if [ -z "$gpu_info" ] && [ -d /sys/bus/pci/devices ]; then
        gpu_info=$(cat /sys/bus/pci/devices/*/uevent 2>/dev/null | grep -E "PCI_ID=" || true)
    fi
    if echo "$gpu_info" | grep -qi -E "Haswell|4th Gen Core"; then
        return 0
    fi
    return 1
}

# Dynamically detect host native display resolution via DRM / Wayland / X11
get_native_resolution() {
    local res=""
    # Priority 1: DRM kernel modes (direct & universal across all compositors/X11)
    for m_file in /sys/class/drm/card*-*/modes; do
        [ -f "$m_file" ] || continue
        local s_file="$(dirname "$m_file")/status"
        if [ -f "$s_file" ] && grep -q "^connected" "$s_file" 2>/dev/null; then
            local line
            line=$(head -n 1 "$m_file" 2>/dev/null | tr -d '[:space:]')
            if [[ "$line" =~ ^[0-9]+x[0-9]+$ ]]; then
                res="$line"
                break
            fi
        fi
    done

    # Priority 2: Hyprland monitor inspection
    if [ -z "$res" ] && command -v hyprctl >/dev/null 2>&1; then
        res=$(hyprctl monitors 2>/dev/null | grep -E '^[[:space:]]*[0-9]+x[0-9]+@' | head -n 1 | sed -E 's/.*([0-9]+x[0-9]+)@.*/\1/' || true)
    fi

    # Priority 3: X11 / Xwayland via xrandr
    if [ -z "$res" ] && command -v xrandr >/dev/null 2>&1; then
        res=$(xrandr --current 2>/dev/null | grep -E '\bconnected\b' | grep -o -E '[0-9]+x[0-9]+\+[0-9]+\+[0-9]+' | head -n 1 | cut -d'+' -f1 || true)
        [ -z "$res" ] && res=$(xrandr --current 2>/dev/null | grep -E '^[[:space:]]+[0-9]+x[0-9]+' | head -n 1 | awk '{print $1}' || true)
    fi

    # Fallback default
    if [[ ! "$res" =~ ^[0-9]+x[0-9]+$ ]]; then
        res="1920x1080"
    fi
    echo "$res"
}

# Dynamically calculate Gamescope display & FSR render arguments based on native resolution
get_default_gamescope_args() {
    local n_res
    n_res=$(get_native_resolution)
    local nw="${n_res%x*}"
    local nh="${n_res#*x}"

    local rw rh
    if [ "$nw" -ge 3840 ] && [ "$nh" -ge 2160 ]; then
        rw=2560; rh=1440
    elif [ "$nw" -ge 2560 ] && [ "$nh" -ge 1440 ]; then
        rw=1920; rh=1080
    elif [ "$nw" -eq 1920 ] && [ "$nh" -eq 1080 ]; then
        rw=1280; rh=720
    elif [ "$nw" -eq 1600 ] && [ "$nh" -eq 900 ]; then
        rw=1280; rh=720
    elif [ "$nw" -eq 1280 ] && [ "$nh" -eq 800 ]; then
        rw=960; rh=600
    else
        rw=$(( (nw * 2 / 3 + 1) / 2 * 2 ))
        rh=$(( (nh * 2 / 3 + 1) / 2 * 2 ))
    fi
    echo "-W $rw -H $rh -w $nw -h $nh -F fsr -f"
}

# Check if systemd user daemon and cgroups v2 scope unit execution is supported
check_systemd_scope_support() {
    if command -v systemd-run >/dev/null 2>&1 && command -v systemctl >/dev/null 2>&1; then
        if systemd-run --user --scope --quiet true 2>/dev/null; then
            return 0
        fi
    fi
    return 1
}

# Detect discrete secondary GPU vendor on hybrid systems (NVIDIA, AMD, Intel Arc)
detect_dgpu_vendor() {
    if [ -n "${GAMECTL_DGPU_VENDOR:-}" ]; then
        echo "$GAMECTL_DGPU_VENDOR"
        return 0
    fi

    local vga_count=0
    local vendors=()

    for dev in /sys/bus/pci/devices/*; do
        [ -f "$dev/class" ] || continue
        local pci_class
        pci_class=$(cat "$dev/class" 2>/dev/null || echo "")
        case "$pci_class" in
            0x0302*|0x030200*)
                # Secondary 3D controller (Optimized for 3D acceleration / dGPU)
                local v_id
                v_id=$(cat "$dev/vendor" 2>/dev/null || echo "")
                case "$v_id" in
                    0x10de) echo "nvidia"; return 0 ;;
                    0x1002) echo "amd"; return 0 ;;
                    0x8086) echo "intel"; return 0 ;;
                esac
                ;;
            0x0300*|0x030000*)
                vga_count=$((vga_count + 1))
                local v_id
                v_id=$(cat "$dev/vendor" 2>/dev/null || echo "")
                vendors+=("$v_id")
                ;;
        esac
    done

    # If multiple display controllers exist without a specific 0x0302 class device
    if [ "$vga_count" -gt 1 ]; then
        for v in "${vendors[@]}"; do
            if [ "$v" = "0x10de" ]; then
                echo "nvidia"
                return 0
            fi
        done
        local has_amd=false has_intel=false amd_count=0
        for v in "${vendors[@]}"; do
            [ "$v" = "0x1002" ] && { has_amd=true; amd_count=$((amd_count + 1)); }
            [ "$v" = "0x8086" ] && has_intel=true
        done
        if [ "$has_amd" = true ] && [ "$has_intel" = true ]; then
            echo "amd"
            return 0
        fi
        if [ "$amd_count" -gt 1 ]; then
            echo "amd"
            return 0
        fi
    fi

    echo "none"
    return 0
}

# Construct rootless Bubblewrap (bwrap) security sandbox argument array
build_sandbox_command() {
    local gdir="$1"
    declare -ga GAMECTL_SANDBOX_PREFIX=()

    if ! command -v bwrap >/dev/null 2>&1; then
        echo "[WARN] bubblewrap (bwrap) not found in PATH. Sandboxing skipped." >&2
        return 1
    fi

    local run_uid="${UID:-$(id -u)}"
    local runtime_dir="${XDG_RUNTIME_DIR:-/run/user/$run_uid}"
    local wayland_socket="${WAYLAND_DISPLAY:-wayland-0}"
    local xauth_file="${XAUTHORITY:-$HOME/.Xauthority}"

    GAMECTL_SANDBOX_PREFIX=(
        bwrap
        --ro-bind /usr /usr
        --ro-bind-try /lib /lib
        --ro-bind-try /lib64 /lib64
        --ro-bind-try /bin /bin
        --ro-bind-try /sbin /sbin
        --ro-bind-try /etc /etc
        --proc /proc
        --dev /dev
        --ro-bind /sys /sys
        --tmpfs /tmp
        --ro-bind-try /tmp/.X11-unix /tmp/.X11-unix
        --tmpfs /run
        --tmpfs "/run/user/$run_uid"
        --ro-bind-try "$runtime_dir/wayland-0" "$runtime_dir/wayland-0"
        --ro-bind-try "$runtime_dir/$wayland_socket" "$runtime_dir/$wayland_socket"
        --bind-try "$runtime_dir/pipewire-0" "$runtime_dir/pipewire-0"
        --bind-try "$runtime_dir/pulse" "$runtime_dir/pulse"
        --bind-try "$runtime_dir/gamectl-$run_uid" "$runtime_dir/gamectl-$run_uid"
        --tmpfs "$HOME"
        --ro-bind-try "$xauth_file" "$xauth_file"
        --bind-try "$HOME/.config/gamectl" "$HOME/.config/gamectl"
        --ro-bind-try "$HOME/.local/share/Steam" "$HOME/.local/share/Steam"
        --ro-bind-try "$HOME/.local/share/gbe-fork" "$HOME/.local/share/gbe-fork"
        --ro-bind-try "$HOME/.steam" "$HOME/.steam"
        --bind-try "$HOME/.local/share/vulkan" "$HOME/.local/share/vulkan"
        --bind "$gdir" "$gdir"
        --chdir "$gdir"
        --unshare-user
        --unshare-ipc
        --unshare-pid
        --die-with-parent
    )
    return 0
}

# Resolve and build wrapper prefix command array (gamemoderun, mangohud, gamescope)
build_wrapper_command() {
    local gdir="$1"
    shift || true
    local opt_gamemode="" opt_hud="" opt_gamescope="" opt_fsr="" opt_systemd_scope="" opt_prime="" opt_sandbox=""
    local remaining_args=()

    while [ $# -gt 0 ]; do
        case "$1" in
            --hud|--mangohud) opt_hud=1; shift ;;
            --no-hud|--no-mangohud) opt_hud=0; shift ;;
            --gamemode) opt_gamemode=1; shift ;;
            --no-gamemode) opt_gamemode=0; shift ;;
            --gamescope) opt_gamescope=1; shift ;;
            --no-gamescope) opt_gamescope=0; shift ;;
            --fsr) opt_fsr=1; opt_gamescope=1; shift ;;
            --no-fsr) opt_fsr=0; shift ;;
            --glthread) opt_glthread=1; shift ;;
            --no-glthread) opt_glthread=0; shift ;;
            --scope|--systemd-scope) opt_systemd_scope=1; shift ;;
            --no-scope|--no-systemd-scope) opt_systemd_scope=0; shift ;;
            --prime) opt_prime=1; shift ;;
            --no-prime) opt_prime=0; shift ;;
            --sandbox) opt_sandbox=1; shift ;;
            --no-sandbox) opt_sandbox=0; shift ;;
            --) shift; remaining_args+=("$@"); break ;;
            *) remaining_args+=("$1"); shift ;;
        esac
    done

    # 1. Base defaults
    local use_gm=0 use_hud=0 use_scope=0 use_fsr=0 use_glthread=0 use_systemd_scope="" use_prime=0 use_sandbox=0
    local gscope_args
    gscope_args=$(get_default_gamescope_args)

    # 2. Global configuration (~/.config/gamectl/wrappers)
    if [ -f "$HOME/.config/gamectl/wrappers" ]; then
        while IFS='=' read -r k v || [ -n "$k" ]; do
            k=$(echo "$k" | tr -d '[:space:]')
            v=$(echo "$v" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//')
            [[ "$k" =~ ^# ]] && continue
            case "$k" in
                gamemode) use_gm="$v" ;;
                hud|mangohud) use_hud="$v" ;;
                gamescope) use_scope="$v" ;;
                fsr) use_fsr="$v" ;;
                glthread|mesa_glthread) use_glthread="$v" ;;
                scope|systemd_scope) use_systemd_scope="$v" ;;
                prime|dgpu) use_prime="$v" ;;
                sandbox) use_sandbox="$v" ;;
                gamescope_args) gscope_args="$v" ;;
            esac
        done < "$HOME/.config/gamectl/wrappers"
    fi

    # 3. Per-game override ($gdir/.wrappers)
    if [ -n "$gdir" ] && [ -f "$gdir/.wrappers" ]; then
        while IFS='=' read -r k v || [ -n "$k" ]; do
            k=$(echo "$k" | tr -d '[:space:]')
            v=$(echo "$v" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//')
            [[ "$k" =~ ^# ]] && continue
            case "$k" in
                gamemode) use_gm="$v" ;;
                hud|mangohud) use_hud="$v" ;;
                gamescope) use_scope="$v" ;;
                fsr) use_fsr="$v" ;;
                glthread|mesa_glthread) use_glthread="$v" ;;
                scope|systemd_scope) use_systemd_scope="$v" ;;
                prime|dgpu) use_prime="$v" ;;
                sandbox) use_sandbox="$v" ;;
                gamescope_args) gscope_args="$v" ;;
            esac
        done < "$gdir/.wrappers"
    fi

    # 4. Environment variable overrides
    [ -n "${GAMECTL_GAMEMODE:-}" ] && use_gm="$GAMECTL_GAMEMODE"
    [ -n "${GAMECTL_HUD:-${GAMECTL_MANGOHUD:-}}" ] && use_hud="${GAMECTL_HUD:-$GAMECTL_MANGOHUD}"
    [ -n "${GAMECTL_GAMESCOPE:-}" ] && use_scope="$GAMECTL_GAMESCOPE"
    [ -n "${GAMECTL_FSR:-}" ] && use_fsr="$GAMECTL_FSR"
    [ -n "${GAMECTL_GLTHREAD:-}" ] && use_glthread="$GAMECTL_GLTHREAD"
    [ -n "${GAMECTL_SCOPE:-${GAMECTL_SYSTEMD_SCOPE:-}}" ] && use_systemd_scope="${GAMECTL_SCOPE:-$GAMECTL_SYSTEMD_SCOPE}"
    [ -n "${GAMECTL_PRIME:-}" ] && use_prime="$GAMECTL_PRIME"
    [ -n "${GAMECTL_SANDBOX:-}" ] && use_sandbox="$GAMECTL_SANDBOX"
    [ -n "${GAMECTL_GAMESCOPE_ARGS:-}" ] && gscope_args="$GAMECTL_GAMESCOPE_ARGS"

    # 5. CLI flag overrides
    [ -n "$opt_gamemode" ] && use_gm="$opt_gamemode"
    [ -n "$opt_hud" ] && use_hud="$opt_hud"
    [ -n "$opt_gamescope" ] && use_scope="$opt_gamescope"
    [ -n "$opt_fsr" ] && use_fsr="$opt_fsr"
    [ -n "${opt_glthread:-}" ] && use_glthread="$opt_glthread"
    [ -n "${opt_systemd_scope:-}" ] && use_systemd_scope="$opt_systemd_scope"
    [ -n "$opt_prime" ] && use_prime="$opt_prime"
    [ -n "$opt_sandbox" ] && use_sandbox="$opt_sandbox"

    if [ -z "${use_systemd_scope:-}" ]; then
        if check_systemd_scope_support; then
            use_systemd_scope=1
        else
            use_systemd_scope=0
        fi
    fi

    local dgpu_vendor="none"
    if [ "$use_prime" = "1" ]; then
        dgpu_vendor=$(detect_dgpu_vendor)
        if [ "$dgpu_vendor" = "none" ]; then
            echo "[WARN] PRIME offloading requested (--prime) but no secondary dGPU detected." >&2
        fi
    fi

    declare -ga GAMECTL_SANDBOX_PREFIX=()
    if [ "$use_sandbox" = "1" ]; then
        build_sandbox_command "$gdir" || use_sandbox=0
    fi

    GAMECTL_ACTIVE_GLTHREAD="$use_glthread"
    GAMECTL_ACTIVE_SYSTEMD_SCOPE="$use_systemd_scope"
    GAMECTL_ACTIVE_PRIME="$use_prime"
    GAMECTL_ACTIVE_PRIME_VENDOR="$dgpu_vendor"
    GAMECTL_ACTIVE_SANDBOX="$use_sandbox"

    local prefix=()
    if [ "$use_gm" = "1" ]; then
        if command -v gamemoderun >/dev/null 2>&1; then
            prefix+=("gamemoderun")
        else
            echo "[WARN] gamemoderun is enabled but binary not found in PATH." >&2
        fi
    fi

    if [ "$use_hud" = "1" ]; then
        if command -v mangohud >/dev/null 2>&1; then
            prefix+=("mangohud")
        else
            echo "[WARN] mangohud is enabled but binary not found in PATH." >&2
        fi
    fi

    if [ "$use_scope" = "1" ] || [ "$use_fsr" = "1" ]; then
        if command -v gamescope >/dev/null 2>&1; then
            prefix+=("gamescope")
            local active_args="$gscope_args"
            if [ "$use_fsr" = "1" ] && [[ ! "$active_args" =~ (-F|fsr|-U) ]]; then
                active_args="-F fsr $active_args"
            elif [ "$use_fsr" = "0" ]; then
                active_args=$(echo "$active_args" | sed -E 's/-F[[:space:]]+fsr//g' | xargs)
            fi
            if [ -n "$active_args" ]; then
                read -r -a parsed_args <<< "$active_args"
                prefix+=("${parsed_args[@]}")
            fi
            prefix+=("--")
        else
            echo "[WARN] gamescope is enabled but binary not found in PATH." >&2
        fi
    fi

    GAMECTL_WRAPPER_PREFIX=("${prefix[@]}")
    GAMECTL_REMAINING_ARGS=("${remaining_args[@]}")
}

# Interactive wrapper configuration for a game or global defaults
configure_wrappers() {
    local gdir="$1"
    local title="${2:-$(basename "$gdir")}"
    local w_file="$gdir/.wrappers"

    local gm=0 hud=0 scope=0 fsr=0 glt=0
    local gscope_args
    gscope_args=$(get_default_gamescope_args)
    if [ -f "$HOME/.config/gamectl/wrappers" ]; then
        grep -q "^gamemode=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && gm=1
        grep -q -E "^(hud|mangohud)=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && hud=1
        grep -q "^gamescope=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && scope=1
        grep -q "^fsr=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && fsr=1
        grep -q -E "^(glthread|mesa_glthread)=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && glt=1
        local g_custom
        g_custom=$(grep -E '^[[:space:]]*gamescope_args[[:space:]]*=' "$HOME/.config/gamectl/wrappers" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*gamescope_args[[:space:]]*=[[:space:]]*//' | tr -d '\r')
        [ -n "$g_custom" ] && gscope_args="$g_custom"
    fi
    if [ -f "$w_file" ]; then
        grep -q "^gamemode=1" "$w_file" 2>/dev/null && gm=1
        grep -q "^gamemode=0" "$w_file" 2>/dev/null && gm=0
        grep -q -E "^(hud|mangohud)=1" "$w_file" 2>/dev/null && hud=1
        grep -q -E "^(hud|mangohud)=0" "$w_file" 2>/dev/null && hud=0
        grep -q "^gamescope=1" "$w_file" 2>/dev/null && scope=1
        grep -q "^gamescope=0" "$w_file" 2>/dev/null && scope=0
        grep -q "^fsr=1" "$w_file" 2>/dev/null && fsr=1
        grep -q "^fsr=0" "$w_file" 2>/dev/null && fsr=0
        grep -q -E "^(glthread|mesa_glthread)=1" "$w_file" 2>/dev/null && glt=1
        grep -q -E "^(glthread|mesa_glthread)=0" "$w_file" 2>/dev/null && glt=0
        local w_custom
        w_custom=$(grep -E '^[[:space:]]*gamescope_args[[:space:]]*=' "$w_file" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*gamescope_args[[:space:]]*=[[:space:]]*//' | tr -d '\r')
        [ -n "$w_custom" ] && gscope_args="$w_custom"
    fi

    while true; do
        local b_gm="${UI_DIM}[OFF]${UI_RST}" b_hud="${UI_DIM}[OFF]${UI_RST}"
        local b_scope="${UI_DIM}[OFF]${UI_RST}" b_fsr="${UI_DIM}[OFF]${UI_RST}" b_glt="${UI_DIM}[OFF]${UI_RST}"
        [ "$gm" = 1 ] && b_gm="${UI_GREEN}[ACTIVE]${UI_RST}"
        [ "$hud" = 1 ] && b_hud="${UI_GREEN}[ACTIVE]${UI_RST}"
        [ "$scope" = 1 ] && b_scope="${UI_GREEN}[ACTIVE]${UI_RST}"
        [ "$fsr" = 1 ] && b_fsr="${UI_GREEN}[ACTIVE]${UI_RST}"
        [ "$glt" = 1 ] && b_glt="${UI_GREEN}[ACTIVE]${UI_RST}"

        local h_gm="${UI_DIM}[N/A]${UI_RST}" h_hud="${UI_DIM}[N/A]${UI_RST}" h_scope="${UI_DIM}[N/A]${UI_RST}"
        command -v gamemoderun >/dev/null 2>&1 && h_gm="${UI_GREEN}[READY]${UI_RST}"
        command -v mangohud >/dev/null 2>&1 && h_hud="${UI_GREEN}[READY]${UI_RST}"
        command -v gamescope >/dev/null 2>&1 && h_scope="${UI_GREEN}[READY]${UI_RST}"

        local glt_hint="${UI_DIM}(Opt-in Performance)${UI_RST}"
        is_haswell_gpu && glt_hint="${UI_AMBER}(Intel Haswell: Keep OFF)${UI_RST}"

        clear
        echo "${UI_BOX}╭─ CONFIGURE RUNTIME WRAPPERS: ${UI_BOLD}${title}${UI_RST}${UI_BOX} ────────────╮${UI_RST}"
        echo "│ ${UI_CYAN}Host Tools${UI_RST}: GameMode $h_gm • MangoHud $h_hud • Gamescope $h_scope"
        echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
        echo "  ${UI_PURPLE}1)${UI_RST} GameMode (gamemoderun)       : $b_gm"
        echo "  ${UI_PURPLE}2)${UI_RST} MangoHud (FPS & Telemetry)   : $b_hud"
        echo "  ${UI_PURPLE}3)${UI_RST} Gamescope (Isolated Window)  : $b_scope"
        echo "  ${UI_PURPLE}4)${UI_RST} Gamescope FSR Upscaling      : $b_fsr"
        echo "  ${UI_PURPLE}5)${UI_RST} Mesa GL Threading (mesa_gl)  : $b_glt $glt_hint"
        echo "${UI_BOX}  ─────────────────────────────────────────────────────────────${UI_RST}"
        echo "  ${UI_CYAN}6)${UI_RST} Preset: Balanced Performance (GameMode + MangoHud)"
        echo "  ${UI_CYAN}7)${UI_RST} Preset: Handheld / FSR (GameMode + MangoHud + Gamescope FSR)"
        echo "  ${UI_CYAN}8)${UI_RST} Reset: Safe Defaults (All Disabled)"
        echo "  ${UI_GREEN}9)${UI_RST} Save & Return to Library"
        echo "  ${UI_RED}0)${UI_RST} Cancel / Discard Changes"
        echo
        read -r -p "Select option [0-9]: " opt
        case "$opt" in
            1) gm=$((1 - gm)) ;;
            2) hud=$((1 - hud)) ;;
            3) scope=$((1 - scope)) ;;
            4) fsr=$((1 - fsr)); [ "$fsr" = 1 ] && scope=1 ;;
            5) glt=$((1 - glt)) ;;
            6) gm=1; hud=1; scope=0; fsr=0; glt=0 ;;
            7) gm=1; hud=1; scope=1; fsr=1; glt=0 ;;
            8) gm=0; hud=0; scope=0; fsr=0; glt=0 ;;
            9)
                cat <<EOF > "$w_file"
# Runtime wrappers for $title
gamemode=$gm
hud=$hud
gamescope=$scope
fsr=$fsr
glthread=$glt
gamescope_args=$gscope_args
EOF
                echo "[VERIFIED] Wrapper configuration saved to: $w_file"
                sleep 0.8
                break
                ;;
            0|q|Q)
                return 0
                ;;
            *)
                ;;
        esac
    done
}

# Global Configuration Manager TUI
configure_global() {
    mkdir -p "$HOME/.config/gamectl"

    while true; do
        clear
        echo "${UI_BOX}╭─ GLOBAL SETTINGS (~/.config/gamectl/) ──────────────────────╮${UI_RST}"
        echo "│ ${UI_CYAN}Default Persona, Runtime Wrappers, Libraries & Companion${UI_RST}"
        echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
        local p_name="Player" p_id=""
        if [ -f "$HOME/.config/gamectl/persona" ]; then
            p_name=$(grep -E '^[[:space:]]*account_name[[:space:]]*=' "$HOME/.config/gamectl/persona" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_name[[:space:]]*=[[:space:]]*//' | tr -d '\r')
            p_id=$(grep -E '^[[:space:]]*account_steamid[[:space:]]*=' "$HOME/.config/gamectl/persona" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_steamid[[:space:]]*=[[:space:]]*//' | tr -d '\r')
        fi
        [ -z "$p_name" ] && p_name="${USER:-Player}"

        local w_desc="Default (All Disabled)"
        if [ -f "$HOME/.config/gamectl/wrappers" ]; then
            local act_w=()
            grep -q "^gamemode=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && act_w+=("GameMode")
            grep -q -E "^(hud|mangohud)=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && act_w+=("MangoHud")
            grep -q "^gamescope=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && act_w+=("Gamescope")
            grep -q "^fsr=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && act_w+=("FSR")
            grep -q -E "^(glthread|mesa_glthread)=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && act_w+=("MesaGL")
            [ ${#act_w[@]} -gt 0 ] && w_desc="${act_w[*]}"
        fi

        local lib_count=0
        [ -f "$HOME/.config/gamectl/libraries" ] && lib_count=$(grep -v -E '^[[:space:]]*(#|$)' "$HOME/.config/gamectl/libraries" 2>/dev/null | wc -l || echo 0)

        local r_host="Not Configured"
        if [ -f "$HOME/.config/gamectl/remote_host" ]; then
            r_host=$(head -n 1 "$HOME/.config/gamectl/remote_host" 2>/dev/null | tr -d '[:space:]')
            [ -z "$r_host" ] && r_host="Not Configured"
        fi

        echo "  ${UI_PURPLE}1)${UI_RST} Global LAN Persona     : ${UI_BOLD}$p_name${UI_RST} ${UI_DIM}(SteamID: ${p_id:-Auto})${UI_RST}"
        echo "  ${UI_PURPLE}2)${UI_RST} Default Wrappers       : ${UI_BOLD}$w_desc${UI_RST}"
        echo "  ${UI_PURPLE}3)${UI_RST} Custom Game Libraries  : ${UI_BOLD}$lib_count${UI_RST} ${UI_DIM}paths registered${UI_RST}"
        echo "  ${UI_PURPLE}4)${UI_RST} Remote Companion Host  : ${UI_BOLD}$r_host${UI_RST}"
        echo "${UI_BOX}  ─────────────────────────────────────────────────────────────${UI_RST}"
        echo "  ${UI_GREEN}5)${UI_RST} Return to Master Dashboard Hub"
        echo
        read -r -p "Select option [1-5]: " cfg_opt

        case "$cfg_opt" in
            1)
                echo
                echo "${UI_BOX}╭─ GLOBAL LAN PERSONA SETTINGS ───────────────────────────────╮${UI_RST}"
                echo -n "  Player Name [$p_name]: "; read -r new_name
                [ -n "$new_name" ] && p_name="$new_name"
                echo -n "  SteamID64 [${p_id:-Auto}] ('gen' for random ID): "; read -r new_id
                if [ "$new_id" = "gen" ]; then
                    p_id=$(generate_steamid64)
                    echo "  [INFO] Generated SteamID64: $p_id"
                elif [ -n "$new_id" ]; then
                    p_id="$new_id"
                fi
                cat <<EOF > "$HOME/.config/gamectl/persona"
[user::general]
account_name=$p_name
account_steamid=$p_id
language=english
EOF
                echo "  ${UI_GREEN}[SUCCESS] Persona saved: $p_name | $p_id${UI_RST}"
                sleep 0.8
                ;;
            2)
                local gm=0 hud=0 scope=0 fsr=0 glt=0
                local gscope_args
                gscope_args=$(get_default_gamescope_args)
                if [ -f "$HOME/.config/gamectl/wrappers" ]; then
                    grep -q "^gamemode=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && gm=1
                    grep -q -E "^(hud|mangohud)=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && hud=1
                    grep -q "^gamescope=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && scope=1
                    grep -q "^fsr=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && fsr=1
                    grep -q -E "^(glthread|mesa_glthread)=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && glt=1
                    local g_custom
                    g_custom=$(grep -E '^[[:space:]]*gamescope_args[[:space:]]*=' "$HOME/.config/gamectl/wrappers" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*gamescope_args[[:space:]]*=[[:space:]]*//' | tr -d '\r')
                    [ -n "$g_custom" ] && gscope_args="$g_custom"
                fi
                while true; do
                    local b_gm="${UI_DIM}[OFF]${UI_RST}" b_hud="${UI_DIM}[OFF]${UI_RST}"
                    local b_scope="${UI_DIM}[OFF]${UI_RST}" b_fsr="${UI_DIM}[OFF]${UI_RST}" b_glt="${UI_DIM}[OFF]${UI_RST}"
                    [ "$gm" = 1 ] && b_gm="${UI_GREEN}[ACTIVE]${UI_RST}"
                    [ "$hud" = 1 ] && b_hud="${UI_GREEN}[ACTIVE]${UI_RST}"
                    [ "$scope" = 1 ] && b_scope="${UI_GREEN}[ACTIVE]${UI_RST}"
                    [ "$fsr" = 1 ] && b_fsr="${UI_GREEN}[ACTIVE]${UI_RST}"
                    [ "$glt" = 1 ] && b_glt="${UI_GREEN}[ACTIVE]${UI_RST}"

                    local glt_hint="${UI_DIM}(Opt-in Performance)${UI_RST}"
                    is_haswell_gpu && glt_hint="${UI_AMBER}(Intel Haswell: Keep OFF)${UI_RST}"

                    clear
                    echo "${UI_BOX}╭─ DEFAULT GLOBAL RUNTIME WRAPPERS ───────────────────────────╮${UI_RST}"
                    echo "│ ${UI_CYAN}These wrappers apply to all games unless overridden per-game${UI_RST}"
                    echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
                    echo "  ${UI_PURPLE}1)${UI_RST} GameMode (gamemoderun)       : $b_gm"
                    echo "  ${UI_PURPLE}2)${UI_RST} MangoHud (FPS & Telemetry)   : $b_hud"
                    echo "  ${UI_PURPLE}3)${UI_RST} Gamescope (Isolated Window)  : $b_scope"
                    echo "  ${UI_PURPLE}4)${UI_RST} Gamescope FSR Upscaling      : $b_fsr"
                    echo "  ${UI_PURPLE}5)${UI_RST} Mesa GL Threading (mesa_gl)  : $b_glt $glt_hint"
                    echo "${UI_BOX}  ─────────────────────────────────────────────────────────────${UI_RST}"
                    echo "  ${UI_CYAN}6)${UI_RST} Preset: Balanced Performance (GameMode + MangoHud)"
                    echo "  ${UI_CYAN}7)${UI_RST} Preset: Handheld / FSR (GameMode + MangoHud + Gamescope FSR)"
                    echo "  ${UI_CYAN}8)${UI_RST} Reset: Safe Defaults (All Disabled)"
                    echo "  ${UI_GREEN}9)${UI_RST} Save & Return"
                    echo
                    read -r -p "Select option [1-9]: " w_opt
                    case "$w_opt" in
                        1) gm=$((1 - gm)) ;;
                        2) hud=$((1 - hud)) ;;
                        3) scope=$((1 - scope)) ;;
                        4) fsr=$((1 - fsr)); [ "$fsr" = 1 ] && scope=1 ;;
                        5) glt=$((1 - glt)) ;;
                        6) gm=1; hud=1; scope=0; fsr=0; glt=0 ;;
                        7) gm=1; hud=1; scope=1; fsr=1; glt=0 ;;
                        8) gm=0; hud=0; scope=0; fsr=0; glt=0 ;;
                        9)
                            cat <<EOF > "$HOME/.config/gamectl/wrappers"
gamemode=$gm
hud=$hud
gamescope=$scope
fsr=$fsr
glthread=$glt
gamescope_args=$gscope_args
EOF
                            echo "  ${UI_GREEN}[SUCCESS] Global wrappers saved.${UI_RST}"
                            sleep 0.8
                            break
                            ;;
                        *) break ;;
                    esac
                done
                ;;
            3)
                clear
                echo "${UI_BOX}╭─ CUSTOM GAME LIBRARIES (~/.config/gamectl/libraries) ───────╮${UI_RST}"
                echo "│ ${UI_CYAN}Direct scan paths for game binaries and appmanifests${UI_RST}"
                echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
                [ -f "$HOME/.config/gamectl/libraries" ] && grep -v -E '^[[:space:]]*(#|$)' "$HOME/.config/gamectl/libraries" 2>/dev/null | nl -w2 -s'. ' || echo "  ${UI_DIM}(No custom libraries registered)${UI_RST}"
                echo "${UI_BOX}  ─────────────────────────────────────────────────────────────${UI_RST}"
                echo "  ${UI_CYAN}1)${UI_RST} Add Directory | ${UI_CYAN}2)${UI_RST} Remove Directory | ${UI_CYAN}3)${UI_RST} Back"
                read -r -p "Select option [1-3]: " lib_opt
                case "$lib_opt" in
                    1)
                        echo -n "  Enter path (e.g. ~/Games): "; read -r new_path
                        if [ -n "$new_path" ]; then
                            new_path="${new_path/#\~/$HOME}"
                            echo "$new_path" >> "$HOME/.config/gamectl/libraries"
                            echo "  ${UI_GREEN}[SUCCESS] Path '$new_path' added.${UI_RST}"
                        fi
                        read -r -p "Press [ENTER] to continue..."
                        ;;
                    2)
                        if [ -f "$HOME/.config/gamectl/libraries" ]; then
                            echo -n "  Enter line number to remove: "; read -r del_num
                            if [[ "$del_num" =~ ^[0-9]+$ ]]; then
                                local target_line
                                target_line=$(grep -v -E '^[[:space:]]*(#|$)' "$HOME/.config/gamectl/libraries" 2>/dev/null | sed -n "${del_num}p")
                                if [ -n "$target_line" ]; then
                                    grep -v -F "$target_line" "$HOME/.config/gamectl/libraries" > "$HOME/.config/gamectl/libraries.tmp" && mv "$HOME/.config/gamectl/libraries.tmp" "$HOME/.config/gamectl/libraries"
                                    echo "  ${UI_GREEN}[SUCCESS] '$target_line' removed.${UI_RST}"
                                fi
                            fi
                        fi
                        read -r -p "Press [ENTER] to continue..."
                        ;;
                    *) ;;
                esac
                ;;
            4)
                echo
                echo "${UI_BOX}╭─ REMOTE COMPANION HOST (~/.config/gamectl/remote_host) ─────╮${UI_RST}"
                echo "│ ${UI_CYAN}Target SSH server for savegame synchronization${UI_RST}"
                echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
                echo "  Current Host: ${UI_BOLD}$r_host${UI_RST}"
                echo -n "  Enter new hostname or SSH alias ('-' to clear): "; read -r new_rhost
                if [ "$new_rhost" = "-" ]; then
                    rm -f "$HOME/.config/gamectl/remote_host"
                    echo "  [INFO] Remote host configuration cleared."
                elif [ -n "$new_rhost" ]; then
                    echo "$new_rhost" > "$HOME/.config/gamectl/remote_host"
                    echo "  ${UI_GREEN}[SUCCESS] Remote host '$new_rhost' saved.${UI_RST}"
                    echo -n "  Test SSH connectivity to '$new_rhost'? [y/N]: "; read -r test_ssh
                    if [[ "$test_ssh" =~ ^[yY] ]]; then
                        echo "  [INFO] Testing SSH connection to $new_rhost (3s timeout)..."
                        if ssh -q -o BatchMode=yes -o ConnectTimeout=3 "$new_rhost" exit 2>/dev/null; then
                            echo "  ${UI_GREEN}[VERIFIED] SSH connection successful!${UI_RST}"
                        else
                            echo "  ${UI_AMBER}[WARN] Host did not respond with public key auth. Ensure host is in ~/.ssh/config.${UI_RST}"
                        fi
                    fi
                fi
                read -r -p "Press [ENTER] to continue..."
                ;;
            *)
                break
                ;;
        esac
    done
}


# --- [MODULE] src/runners/50_launcher.sh ---
# Interactive Live HUD for running game process
game_controller_hud() {
    local game_pid="$1"
    local title="$2"
    local log_file="$3"
    local gdir="$4"
    local gbin="$5"
    local info_file="$6"
    local run_type="$7"

    while true; do
        local is_alive=0
        if kill -0 "$game_pid" 2>/dev/null; then
            is_alive=1
        fi

        clear
        echo "${UI_BOX}╭─ GAME CONTROLLER HUD ───────────────────────────────────────╮${UI_RST}"
        echo "│ ${UI_CYAN}Target Game ${UI_RST}: ${UI_BOLD}$title${UI_RST}"
        echo "│ ${UI_CYAN}Process PID ${UI_RST}: ${UI_BOLD}$game_pid${UI_RST} ${UI_DIM}($run_type)${UI_RST}"
        if [ "$is_alive" -eq 1 ]; then
            echo "│ ${UI_CYAN}Status      ${UI_RST}: ${UI_GREEN}[RUNNING]${UI_RST} ${UI_DIM}(Active window on desktop display)${UI_RST}"
        else
            echo "│ ${UI_CYAN}Status      ${UI_RST}: ${UI_ICE}[TERMINATED / EXITED]${UI_RST}"
        fi
        echo "│ ${UI_CYAN}Log Stream  ${UI_RST}: ${UI_DIM}$log_file${UI_RST}"
        echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"

        if [ "$is_alive" -eq 1 ]; then
            echo "  ${UI_PURPLE}1)${UI_RST} Return to Game Library ${UI_DIM}(Game continues running in background)${UI_RST}"
            echo "  ${UI_PURPLE}2)${UI_RST} Return to Master Dashboard ${UI_DIM}(Game continues running in background)${UI_RST}"
            echo "  ${UI_PURPLE}3)${UI_RST} Live Game Log Stream ${UI_DIM}(tail -f)${UI_RST}"
            echo "  ${UI_AMBER}4)${UI_RST} Stop Game ${UI_DIM}(Graceful Shutdown / SIGTERM)${UI_RST}"
            echo "  ${UI_RED}5)${UI_RST} Force Kill Game ${UI_DIM}(Emergency Teardown / SIGKILL)${UI_RST}"
            echo
            read -t 30 -r -p "Select action [1-5]: " hud_opt || hud_opt="1"

            case "$hud_opt" in
                1)
                    return 0
                    ;;
                2)
                    return 10
                    ;;
                3)
                    clear
                    echo "${UI_BOX}╭─ LIVE LOG STREAM: $title (PID: $game_pid) ─────────────╮${UI_RST}"
                    echo "│ ${UI_CYAN}Press any key to return to Game Controller Menu               ${UI_RST}"
                    echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
                    tail -n 25 "$log_file" 2>/dev/null || true
                    echo "${UI_DIM}─── Live Output (press any key to stop) ───────────────────────${UI_RST}"
                    local t_pid=""
                    tail -f "$log_file" 2>/dev/null &
                    t_pid=$!
                    ( read -r -s -n 1 </dev/tty || true ) 2>/dev/null
                    kill "$t_pid" 2>/dev/null || true
                    wait "$t_pid" 2>/dev/null || true
                    ;;
                4)
                    local s_unit=""
                    [ -f "$info_file" ] && s_unit=$(grep -E '^SCOPE_UNIT=' "$info_file" 2>/dev/null | cut -d'=' -f2- || true)
                    echo "  [INFO] Sending SIGTERM signal to process PID $game_pid..."
                    if [ -n "$s_unit" ]; then
                        systemctl --user stop "$s_unit.scope" 2>/dev/null || true
                    fi
                    kill "$game_pid" 2>/dev/null || true
                    local wait_cnt=0
                    while kill -0 "$game_pid" 2>/dev/null && [ "$wait_cnt" -lt 6 ]; do
                        sleep 0.3
                        wait_cnt=$((wait_cnt + 1))
                    done
                    if [ -d "$gdir/pfx" ]; then
                        local ws_bin
                        ws_bin="$(get_wineserver_bin "$(find_runner "$gdir" 2>/dev/null || true)" 2>/dev/null || true)"
                        [ -n "$ws_bin" ] && WINEPREFIX="$gdir/pfx" "$ws_bin" -w 2>/dev/null || true # wineserver -w
                    fi
                    if ! kill -0 "$game_pid" 2>/dev/null; then
                        echo "  ${UI_GREEN}[SUCCESS] Game '$title' (PID $game_pid) terminated gracefully.${UI_RST}"
                        rm -f "$info_file" 2>/dev/null || true
                    else
                        echo "  ${UI_AMBER}[WARN] Process still running. You can select option 5 (Force Kill).${UI_RST}"
                    fi
                    sleep 0.8
                    ;;
                5)
                    local s_unit=""
                    [ -f "$info_file" ] && s_unit=$(grep -E '^SCOPE_UNIT=' "$info_file" 2>/dev/null | cut -d'=' -f2- || true)
                    echo "  [INFO] Sending SIGKILL signal to process PID $game_pid..."
                    if [ -n "$s_unit" ]; then
                        systemctl --user kill -s SIGKILL "$s_unit.scope" 2>/dev/null || true
                        systemctl --user stop "$s_unit.scope" 2>/dev/null || true
                    fi
                    kill -9 "$game_pid" 2>/dev/null || true
                    if [ -d "$gdir/pfx" ]; then
                        # Remediation DEFECT-02: Force terminate stuck wineserver daemon and release lockfiles
                        local ws_bin
                        ws_bin="$(get_wineserver_bin "$(find_runner "$gdir" 2>/dev/null || true)" 2>/dev/null || true)"
                        [ -n "$ws_bin" ] && WINEPREFIX="$gdir/pfx" "$ws_bin" -k 2>/dev/null || true # wineserver -k
                    fi
                    sleep 0.3
                    echo "  ${UI_GREEN}[SUCCESS] Game '$title' (PID $game_pid) force-killed.${UI_RST}"
                    rm -f "$info_file" 2>/dev/null || true
                    sleep 0.8
                    ;;
                *)
                    ;;
            esac
        else
            echo "  ${UI_PURPLE}1)${UI_RST} Return to Game Library"
            echo "  ${UI_PURPLE}2)${UI_RST} Return to Master Dashboard"
            echo "  ${UI_PURPLE}3)${UI_RST} View Recent Logs (tail -n 25)"
            echo
            read -t 30 -r -p "Select action [1-3]: " hud_opt || hud_opt="1"
            case "$hud_opt" in
                1) return 0 ;;
                2) return 10 ;;
                3)
                    echo
                    echo "${UI_DIM}──────────────────────────────────────────${UI_RST}"
                    tail -n 25 "$log_file" 2>/dev/null || echo "[No logs available]"
                    echo "${UI_DIM}──────────────────────────────────────────${UI_RST}"
                    read -t 15 -r -p "Press [ENTER] to return..." || true
                    ;;
                *) return 0 ;;
            esac
        fi
    done
}

# Setup P2P Multiplayer Compatibility Layer, mod DLL overrides & Spacewar (AppID 480) entitlement
setup_onlinefix() {
    local gdir="${1:-}"
    shift || true
    local auto_yes=false
    while [ $# -gt 0 ]; do
        case "$1" in
            -y|--yes|--non-interactive) auto_yes=true; shift ;;
            *) shift ;;
        esac
    done

    if [ -z "$gdir" ] || [ ! -d "$gdir" ]; then
        echo "[ERROR] Game directory not found: $gdir" >&2
        return 1
    fi
    gdir="$(cd "$gdir" && pwd)"

    echo "[INFO] Running OnlineFix setup and Spacewar entitlement audit in: $gdir..."

    # 1. Discover OnlineFix signature files
    local of_files
    of_files=$(find "$gdir" -maxdepth 3 \( -name "pfx" -o -name ".git" -o -name ".save_snapshots" -o -name "saves" \) -prune -o \( \
        -iname "OnlineFix64.dll" -o -iname "OnlineFix.dll" -o -iname "OnlineFix.ini" -o \
        -iname "dnet.dll" -o -iname "SteamOverlay64.dll" \
    \) -print 2>/dev/null || true)

    if [ -z "$of_files" ]; then
        echo "[WARN] No OnlineFix signatures found in this game directory." >&2
        echo "       Neither OnlineFix64.dll, OnlineFix.dll, nor OnlineFix.ini was found." >&2
        return 1
    fi
    echo "[VERIFIED] OnlineFix signature detected."

    # 2. Spacewar (AppID 480) Entitlement & ACF Check
    local s_primary
    s_primary="$(get_steam_primary_apps 2>/dev/null || echo "$HOME/.local/share/Steam/steamapps")"
    local has_spacewar=0
    if [ -f "$s_primary/appmanifest_480.acf" ]; then
        has_spacewar=1
    fi
    local sls_cfg="$HOME/.config/SLSsteam/config.yaml"
    if [ -f "$sls_cfg" ] && grep -q -E '^[[:space:]]*480:' "$sls_cfg" 2>/dev/null; then
        has_spacewar=1
    fi

    if [ "$has_spacewar" -eq 1 ]; then
        echo "[VERIFIED] Spacewar (AppID 480) already registered in Steam/SLSsteam library."
    else
        echo "[INFO] Spacewar (AppID 480) not registered yet. Running automatic registration..."
        sync_steam 480 "Spacewar" "$gdir"
        echo "[VERIFIED] Spacewar (AppID 480) successfully registered to Steam/SLSsteam."
    fi

    # 3. Audit & Sync OnlineFix.ini PlayerName
    local ini_file
    ini_file=$(find "$gdir" -maxdepth 3 \( -name "pfx" -o -name ".git" \) -prune -o -iname "OnlineFix.ini" -print 2>/dev/null | head -n 1)
    if [ -n "$ini_file" ] && [ -f "$ini_file" ]; then
        local curr_pname
        curr_pname=$(grep -E '^[[:space:]]*PlayerName[[:space:]]*=' "$ini_file" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*PlayerName[[:space:]]*=[[:space:]]*//' | tr -d '\r')
        echo "[INFO] OnlineFix.ini detected: $ini_file"
        echo "       Current PlayerName: ${curr_pname:-[Unset]}"

        local persona_name=""
        if [ -f "$HOME/.config/gamectl/persona" ]; then
            persona_name=$(grep -E '^[[:space:]]*account_name[[:space:]]*=' "$HOME/.config/gamectl/persona" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_name[[:space:]]*=[[:space:]]*//' | tr -d '\r')
        fi
        [ -z "$persona_name" ] && persona_name="${USER:-Player}"

        if [ -n "$persona_name" ] && [ "$persona_name" != "$curr_pname" ]; then
            local should_sync=false
            if [ "$auto_yes" = true ]; then
                should_sync=true
            elif [ -t 0 ]; then
                echo -n "       Synchronize PlayerName to '$persona_name'? [Y/n] (Auto-yes in 5s): "
                local confirm_sync=""
                read -t 5 -r confirm_sync || confirm_sync="y"
                echo
                if [[ ! "$confirm_sync" =~ ^[nN] ]]; then
                    should_sync=true
                fi
            else
                should_sync=true
            fi

            if [ "$should_sync" = true ]; then
                sed -i -E "s/^[[:space:]]*PlayerName[[:space:]]*=.*/PlayerName = $persona_name/" "$ini_file"
                echo "       ${UI_GREEN}[SUCCESS] PlayerName in OnlineFix.ini synchronized to: $persona_name${UI_RST}"
            fi
        fi
    fi

    echo "[VERIFIED] OnlineFix setup completed for: $(basename "$gdir")"
    return 0
}

# Launch game with performance wrapping and runner isolation
launch_game() {
    local gdir="$1"
    local gbin="$2"
    local title="$3"
    shift 3 || true

    echo "[INFO] Preparing launch: $title..."
    backup_save "$gdir" true || true

    # Resolve wrappers and extra flags
    declare -a GAMECTL_WRAPPER_PREFIX=()
    declare -a GAMECTL_REMAINING_ARGS=()
    GAMECTL_ACTIVE_GLTHREAD=0
    build_wrapper_command "$gdir" "$@"
    local wrappers=("${GAMECTL_WRAPPER_PREFIX[@]}")
    local game_args=("${GAMECTL_REMAINING_ARGS[@]}")

    # Set Mesa performance env safely (only enable glthread if explicitly opted in)
    if [ "${GAMECTL_ACTIVE_GLTHREAD:-0}" = "1" ]; then
        export mesa_glthread=true
    else
        unset mesa_glthread
    fi
    export vblank_mode=0

    # Hybrid dGPU PRIME offloading
    if [ "${GAMECTL_ACTIVE_PRIME:-0}" = "1" ]; then
        case "${GAMECTL_ACTIVE_PRIME_VENDOR:-none}" in
            nvidia)
                export __NV_PRIME_RENDER_OFFLOAD=1
                export __GLX_VENDOR_LIBRARY_NAME=nvidia
                export __VK_LAYER_NV_optimus=NVIDIA_only
                echo "[INFO] Hybrid Graphics: Injected NVIDIA PRIME offload environment."
                ;;
            amd|intel)
                export DRI_PRIME=1
                echo "[INFO] Hybrid Graphics: Injected DRI_PRIME=1 offload environment."
                ;;
            *)
                export DRI_PRIME=1
                echo "[INFO] Hybrid Graphics: Fallback to DRI_PRIME=1 offload environment."
                ;;
        esac
    fi

    # Remedi Audio (DEFECT-03): Set buffer latency environment safely (PipeWire / PulseAudio)
    export PIPEWIRE_LATENCY="${GAMECTL_PIPEWIRE_LATENCY:-256/48000}"
    export PULSE_LATENCY_MSEC="${GAMECTL_PULSE_LATENCY:-60}"

    # Capture current CPU scaling governor for clean restoration
    local prev_governor=""
    if [ -f /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]; then
        prev_governor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo "")
    fi

    # Attempt CPU scaling governor if permitted and not already in performance mode
    if [ -w /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]; then
        if [ "$prev_governor" != "performance" ]; then
            echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor >/dev/null 2>&1 || true
        fi
    fi

    # Local state cleanup helper & signal trap
    local unit_name=""
    _restore_launch_state() {
        if [ -n "$unit_name" ]; then
            systemctl --user stop "$unit_name.scope" 2>/dev/null || true
        fi
        if [ -n "$prev_governor" ] && [ -w /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]; then
            echo "$prev_governor" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor >/dev/null 2>&1 || true
        fi
        if [ "$is_win" = true ] && [ -d "$gdir/pfx" ]; then
            # Remediation DEFECT-02: Flush wine prefix writes to disk (wineserver -w)
            local ws_bin
            ws_bin="$(get_wineserver_bin "${runner_bin:-}" 2>/dev/null || true)"
            [ -n "$ws_bin" ] && WINEPREFIX="$gdir/pfx" "$ws_bin" -w 2>/dev/null || true
        fi
        unset __NV_PRIME_RENDER_OFFLOAD __GLX_VENDOR_LIBRARY_NAME __VK_LAYER_NV_optimus DRI_PRIME
        clean_stale_locks
    }
    trap '_restore_launch_state; trap - INT TERM EXIT; return 130 2>/dev/null || exit 130' INT
    trap '_restore_launch_state; trap - INT TERM EXIT; return 143 2>/dev/null || exit 143' TERM
    trap '_restore_launch_state' EXIT

    if [ ${#wrappers[@]} -gt 0 ]; then
        echo "[INFO] Active wrappers: ${wrappers[*]}"
    fi

    cd "$gdir"

    # Check if target is a Windows executable (.exe / PE)
    local is_win=false
    case "$gbin" in
        *.exe|*.EXE) is_win=true ;;
    esac
    if [ "$is_win" = false ] && [ -f "$gdir/$gbin" ]; then
        if file -b "$gdir/$gbin" 2>/dev/null | grep -qi -E "PE32|MS Windows"; then
            is_win=true
        fi
    fi

    # Prepare runtime directory and log stream
    local run_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$UID}"
    mkdir -p -m 700 "$run_dir/active_games"
    local safe_gbin
    safe_gbin=$(basename "$gbin" | tr -cd '[:alnum:]_-')
    local log_file="$run_dir/game_${safe_gbin}.log"
    : > "$log_file"

    local game_pid=""
    local run_type="Native Linux"

    local safe_title
    safe_title=$(echo "$title" | tr -cd '[:alnum:]_-')
    [ -z "$safe_title" ] && safe_title="game"

    local use_scope=false
    if [ "${GAMECTL_ACTIVE_SYSTEMD_SCOPE:-0}" = "1" ] && check_systemd_scope_support; then
        use_scope=true
    fi

    local -a sandbox_cmd=()
    if [ "${GAMECTL_ACTIVE_SANDBOX:-0}" = "1" ] && [ ${#GAMECTL_SANDBOX_PREFIX[@]} -gt 0 ]; then
        sandbox_cmd=("${GAMECTL_SANDBOX_PREFIX[@]}")
        echo "[INFO] Security Sandbox: Bubblewrap rootless filesystem isolation active."
    fi

    _exec_in_scope() {
        local -a final_cmd=()
        [ ${#sandbox_cmd[@]} -gt 0 ] && final_cmd+=("${sandbox_cmd[@]}")
        final_cmd+=("$@")
        if [ "$use_scope" = true ]; then
            exec systemd-run --user --scope --quiet --unit="gamectl-${safe_title}-${BASHPID}" --description="gamectl: ${title}" "${final_cmd[@]}"
        else
            exec "${final_cmd[@]}"
        fi
    }

    if [ "$is_win" = true ]; then
        local detected_overrides
        detected_overrides=$(detect_dll_overrides "$gdir")
        if [ -n "$detected_overrides" ]; then
            export WINEDLLOVERRIDES="$detected_overrides"
            echo "[INFO] Active DLL Overrides: $WINEDLLOVERRIDES"
        fi

        local runner_bin
        runner_bin=$(find_runner "$gdir" 2>/dev/null || true)
        if [ -z "$runner_bin" ]; then
            echo "[ERROR] Windows runner not found (umu-run, Proton, or Wine not installed)." >&2
            echo "        Install GE-Proton in ~/.local/share/Steam/compatibilitytools.d/ or install wine." >&2
            _restore_launch_state
            return 1
        fi

        local pfx_dir="$gdir/pfx"
        mkdir -p "$pfx_dir"
        local appid=""
        if [ -f "$gdir/steam_appid.txt" ]; then
            appid=$(tr -dc '0-9' < "$gdir/steam_appid.txt")
        fi
        [ -z "$appid" ] && appid="0"

        run_type="Windows ($(basename "$runner_bin"))"
        echo "[INFO] Launching Windows game via $(basename "$runner_bin") in background..."
        echo "[INFO] Isolated Wine Prefix: $pfx_dir"
        echo "[INFO] Log stream: $log_file"

        case "$runner_bin" in
            umu-run)
                (
                    export WINEPREFIX="$pfx_dir" GAMEID="$appid" WINEDLLOVERRIDES="${WINEDLLOVERRIDES:-}"
                    _exec_in_scope "${wrappers[@]}" umu-run "$gdir/$gbin" "${game_args[@]}"
                ) > "$log_file" 2>&1 &
                game_pid=$!
                ;;
            *proton*)
                (
                    export STEAM_COMPAT_CLIENT_INSTALL_PATH="${STEAM_CLIENT_INSTALL_PATH:-$(get_steam_root 2>/dev/null || echo "$HOME/.local/share/Steam")}" \
                    STEAM_COMPAT_DATA_PATH="$gdir" \
                    STEAM_COMPAT_APP_ID="$appid" \
                    WINEPREFIX="$pfx_dir" \
                    WINEDLLOVERRIDES="${WINEDLLOVERRIDES:-}"
                    _exec_in_scope "${wrappers[@]}" "$runner_bin" waitforexitandrun "$gdir/$gbin" "${game_args[@]}"
                ) > "$log_file" 2>&1 &
                game_pid=$!
                ;;
            *)
                (
                    export WINEPREFIX="$pfx_dir" WINEDLLOVERRIDES="${WINEDLLOVERRIDES:-}"
                    _exec_in_scope "${wrappers[@]}" "$runner_bin" "$gdir/$gbin" "${game_args[@]}"
                ) > "$log_file" 2>&1 &
                game_pid=$!
                ;;
        esac
    else
        echo "[INFO] Launching $title (Native Linux) in background..."
        echo "[INFO] Log stream: $log_file"
        (
            _exec_in_scope "${wrappers[@]}" ./"$gbin" "${game_args[@]}"
        ) > "$log_file" 2>&1 &
        game_pid=$!
    fi

    if [ -z "$game_pid" ] || ! kill -0 "$game_pid" 2>/dev/null; then
        echo "[ERROR] Failed to launch game into background." >&2
        _restore_launch_state
        return 1
    fi

    if [ "$use_scope" = true ]; then
        unit_name="gamectl-${safe_title}-${game_pid}"
    fi

    local info_file="$run_dir/active_games/${game_pid}.info"
    cat <<EOF > "$info_file"
PID=$game_pid
TITLE=$title
DIR=$gdir
BIN=$gbin
LOG=$log_file
START=$(date +%s)
SCOPE_UNIT=$unit_name
EOF

    # Detached background watchdog to restore CPU governor and cleanup when process exits
    (
        wait "$game_pid" 2>/dev/null
        if [ -n "$unit_name" ]; then
            systemctl --user stop "$unit_name.scope" 2>/dev/null || true
        fi
        if [ "$is_win" = true ] && [ -d "$pfx_dir" ]; then
            # Remediation DEFECT-02: Wait for wineserver to flush data & release lockfile before snapshot (wineserver -w)
            local ws_bin
            ws_bin="$(get_wineserver_bin "${runner_bin:-}" 2>/dev/null || true)"
            [ -n "$ws_bin" ] && WINEPREFIX="$pfx_dir" "$ws_bin" -w 2>/dev/null || true
        fi
        rm -f "$info_file" 2>/dev/null || true
        _restore_launch_state
    ) &

    echo "[VERIFIED] Game '$title' running in background (PID: $game_pid)."

    # If running interactively, invoke Game Controller HUD
    local hud_exit=0
    if [ -t 0 ]; then
        game_controller_hud "$game_pid" "$title" "$log_file" "$gdir" "$gbin" "$info_file" "$run_type" || hud_exit=$?
    fi

    trap - INT TERM EXIT
    return "$hud_exit"
}

# Sync savegame to remote companion host
sync_save_remote() {
    local gdir="$1"
    local title="$2"
    local override_host="${3:-}"
    local sdir="$gdir/saves"
    local rhost="$override_host"
    [ -z "$rhost" ] && rhost=$(get_remote_host)

    if [ ! -d "$sdir" ]; then
        echo "[ERROR] Portable saves directory not found in $gdir"
        return 1
    fi

    if [ -z "$rhost" ]; then
        echo "[WARN] Target remote host not configured."
        echo "       Define host in ~/.config/gamectl/remote_host or GAMECTL_REMOTE_HOST variable."
        return 1
    fi

    echo "[INFO] Checking connectivity to $rhost..."
    if ! ssh -q -o ConnectTimeout=1 -o BatchMode=yes "$rhost" exit 2>/dev/null; then
        echo "[WARN] Remote host '$rhost' offline or unreachable on local network."
        return 1
    fi

    echo "[INFO] Synchronizing savegame $title to $rhost..."
    local canon_gdir
    canon_gdir="$(cd "$gdir" 2>/dev/null && pwd || echo "$gdir")"

    local rel_path
    if [[ "$canon_gdir" == "$HOME/"* ]]; then
        rel_path="${canon_gdir#$HOME/}"
    else
        # For games stored on secondary drives (/mnt, /media, /data, etc.)
        rel_path="Games/$(basename "$canon_gdir")"
    fi
    rel_path="${rel_path#/}"

    ssh "$rhost" "mkdir -p ~/$rel_path"
    rsync -avzP --exclude="*.tmp" "$sdir/" "$rhost:~/$rel_path/saves/"
    echo "[VERIFIED] Savegame synchronization to $rhost completed."
}

# Aliases for remote savegame synchronization
sync_to_companion() {
    sync_save_remote "$@"
}

sync_to_tuf() {
    sync_save_remote "$@"
}


# Inject GBE Fork emulator and portable saves into a game folder
inject_game() {
    local target_dir="$1"
    local appid="${2:-}"
    local sync_mode="${3:-all}"

    if [ ! -d "$target_dir" ]; then
        echo "[ERROR] Target directory not found: $target_dir" >&2
        return 1
    fi

    # Canonical path
    target_dir="$(cd "$target_dir" && pwd)"

    # Resolve AppID if not provided
    if [ -z "$appid" ]; then
        if [ -f "$target_dir/steam_appid.txt" ]; then
            appid=$(tr -dc '0-9' < "$target_dir/steam_appid.txt")
        fi
        if [ -z "$appid" ]; then
            local parent_dir
            parent_dir="$(dirname "$target_dir")"
            if [ "$(basename "$parent_dir")" = "common" ]; then
                local steamapps_dir
                steamapps_dir="$(dirname "$parent_dir")"
                local base_name
                base_name="$(basename "$target_dir")"
                for acf in "$steamapps_dir"/appmanifest_*.acf; do
                    [ -f "$acf" ] || continue
                    if grep -q "\"installdir\"[[:space:]]\+\"$base_name\"" "$acf" 2>/dev/null; then
                        appid=$(grep -E '^\s*"appid"' "$acf" | head -n 1 | sed -E 's/.*"appid"[[:space:]]+"([0-9]+)".*/\1/')
                        break
                    fi
                done
            fi
        fi
    fi

    echo "[INFO] Preparing GBE Fork injection in: $target_dir..."

    # 1. Identify Target Executable and Platform
    local gbin=""
    gbin=$(find_game_binary "$target_dir") || true

    local target_platform="linux"
    local arch="x64"
    local is_32bit=false

    # Check existing steam libraries in target folder
    local found_win64 found_win32 found_linux
    found_win64=$(find "$target_dir" -maxdepth 4 -name "steam_api64.dll" 2>/dev/null | head -n 1)
    found_win32=$(find "$target_dir" -maxdepth 4 -name "steam_api.dll" 2>/dev/null | head -n 1)
    found_linux=$(find "$target_dir" -maxdepth 4 -name "libsteam_api.so" 2>/dev/null | head -n 1)

    if [ -n "$gbin" ] && [ -f "$target_dir/$gbin" ]; then
        local btype
        btype=$(file -b "$target_dir/$gbin" 2>/dev/null || echo "")
        if echo "$btype" | grep -qi -E "PE32|MS Windows|\.exe"; then
            target_platform="windows"
            if echo "$btype" | grep -qi "PE32+"; then
                arch="x64"
                is_32bit=false
            elif echo "$btype" | grep -qi "32-bit"; then
                arch="x86"
                is_32bit=true
            else
                arch="x64"
                is_32bit=false
            fi
        else
            target_platform="linux"
            if echo "$btype" | grep -qi "32-bit"; then
                arch="x86"
                is_32bit=true
            else
                arch="x64"
                is_32bit=false
            fi
        fi
    elif [ -n "$found_linux" ]; then
        target_platform="linux"
        if file -b "$found_linux" | grep -qi "32-bit"; then
            arch="x86"
            is_32bit=true
        else
            arch="x64"
            is_32bit=false
        fi
    elif [ -n "$found_win64" ] || [ -n "$found_win32" ]; then
        target_platform="windows"
        if [ -n "$found_win64" ]; then
            arch="x64"
            is_32bit=false
        else
            arch="x86"
            is_32bit=true
        fi
    fi

    # 2. Perform Shim Injections (with backup of originals)
    local primary_shim_dir="$target_dir"

    # 2a. Windows Shim Injection (if windows steam files exist or target is windows)
    if [ -n "$found_win64" ] || [ -n "$found_win32" ] || [ "$target_platform" = "windows" ]; then
        local win_targets=()
        if [ -n "$found_win64" ]; then
            win_targets+=("$found_win64:x64")
        fi
        if [ -n "$found_win32" ]; then
            win_targets+=("$found_win32:x86")
        fi

        # If neither found but target is windows, determine destination based on detected arch or gbin location
        if [ ${#win_targets[@]} -eq 0 ] && [ "$target_platform" = "windows" ]; then
            local bin_subdir="$target_dir"
            [ -n "$gbin" ] && [ -f "$target_dir/$gbin" ] && bin_subdir="$(dirname "$target_dir/$gbin")"
            if [ "$is_32bit" = true ]; then
                win_targets+=("$bin_subdir/steam_api.dll:x86")
            else
                win_targets+=("$bin_subdir/steam_api64.dll:x64")
            fi
        fi

        for entry in "${win_targets[@]}"; do
            local t_dll="${entry%%:*}"
            local t_arch="${entry##*:}"
            local t_template
            t_template=$(get_gbe_template "windows" "$t_arch") || true

            if [ -z "$t_template" ] || [ ! -f "$t_template" ]; then
                echo "[WARN] Windows GBE Fork template ($t_arch) not found." >&2
                continue
            fi

            # Backup original Valve DLL if present (<7MB and .orig not existing)
            if [ -f "$t_dll" ]; then
                local sz
                sz=$(stat -c%s "$t_dll" 2>/dev/null || echo 0)
                if [ "$sz" -lt 7000000 ] && [ ! -f "$t_dll.orig" ]; then
                    cp -a "$t_dll" "$t_dll.orig"
                    echo "[INFO] Original $(basename "$t_dll") backed up to: $t_dll.orig"
                fi
            fi

            mkdir -p "$(dirname "$t_dll")"
            cp "$t_template" "$t_dll"
            chmod +x "$t_dll" 2>/dev/null || true
            primary_shim_dir="$(dirname "$t_dll")"
            echo "[INFO] Windows GBE Fork DLL ($t_arch) installed at: $t_dll"
        done
    fi

    # 2b. Linux Shim Injection (if linux steam files exist or target is linux)
    if [ -n "$found_linux" ] || [ "$target_platform" = "linux" ]; then
        local linux_arch="x64"
        if [ -n "$found_linux" ]; then
            if file -b "$found_linux" | grep -qi "32-bit"; then
                linux_arch="x86"
            fi
        elif [ "$is_32bit" = true ]; then
            linux_arch="x86"
        fi

        local target_so="$target_dir/libsteam_api.so"
        if [ -n "$found_linux" ]; then
            target_so="$found_linux"
        elif [ -d "$target_dir/lib64" ] && [ "$linux_arch" = "x64" ]; then
            target_so="$target_dir/lib64/libsteam_api.so"
        elif [ -d "$target_dir/lib32" ] && [ "$linux_arch" = "x86" ]; then
            target_so="$target_dir/lib32/libsteam_api.so"
        fi

        local src_so
        src_so=$(get_gbe_template "linux" "$linux_arch") || true
        if [ -n "$src_so" ] && [ -f "$src_so" ]; then
            # Backup original Valve SO if present (<7MB and .orig not existing)
            if [ -f "$target_so" ]; then
                local sz
                sz=$(stat -c%s "$target_so" 2>/dev/null || echo 0)
                if [ "$sz" -lt 7000000 ] && [ ! -f "$target_so.orig" ]; then
                    cp -a "$target_so" "$target_so.orig"
                    echo "[INFO] Original libsteam_api.so backed up to: $target_so.orig"
                fi
            fi

            mkdir -p "$(dirname "$target_so")"
            cp "$src_so" "$target_so"
            chmod +x "$target_so"
            primary_shim_dir="$(dirname "$target_so")"
            echo "[INFO] Linux GBE Fork ELF ($linux_arch) installed at: $target_so"
        else
            [ "$target_platform" = "linux" ] && echo "[WARN] Linux GBE Fork template ($linux_arch) not found at: ${src_so:-empty}" >&2
        fi
    fi

    # 3. Setup steam_settings and configs.user.ini
    mkdir -p "$target_dir/steam_settings"
    local user_name=""
    local steamid=""

    # Check existing game persona or global persona
    if [ -f "$target_dir/steam_settings/configs.user.ini" ]; then
        user_name=$(grep -E '^[[:space:]]*account_name[[:space:]]*=' "$target_dir/steam_settings/configs.user.ini" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_name[[:space:]]*=[[:space:]]*//' | tr -d '\r')
        steamid=$(grep -E '^[[:space:]]*account_steamid[[:space:]]*=' "$target_dir/steam_settings/configs.user.ini" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_steamid[[:space:]]*=[[:space:]]*//' | tr -d '\r')
    fi
    if [ -z "$user_name" ] && [ -f "$HOME/.config/gamectl/persona" ]; then
        user_name=$(grep -E '^[[:space:]]*account_name[[:space:]]*=' "$HOME/.config/gamectl/persona" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_name[[:space:]]*=[[:space:]]*//' | tr -d '\r')
    fi
    if [ -z "$steamid" ] && [ -f "$HOME/.config/gamectl/persona" ]; then
        steamid=$(grep -E '^[[:space:]]*account_steamid[[:space:]]*=' "$HOME/.config/gamectl/persona" 2>/dev/null | head -n 1 | sed -E 's/^[[:space:]]*account_steamid[[:space:]]*=[[:space:]]*//' | tr -d '\r')
    fi
    [ -z "$user_name" ] && user_name="${USER:-Player}"
    if [ -z "$steamid" ]; then
        steamid=$(resolve_active_steamid)
    fi

    cat <<EOF > "$target_dir/steam_settings/configs.user.ini"
[user::general]
account_name=$user_name
account_steamid=$steamid
language=english

[user::saves]
local_save_path=./saves
EOF

    # Scaffold custom_broadcasts.txt if missing
    if [ ! -f "$target_dir/steam_settings/custom_broadcasts.txt" ]; then
        cat <<EOF > "$target_dir/steam_settings/custom_broadcasts.txt"
# GBE Fork LAN Custom Broadcast IP list
# Add peer IPs or broadcast subnets (one IP per line)
127.0.0.1
255.255.255.255
EOF
    fi

    # If shim is in a subfolder, link steam_settings beside it as per GBE specification
    if [ "$primary_shim_dir" != "$target_dir" ] && [ -d "$primary_shim_dir" ]; then
        ln -sfn "$target_dir/steam_settings" "$primary_shim_dir/steam_settings" 2>/dev/null || true
    fi

    # 4. Setup isolated portable saves folder and markers
    mkdir -p "$target_dir/saves"
    echo -n "saves" > "$target_dir/local_save.txt"
    if [ "$primary_shim_dir" != "$target_dir" ] && [ -d "$primary_shim_dir" ]; then
        echo -n "saves" > "$primary_shim_dir/local_save.txt" 2>/dev/null || true
        ln -sfn "$target_dir/saves" "$primary_shim_dir/saves" 2>/dev/null || true
    fi

    # 5. Write steam_appid.txt if available
    if [ -n "$appid" ] && [ "$appid" != "STANDALONE" ]; then
        echo -n "$appid" > "$target_dir/steam_appid.txt"
        if [ "$primary_shim_dir" != "$target_dir" ] && [ -d "$primary_shim_dir" ]; then
            echo -n "$appid" > "$primary_shim_dir/steam_appid.txt" 2>/dev/null || true
        fi
        echo "[INFO] AppID $appid registered in: $target_dir/steam_appid.txt"
        fetch_dlc "$target_dir" "$appid"
        if [ "$sync_mode" != "--no-sync" ] && [ "$sync_mode" != "no-sync" ] && [ "$sync_mode" != "standalone" ]; then
            sync_steam "$appid" "$(basename "$target_dir")" "$target_dir"
        else
            echo "[INFO] Standalone Mode active: Skipping Steam Client synchronization."
        fi
    fi

    echo "[VERIFIED] GBE Fork successfully injected (Platform: $target_platform, Arch: $arch, Save: ./saves, AppID: ${appid:-None})"
}


# CLI helper for launching games with wrappers and options
cli_launch() {
    local l_dir="${1:-}"
    shift || true
    local l_bin=""
    local l_title=""
    local l_flags=()

    while [ $# -gt 0 ]; do
        case "$1" in
            --hud|--mangohud|--no-hud|--no-mangohud|--gamemode|--no-gamemode|--gamescope|--no-gamescope|--fsr|--no-fsr|--glthread|--no-glthread|--scope|--systemd-scope|--no-scope|--no-systemd-scope|--prime|--no-prime|--sandbox|--no-sandbox)
                l_flags+=("$1")
                shift
                ;;
            *)
                if [ -z "$l_bin" ]; then
                    l_bin="$1"
                elif [ -z "$l_title" ]; then
                    l_title="$1"
                else
                    l_flags+=("$1")
                fi
                shift
                ;;
        esac
    done

    [ -z "$l_title" ] && l_title="$(basename "$l_dir")"
    if [ -z "$l_bin" ]; then
        l_bin=$(find_game_binary "$l_dir" 2>/dev/null || echo "")
    fi

    if [ -n "$l_bin" ]; then
        launch_game "$l_dir" "$l_bin" "$l_title" "${l_flags[@]}"
    else
        echo "[ERROR] Executable binary not found in: $l_dir" >&2
        return 1
    fi
}


# --- [MODULE] src/diagnostics/60_doctor.sh ---
# System Diagnostics & Health Audit
doctor_audit() {
    local pass_cnt=0 warn_cnt=0 miss_cnt=0

    echo "${UI_BOX}╭─ GAMECTL SYSTEM DIAGNOSTICS & HEALTH AUDIT ─────────────────╮${UI_RST}"
    local os_str="Linux"
    [ -f /etc/os-release ] && os_str=$(grep -E '^PRETTY_NAME=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
    echo "│ ${UI_CYAN}Host OS     ${UI_RST}: ${UI_BOLD}$os_str${UI_RST} ${UI_DIM}($(uname -sr) $(uname -m))${UI_RST}"
    echo "│ ${UI_CYAN}Display     ${UI_RST}: ${WAYLAND_DISPLAY:+Wayland ($WAYLAND_DISPLAY)}${DISPLAY:+ X11 ($DISPLAY)}"
    echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"

    # Layer 1: CLI Fundamental Tools
    echo
    echo "  ${UI_PURPLE}[LAYER 1] Fundamental CLI Tools${UI_RST}"
    local cli_tool
    for cli_tool in fzf jq curl file unzip rsync ssh; do
        if command -v "$cli_tool" >/dev/null 2>&1; then
            echo "    • $(printf '%-10s' "$cli_tool") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($(command -v "$cli_tool"))${UI_RST}"
            pass_cnt=$((pass_cnt + 1))
        else
            echo "    • $(printf '%-10s' "$cli_tool") : ${UI_RED}[MISSING]${UI_RST} Install via distro package manager"
            miss_cnt=$((miss_cnt + 1))
        fi
    done

    # Layer 2: Python Runtime & YAML Engine
    echo
    echo "  ${UI_PURPLE}[LAYER 2] Python Runtime & YAML Engine${UI_RST}"
    if command -v python3 >/dev/null 2>&1; then
        echo "    • $(printf '%-10s' "python3") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($(python3 --version 2>&1))${UI_RST}"
        pass_cnt=$((pass_cnt + 1))
        if python3 -c "import ruamel.yaml" 2>/dev/null; then
            echo "    • $(printf '%-10s' "YAML") : ${UI_GREEN}[READY]${UI_RST} ruamel.yaml (Preserves SLSsteam layout)"
            pass_cnt=$((pass_cnt + 1))
        elif python3 -c "import yaml" 2>/dev/null; then
            echo "    • $(printf '%-10s' "YAML") : ${UI_GREEN}[READY]${UI_RST} PyYAML fallback installed"
            pass_cnt=$((pass_cnt + 1))
        else
            echo "    • $(printf '%-10s' "YAML") : ${UI_AMBER}[WARN]${UI_RST} Neither ruamel.yaml nor pyyaml found"
            warn_cnt=$((warn_cnt + 1))
        fi
    else
        echo "    • $(printf '%-10s' "python3") : ${UI_RED}[MISSING]${UI_RST} Python 3 runtime not found"
        miss_cnt=$((miss_cnt + 1))
    fi

    # Layer 3: GBE Fork Templates
    echo
    echo "  ${UI_PURPLE}[LAYER 3] GBE Fork Binary Templates${UI_RST}"
    local gbe_targets=(
        "Linux x64:linux:x64"
        "Linux x86:linux:x86"
        "Windows x64:windows:x64"
        "Windows x86:windows:x86"
    )
    for gt in "${gbe_targets[@]}"; do
        local g_label="${gt%%:*}"
        local g_rest="${gt#*:}"
        local g_plat="${g_rest%%:*}"
        local g_arch="${g_rest##*:}"
        local g_path
        g_path=$(get_gbe_template "$g_plat" "$g_arch" 2>/dev/null || true)
        if [ -n "$g_path" ] && [ -f "$g_path" ]; then
            echo "    • $(printf '%-11s' "$g_label") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($g_path)${UI_RST}"
            pass_cnt=$((pass_cnt + 1))
        else
            echo "    • $(printf '%-11s' "$g_label") : ${UI_RED}[MISSING]${UI_RST} Place template in ~/.local/share/gbe-fork/"
            miss_cnt=$((miss_cnt + 1))
        fi
    done

    # Layer 4: Windows Game Runner
    echo
    echo "  ${UI_PURPLE}[LAYER 4] Windows Game Runners${UI_RST}"
    local r_found=0
    if command -v umu-run >/dev/null 2>&1; then
        echo "    • $(printf '%-10s' "umu-run") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($(command -v umu-run))${UI_RST}"
        r_found=1
    else
        echo "    • $(printf '%-10s' "umu-run") : ${UI_DIM}[N/A]${UI_RST} (Optional Unified Proton Runner)"
    fi

    local ge_proton=""
    local s_dyn_root
    s_dyn_root="$(get_steam_root 2>/dev/null || true)"
    local cdir
    for cdir in "$s_dyn_root/compatibilitytools.d" "$HOME/.local/share/Steam/compatibilitytools.d" "$HOME/.steam/root/compatibilitytools.d" "$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam/compatibilitytools.d"; do
        [ -n "$cdir" ] && [ -d "$cdir" ] || continue
        ge_proton=$(find "$cdir" -maxdepth 2 -name "proton" 2>/dev/null | head -n 1 || true)
        [ -n "$ge_proton" ] && break
    done
    if [ -n "$ge_proton" ]; then
        echo "    • $(printf '%-10s' "GE-Proton") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($ge_proton)${UI_RST}"
        r_found=1
    else
        echo "    • $(printf '%-10s' "GE-Proton") : ${UI_DIM}[N/A]${UI_RST} (In compatibilitytools.d/)"
    fi

    if command -v wine >/dev/null 2>&1; then
        echo "    • $(printf '%-10s' "Wine") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($(wine --version 2>/dev/null || echo 'wine'))${UI_RST}"
        r_found=1
    else
        echo "    • $(printf '%-10s' "Wine") : ${UI_DIM}[N/A]${UI_RST} (System Wine fallback)"
    fi

    if [ "$r_found" -eq 1 ]; then
        pass_cnt=$((pass_cnt + 1))
    else
        echo "    • ${UI_AMBER}[WARN] No Windows runners detected. Only Native Linux games can launch.${UI_RST}"
        warn_cnt=$((warn_cnt + 1))
    fi

    # Layer 5: Performance & Display Wrappers
    echo
    echo "  ${UI_PURPLE}[LAYER 5] Performance & Display Wrappers${UI_RST}"
    for w_tool in "gamemoderun:GameMode" "mangohud:MangoHud" "gamescope:Gamescope"; do
        local wt_cmd="${w_tool%%:*}"
        local wt_name="${w_tool##*:}"
        if command -v "$wt_cmd" >/dev/null 2>&1; then
            echo "    • $(printf '%-10s' "$wt_name") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($(command -v "$wt_cmd"))${UI_RST}"
            pass_cnt=$((pass_cnt + 1))
        else
            echo "    • $(printf '%-10s' "$wt_name") : ${UI_DIM}[OFF]${UI_RST} Not installed ($wt_cmd missing)"
            warn_cnt=$((warn_cnt + 1))
        fi
    done

    # Layer 6: Headless Downloader Engine
    echo
    echo "  ${UI_PURPLE}[LAYER 6] Headless Downloader Engine${UI_RST}"
    local dl_bin=""
    if command -v depotdownloader >/dev/null 2>&1; then
        dl_bin="$(command -v depotdownloader)"
    elif [ -x "$HOME/.local/share/gamectl/bin/DepotDownloader" ]; then
        dl_bin="$HOME/.local/share/gamectl/bin/DepotDownloader"
    elif [ -x "$HOME/.local/bin/depotdownloader" ]; then
        dl_bin="$HOME/.local/bin/depotdownloader"
    fi
    if [ -n "$dl_bin" ]; then
        echo "    • $(printf '%-15s' "DepotDownloader") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($dl_bin)${UI_RST}"
        pass_cnt=$((pass_cnt + 1))
    else
        echo "    • $(printf '%-15s' "DepotDownloader") : ${UI_RED}[MISSING]${UI_RST} Run 'gamectl ensure-downloader' to install"
        miss_cnt=$((miss_cnt + 1))
    fi

    # Layer 7: Steam Client & SLSsteam Integration
    echo
    echo "  ${UI_PURPLE}[LAYER 7] Steam Client & SLSsteam Integration${UI_RST}"
    local s_root
    s_root="$(get_steam_root 2>/dev/null || true)"
    if [ -n "$s_root" ] && [ -d "$s_root" ]; then
        echo "    • $(printf '%-12s' "Steam Root") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($s_root)${UI_RST}"
        pass_cnt=$((pass_cnt + 1))
    else
        echo "    • $(printf '%-12s' "Steam Root") : ${UI_AMBER}[WARN]${UI_RST} Steam client directory not found"
        warn_cnt=$((warn_cnt + 1))
    fi

    local sls_file="$HOME/.config/SLSsteam/config.yaml"
    if [ -f "$sls_file" ]; then
        echo "    • $(printf '%-12s' "SLSsteam") : ${UI_GREEN}[READY]${UI_RST} ${UI_DIM}($sls_file)${UI_RST}"
        pass_cnt=$((pass_cnt + 1))
    else
        echo "    • $(printf '%-12s' "SLSsteam") : ${UI_AMBER}[WARN]${UI_RST} SLSsteam config.yaml not found (needed for zero-download unlock)"
        warn_cnt=$((warn_cnt + 1))
    fi

    # Hardware GPU & Mesa Driver Health
    echo
    echo "  ${UI_PURPLE}[HARDWARE] GPU Controller & Mesa Driver Health${UI_RST}"
    local gpu_line
    gpu_line=$(lspci 2>/dev/null | grep -E "VGA|3D" | head -n 1 | sed -E 's/^[0-9a-f:.]+ (VGA compatible controller|3D controller): //' || true)
    [ -z "$gpu_line" ] && gpu_line="Not detected via lspci"
    echo "    • GPU Controller : ${UI_BOLD}$gpu_line${UI_RST}"
    if is_haswell_gpu; then
        echo "    • Mesa Driver    : ${UI_AMBER}[WARN]${UI_RST} Intel Haswell has incomplete Vulkan (hasvk)."
        echo "    • Driver Safety  : ${UI_ICE}Mesa GL Threading is disabled by default to prevent FNA/XNA asset decompression crashes.${UI_RST}"
        warn_cnt=$((warn_cnt + 1))
    else
        echo "    • Driver Status  : ${UI_GREEN}[READY]${UI_RST} GPU supported by standard Mesa driver stack."
        pass_cnt=$((pass_cnt + 1))
    fi

    local dgpu_vend
    dgpu_vend="$(detect_dgpu_vendor 2>/dev/null || echo "none")"
    if [ "$dgpu_vend" != "none" ]; then
        echo "    • Hybrid dGPU    : ${UI_GREEN}[READY]${UI_RST} Discrete GPU detected ($dgpu_vend). PRIME offload available (--prime)."
        pass_cnt=$((pass_cnt + 1))
    else
        echo "    • Hybrid dGPU    : ${UI_DIM}[N/A]${UI_RST} No discrete secondary GPU detected (single GPU topology)."
    fi

    echo
    echo "${UI_BOX}╭─ DIAGNOSTIC AUDIT SUMMARY ──────────────────────────────────╮${UI_RST}"
    echo "│ ${UI_GREEN}Passed: $pass_cnt${UI_RST}  •  ${UI_AMBER}Warnings: $warn_cnt${UI_RST}  •  ${UI_RED}Missing: $miss_cnt${UI_RST}"
    if [ "$miss_cnt" -eq 0 ] && [ "$warn_cnt" -eq 0 ]; then
        echo "│ System Status: ${UI_GREEN}[READY] 100% optimal for sovereign offline gaming.${UI_RST}"
    elif [ "$miss_cnt" -eq 0 ]; then
        echo "│ System Status: ${UI_GREEN}[READY] Core dependencies satisfied. Review warnings above.${UI_RST}"
    else
        echo "│ System Status: ${UI_AMBER}[WARN] Essential dependencies missing. Install missing tools.${UI_RST}"
    fi
    echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"

    return $(( miss_cnt > 0 ? 1 : 0 ))
}

# Query ProtonDB community compatibility tier and rating (Chunk 5)
query_protondb() {
    local target="${1:-}"

    if [ -z "$target" ]; then
        echo "Usage: gamectl protondb <appid|game_dir>" >&2
        return 1
    fi

    local appid=""
    if [[ "$target" =~ ^[0-9]+$ ]]; then
        appid="$target"
    elif [ -d "$target" ]; then
        if [ -f "$target/steam_appid.txt" ]; then
            appid=$(tr -dc '0-9' < "$target/steam_appid.txt")
        fi
        if [ -z "$appid" ]; then
            local base_dir
            base_dir="$(basename "$target")"
            local parent_apps
            parent_apps="$(dirname "$target")"
            if [ "$(basename "$parent_apps")" = "common" ]; then
                local steamapps_dir
                steamapps_dir="$(dirname "$parent_apps")"
                local acf
                for acf in "$steamapps_dir"/appmanifest_*.acf; do
                    [ -f "$acf" ] || continue
                    local installdir
                    installdir=$(grep -E '^\s*"installdir"' "$acf" | head -n 1 | sed -E 's/.*"installdir"[[:space:]]+"([^"]+)".*/\1/')
                    if [ "$installdir" = "$base_dir" ]; then
                        appid=$(grep -E '^\s*"appid"' "$acf" | head -n 1 | sed -E 's/.*"appid"[[:space:]]+"([0-9]+)".*/\1/')
                        break
                    fi
                done
            fi
        fi
    fi

    if [ -z "$appid" ] || [[ ! "$appid" =~ ^[0-9]+$ ]]; then
        echo "[ERROR] Invalid AppID or game directory lacks steam_appid.txt: $target" >&2
        return 1
    fi

    echo "${UI_BOX}╭─ PROTONDB COMPATIBILITY REPORT ─────────────────────────────╮${UI_RST}"
    echo "│ ${UI_CYAN}Target AppID${UI_RST}  : ${UI_BOLD}$appid${UI_RST}"

    local pdb=""
    pdb=$(fetch_cached_json "https://www.protondb.com/api/v1/reports/summaries/${appid}.json" "protondb_${appid}" 3600 2>/dev/null || true)

    if [ -n "$pdb" ] && [ "$pdb" != "null" ] && echo "$pdb" | jq . >/dev/null 2>&1; then
        local tier score conf trending
        tier=$(echo "$pdb" | jq -r ".tier // \"Unknown\"" 2>/dev/null)
        score=$(echo "$pdb" | jq -r ".score // \"-\"" 2>/dev/null)
        conf=$(echo "$pdb" | jq -r ".confidence // \"-\"" 2>/dev/null)
        trending=$(echo "$pdb" | jq -r ".trendingTier // \"-\"" 2>/dev/null)

        local tier_upper="${tier^^}"
        local c_tier="${UI_GREEN}[$tier_upper]${UI_RST}"
        local recommendation=""

        case "$tier_upper" in
            *PLATINUM*)
                c_tier="${UI_ICE}[PLATINUM]${UI_RST}"
                recommendation="Plug and play. Works flawlessly out of the box without special tweaking."
                ;;
            *GOLD*)
                c_tier="${UI_AMBER}[GOLD]${UI_RST}"
                recommendation="Runs well after minor tweaks (e.g. GE-Proton / DirectX DLL override)."
                ;;
            *SILVER*)
                c_tier="${UI_DIM}[SILVER]${UI_RST}"
                recommendation="Playable with minor issues / requires specific launch options."
                ;;
            *BRONZE*)
                c_tier="${UI_AMBER}[BRONZE]${UI_RST}"
                recommendation="Frequent crashes or graphical glitches. Specific GE-Proton version recommended."
                ;;
            *BORKED*)
                c_tier="${UI_RED}[BORKED]${UI_RST}"
                recommendation="Game currently does not run under Wine/Proton (likely invasive anti-cheat)."
                ;;
            *NATIVE*)
                c_tier="${UI_GREEN}[NATIVE]${UI_RST}"
                recommendation="Native Linux ELF build available without Wine emulation."
                ;;
            *)
                recommendation="Limited community reports. Test with latest GE-Proton release."
                ;;
        esac

        echo "│ ${UI_CYAN}ProtonDB Tier${UI_RST} : $c_tier"
        echo "│ ${UI_CYAN}Rating Score ${UI_RST} : ${UI_BOLD}$score${UI_RST} ${UI_DIM}(Confidence: $conf, Trending: $trending)${UI_RST}"
        echo "│ ${UI_CYAN}Recommendation${UI_RST}: $recommendation"
        echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
        return 0
    else
        echo "│ ${UI_CYAN}ProtonDB Tier${UI_RST} : ${UI_DIM}[NO REPORTS YET]${UI_RST}"
        echo "│ ${UI_CYAN}Details       ${UI_RST}: No community reports currently recorded for AppID $appid."
        echo "${UI_BOX}╰─────────────────────────────────────────────────────────────╯${UI_RST}"
        return 0
    fi
}


# --- [MODULE] src/tui/70_dashboard.sh ---
# Preview pane generator for installed games
preview_game() {
    local appid title status gdir gbin
    appid=$(echo "$1" | sed -r 's/\x1b\[[0-9;]*m//g' | tr -d '[:space:]')
    title=$(echo "$2" | sed -r 's/\x1b\[[0-9;]*m//g' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    status=$(echo "$3" | sed -r 's/\x1b\[[0-9;]*m//g' | tr -d '[]:space:')
    gdir="$4"
    gbin="$5"

    local status_badge="${UI_CYAN}[${status}]${UI_RST}"
    local status_desc=""
    case "$status" in
        *VALVE_SO*)
            status_badge="${UI_AMBER}[VALVE_SO]${UI_RST}"
            status_desc="${UI_DIM}(Official Steam DRM - Requires Steam Client)${UI_RST}"
            ;;
        *VALVE_DLL*)
            status_badge="${UI_CYAN}[VALVE_DLL]${UI_RST}"
            status_desc="${UI_DIM}(Windows Steam DRM - Requires Steam + Runner)${UI_RST}"
            ;;
        *GBE_FORK*)
            status_badge="${UI_GREEN}[GBE_FORK]${UI_RST}"
            status_desc="${UI_DIM}(Goldberg Fork - Steam-Free, Full DLC, LAN Ready)${UI_RST}"
            ;;
        *STANDALONE*)
            status_badge="${UI_ICE}[STANDALONE]${UI_RST}"
            status_desc="${UI_DIM}(DRM-Free Standalone)${UI_RST}"
            ;;
    esac

    local run_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$UID}"
    local is_running=false
    local run_pid=""
    if [ -d "$run_dir/active_games" ]; then
        for inf in "$run_dir/active_games"/*.info; do
            [ -f "$inf" ] || continue
            local inf_dir
            inf_dir=$(grep -E '^DIR=' "$inf" 2>/dev/null | head -n 1 | cut -d'=' -f2-)
            if [ "$inf_dir" = "$gdir" ]; then
                local check_pid
                check_pid=$(grep -E '^PID=' "$inf" 2>/dev/null | head -n 1 | cut -d'=' -f2)
                if [ -n "$check_pid" ] && kill -0 "$check_pid" 2>/dev/null; then
                    is_running=true
                    run_pid="$check_pid"
                    break
                fi
            fi
        done
    fi
    if [ "$is_running" = true ]; then
        status_badge="${UI_GREEN}[RUNNING PID:$run_pid]${UI_RST}"
        status_desc="${UI_DIM}(Game window active in background)${UI_RST}"
    fi

    echo "${UI_BOX}╭─ GAME INFORMATION ───────────────────────────────────╮${UI_RST}"
    echo "│ ${UI_BOLD}${title}${UI_RST} ${UI_DIM}(AppID: ${appid})${UI_RST}"
    echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
    echo "  ${UI_CYAN}Status      ${UI_RST}: $status_badge $status_desc"
    echo "  ${UI_CYAN}Directory   ${UI_RST}: ${UI_DIM}$gdir${UI_RST}"
    echo "  ${UI_CYAN}Executable  ${UI_RST}: ${UI_BOLD}$gbin${UI_RST}"

    if [ -f "$gdir/$gbin" ]; then
        local arch_info
        arch_info=$(file -b "$gdir/$gbin" | cut -d',' -f1,2)
        echo "  ${UI_CYAN}Architecture${UI_RST}: ${UI_DIM}$arch_info${UI_RST}"
        local is_win=false
        case "$gbin" in *.exe|*.EXE) is_win=true ;; esac
        if [ "$is_win" = false ] && file -b "$gdir/$gbin" 2>/dev/null | grep -qi "PE32"; then
            is_win=true
        fi
        if [ "$is_win" = true ]; then
            local r_path
            r_path=$(find_runner "$gdir" 2>/dev/null || true)
            if [ -n "$r_path" ]; then
                echo "  ${UI_CYAN}Runner      ${UI_RST}: ${UI_PURPLE}$(basename "$r_path")${UI_RST} ${UI_DIM}($r_path)${UI_RST}"
            else
                echo "  ${UI_CYAN}Runner      ${UI_RST}: ${UI_RED}[MISSING] No Windows runner found (umu-run/Proton/wine)${UI_RST}"
            fi
            echo "  ${UI_CYAN}Prefix      ${UI_RST}: ${UI_DIM}$gdir/pfx (ISOLATED)${UI_RST}"
        else
            echo "  ${UI_CYAN}Runner      ${UI_RST}: ${UI_GREEN}Native Linux${UI_RST} ${UI_DIM}(Direct ELF/Script)${UI_RST}"
        fi
    fi

    echo
    echo "${UI_BOX}╭─ STORAGE & SAVEGAMES ────────────────────────────────╮${UI_RST}"
    if [ -d "$gdir/saves" ]; then
        local save_sz
        save_sz=$(du -sh "$gdir/saves" 2>/dev/null | cut -f1)
        echo "  ${UI_CYAN}Save Path   ${UI_RST}: ${UI_GREEN}./saves${UI_RST} ${UI_DIM}(PORTABLE - ACTIVE | Size: $save_sz)${UI_RST}"
        if [ -d "$gdir/.save_snapshots" ]; then
            local snaps
            snaps=$(ls -d "$gdir/.save_snapshots"/slot* 2>/dev/null | wc -l)
            echo "  ${UI_CYAN}Snapshots   ${UI_RST}: ${UI_BOLD}$snaps active recovery slots${UI_RST}"
        else
            echo "  ${UI_CYAN}Snapshots   ${UI_RST}: ${UI_DIM}0 slots (Auto-created before launch)${UI_RST}"
        fi
    else
        echo "  ${UI_CYAN}Save Path   ${UI_RST}: ${UI_AMBER}Default OS (Global Steam/Home - Not Isolated)${UI_RST}"
        echo "  ${UI_CYAN}Snapshots   ${UI_RST}: ${UI_DIM}Disabled (Requires GBE Fork ./saves)${UI_RST}"
    fi

    if [ -f "$gdir/steam_settings/DLC.txt" ]; then
        local dlc_count
        dlc_count=$(grep -c "=" "$gdir/steam_settings/DLC.txt" 2>/dev/null || echo 0)
        echo "  ${UI_CYAN}DLC State   ${UI_RST}: ${UI_GREEN}$dlc_count items unlocked (Full DLC)${UI_RST}"
    fi
    echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"

    echo
    echo "${UI_BOX}╭─ RUNTIME WRAPPERS & PERFORMANCE ─────────────────────╮${UI_RST}"
    local w_gm="${UI_DIM}[N/A]${UI_RST}" w_hud="${UI_DIM}[N/A]${UI_RST}" w_scope="${UI_DIM}[N/A]${UI_RST}"
    command -v gamemoderun >/dev/null 2>&1 && w_gm="${UI_GREEN}[READY]${UI_RST}"
    command -v mangohud >/dev/null 2>&1 && w_hud="${UI_GREEN}[READY]${UI_RST}"
    command -v gamescope >/dev/null 2>&1 && w_scope="${UI_GREEN}[READY]${UI_RST}"
    echo "  ${UI_CYAN}Host Tools  ${UI_RST}: GameMode $w_gm • MangoHud $w_hud • Gamescope $w_scope"

    local act_w=()
    local c_gm=0 c_hud=0 c_scope=0 c_fsr=0 c_glt=0
    if [ -f "$HOME/.config/gamectl/wrappers" ]; then
        grep -q "^gamemode=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && c_gm=1
        grep -q -E "^(hud|mangohud)=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && c_hud=1
        grep -q "^gamescope=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && c_scope=1
        grep -q "^fsr=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && c_fsr=1
        grep -q -E "^(glthread|mesa_glthread)=1" "$HOME/.config/gamectl/wrappers" 2>/dev/null && c_glt=1
    fi
    if [ -f "$gdir/.wrappers" ]; then
        grep -q "^gamemode=1" "$gdir/.wrappers" 2>/dev/null && c_gm=1
        grep -q "^gamemode=0" "$gdir/.wrappers" 2>/dev/null && c_gm=0
        grep -q -E "^(hud|mangohud)=1" "$gdir/.wrappers" 2>/dev/null && c_hud=1
        grep -q -E "^(hud|mangohud)=0" "$gdir/.wrappers" 2>/dev/null && c_hud=0
        grep -q "^gamescope=1" "$gdir/.wrappers" 2>/dev/null && c_scope=1
        grep -q "^gamescope=0" "$gdir/.wrappers" 2>/dev/null && c_scope=0
        grep -q "^fsr=1" "$gdir/.wrappers" 2>/dev/null && c_fsr=1
        grep -q "^fsr=0" "$gdir/.wrappers" 2>/dev/null && c_fsr=0
        grep -q -E "^(glthread|mesa_glthread)=1" "$gdir/.wrappers" 2>/dev/null && c_glt=1
        grep -q -E "^(glthread|mesa_glthread)=0" "$gdir/.wrappers" 2>/dev/null && c_glt=0
    fi
    [ "$c_gm" = 1 ] && act_w+=("GameMode")
    [ "$c_hud" = 1 ] && act_w+=("MangoHud")
    [ "$c_scope" = 1 ] && act_w+=("Gamescope")
    [ "$c_fsr" = 1 ] && act_w+=("FSR")
    [ "$c_glt" = 1 ] && act_w+=("MesaGL")
    if [ ${#act_w[@]} -gt 0 ]; then
        echo "  ${UI_CYAN}Game Profile${UI_RST}: ${UI_BOLD}${act_w[*]}${UI_RST}"
    else
        echo "  ${UI_CYAN}Game Profile${UI_RST}: ${UI_DIM}Clean Native (Zero Wrappers)${UI_RST}"
    fi
    echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"

    echo
    echo "${UI_BOX}╭─ LAN MULTIPLAYER & IDENTITY ─────────────────────────╮${UI_RST}"
    if [[ "$status" =~ GBE_FORK ]]; then
        local p_info p_name p_id
        p_info=$(get_game_persona "$gdir")
        p_name=$(echo "$p_info" | cut -d'|' -f1)
        p_id=$(echo "$p_info" | cut -d'|' -f2)
        echo "  ${UI_CYAN}Player Name ${UI_RST}: ${UI_BOLD}${p_name:-Player}${UI_RST} ${UI_DIM}(SteamID64: ${p_id:-Default})${UI_RST}"
        if [ -f "$gdir/steam_settings/custom_broadcasts.txt" ]; then
            local bc_count
            bc_count=$(grep -v -E '^[[:space:]]*(#|$)' "$gdir/steam_settings/custom_broadcasts.txt" 2>/dev/null | wc -l)
            echo "  ${UI_CYAN}Broadcast   ${UI_RST}: ${UI_BOLD}$bc_count peers configured${UI_RST}"
        else
            echo "  ${UI_CYAN}Broadcast   ${UI_RST}: ${UI_DIM}Subnet default (127.0.0.1, 255.255.255.255)${UI_RST}"
        fi
    else
        echo "  ${UI_CYAN}GBE State   ${UI_RST}: ${UI_AMBER}[INACTIVE] (Official Steam/DRM binary)${UI_RST}"
        echo "  ${UI_CYAN}Note        ${UI_RST}: ${UI_DIM}Press <CTRL-I> to enable LAN co-op & custom persona${UI_RST}"
    fi
    local total_sz
    total_sz=$(du -sh "$gdir" 2>/dev/null | cut -f1)
    echo "  ${UI_CYAN}Disk Size   ${UI_RST}: ${UI_BOLD}$total_sz${UI_RST}"
    echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"

    echo
    echo "${UI_BOX}╭─ KEYBOARD SHORTCUTS ─────────────────────────────────╮${UI_RST}"
    echo "  ${UI_PILL_ENTER} ${UI_BOLD}Launch Game${UI_RST}       ${UI_PILL_CTRLI} ${UI_BOLD}Inject GBE Fork${UI_RST}"
    echo "  ${UI_PILL_CTRLO} ${UI_BOLD}Setup Wrappers${UI_RST}    ${UI_PILL_CTRLP} ${UI_BOLD}Configure LAN Persona${UI_RST}"
    local rhost
    rhost=$(get_remote_host)
    if [ -n "$rhost" ]; then
        echo "  ${UI_PILL_CTRLS} ${UI_BOLD}Sync to $rhost${UI_RST}   ${UI_PILL_CTRLB} ${UI_BOLD}Manual Save Snapshot${UI_RST}"
    else
        echo "  ${UI_PILL_CTRLS} ${UI_BOLD}Cloud Sync (N/A)${UI_RST}   ${UI_PILL_CTRLB} ${UI_BOLD}Manual Save Snapshot${UI_RST}"
    fi
    echo "  ${UI_PILL_ESC}   ${UI_BOLD}Back to Master Dashboard Hub${UI_RST}"
    echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
    echo "========================================================"
}


# Preview pane generator for Master Dashboard
preview_dashboard() {
    local item_key="${1:-1}"
    local gcount="${2:-}"

    local os_name="Linux"
    if [ -f /etc/os-release ]; then
        os_name=$(grep -E '^PRETTY_NAME=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
    fi
    local kernel_info
    kernel_info=$(uname -sr)

    local disp_info="Headless/Unknown"
    if [ -n "${WAYLAND_DISPLAY:-}" ]; then
        disp_info="Wayland ($WAYLAND_DISPLAY)"
        [ -n "${DISPLAY:-}" ] && disp_info="$disp_info + Xwayland ($DISPLAY)"
    elif [ -n "${DISPLAY:-}" ]; then
        disp_info="X11 ($DISPLAY)"
    fi

    [ -z "$gcount" ] && gcount=$(scan_installed_games 2>/dev/null | wc -l || echo "0")

    local def_runner
    def_runner=$(find_runner "$HOME" 2>/dev/null || true)
    local runner_str="${UI_DIM}[MISSING] Not installed${UI_RST}"
    if [ -n "$def_runner" ]; then
        runner_str="${UI_PURPLE}$(basename "$def_runner")${UI_RST} ${UI_DIM}($def_runner)${UI_RST}"
    fi

    local gbe_l64 gbe_w64
    gbe_l64=$(get_gbe_template "linux" "x64" 2>/dev/null || true)
    gbe_w64=$(get_gbe_template "windows" "x64" 2>/dev/null || true)
    local gbe_status="${UI_GREEN}[READY]${UI_RST}"
    [ -z "$gbe_l64" ] || [ -z "$gbe_w64" ] && gbe_status="${UI_AMBER}[PARTIAL]${UI_RST}"

    local w_gm="${UI_DIM}[N/A]${UI_RST}" w_hud="${UI_DIM}[N/A]${UI_RST}" w_scope="${UI_DIM}[N/A]${UI_RST}"
    command -v gamemoderun >/dev/null 2>&1 && w_gm="${UI_GREEN}[READY]${UI_RST}"
    command -v mangohud >/dev/null 2>&1 && w_hud="${UI_GREEN}[READY]${UI_RST}"
    command -v gamescope >/dev/null 2>&1 && w_scope="${UI_GREEN}[READY]${UI_RST}"

    local dl_status="${UI_RED}[MISSING]${UI_RST}" sls_status="${UI_DIM}[N/A]${UI_RST}"
    if command -v depotdownloader >/dev/null 2>&1 || [ -x "$HOME/.local/share/gamectl/bin/DepotDownloader" ] || [ -x "$HOME/.local/bin/depotdownloader" ]; then
        dl_status="${UI_GREEN}[READY]${UI_RST}"
    fi
    [ -f "$HOME/.config/SLSsteam/config.yaml" ] && sls_status="${UI_GREEN}[READY]${UI_RST}"

    local run_dir="${XDG_RUNTIME_DIR:-/tmp/gamectl-$UID}"
    local active_count=0
    local active_titles=()
    if [ -d "$run_dir/active_games" ]; then
        for inf in "$run_dir/active_games"/*.info; do
            [ -f "$inf" ] || continue
            local a_pid a_title
            a_pid=$(grep -E '^PID=' "$inf" 2>/dev/null | head -n 1 | cut -d'=' -f2)
            a_title=$(grep -E '^TITLE=' "$inf" 2>/dev/null | head -n 1 | cut -d'=' -f2)
            if [ -n "$a_pid" ] && kill -0 "$a_pid" 2>/dev/null; then
                active_count=$((active_count + 1))
                active_titles+=("$a_title [PID:$a_pid]")
            else
                rm -f "$inf" 2>/dev/null || true
            fi
        done
    fi
    local active_desc="${UI_DIM}None${UI_RST}"
    if [ "$active_count" -gt 0 ]; then
        active_desc="${UI_GREEN}$active_count running${UI_RST} ${UI_DIM}(${active_titles[*]})${UI_RST}"
    fi

    echo "${UI_BOX}╭─ GAMECTL SOVEREIGN COCKPIT ───────────────────────────╮${UI_RST}"
    echo "│ ${UI_BOLD}SYSTEM STATUS & HARDWARE RUNTIME${UI_RST}"
    echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
    echo "  ${UI_CYAN}Host OS     ${UI_RST}: ${UI_BOLD}$os_name${UI_RST} ${UI_DIM}($kernel_info)${UI_RST}"
    echo "  ${UI_CYAN}Display     ${UI_RST}: ${UI_BOLD}$disp_info${UI_RST}"
    echo "  ${UI_CYAN}Games Loaded${UI_RST}: ${UI_GREEN}$gcount titles detected${UI_RST}"
    echo "  ${UI_CYAN}Active Game ${UI_RST}: $active_desc"
    echo "  ${UI_CYAN}Win Runner  ${UI_RST}: $runner_str"
    echo "  ${UI_CYAN}GBE Fork    ${UI_RST}: $gbe_status ${UI_DIM}(Linux x64: $([ -n "$gbe_l64" ] && echo "OK" || echo "MISSING") | Win x64: $([ -n "$gbe_w64" ] && echo "OK" || echo "MISSING"))${UI_RST}"
    echo "  ${UI_CYAN}Tooling     ${UI_RST}: GameMode $w_gm • MangoHud $w_hud • Gamescope $w_scope"
    echo "  ${UI_CYAN}Integration ${UI_RST}: DepotDownloader $dl_status • SLSsteam $sls_status"
    echo

    case "$item_key" in
        *1*|*LIBRARY*|*PUSTAKA*)
            echo "${UI_BOX}╭─ SELECTED MODULE ─────────────────────────────────────╮${UI_RST}"
            echo "│ ${UI_BOLD}[01] GAME LIBRARY${UI_RST}"
            echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
            echo "  • Browse installed Native Linux and Windows Proton/Wine games."
            echo "  • One-click launch with runtime wrappers & isolated runner prefix."
            echo "  • Automatic 3-slot savegame snapshot protection before launch."
            echo "  • Action shortcuts: ${UI_CYAN}Ctrl-I${UI_RST} (Inject), ${UI_CYAN}Ctrl-O${UI_RST} (Wrappers), ${UI_CYAN}Ctrl-P${UI_RST} (Persona)."
            ;;
        *2*|*SEARCH*|*PENCARIAN*)
            echo "${UI_BOX}╭─ SELECTED MODULE ─────────────────────────────────────╮${UI_RST}"
            echo "│ ${UI_BOLD}[02] STEAM STORE SEARCH & PROTONDB${UI_RST}"
            echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
            echo "  • Search public Steam Store catalog via official web API."
            echo "  • Instant Linux compatibility tier audit from ProtonDB."
            echo "  • One-click background or foreground headless download."
            ;;
        *3*|*DOWNLOAD*|*UNDUHAN*)
            echo "${UI_BOX}╭─ SELECTED MODULE ─────────────────────────────────────╮${UI_RST}"
            echo "│ ${UI_BOLD}[03] DOWNLOAD MONITOR${UI_RST}"
            echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
            echo "  • Monitor active background DepotDownloader tasks."
            echo "  • Real-time log streaming (tail -f) and stuck process termination."
            ;;
        *4*|*UNLOCK*|*ENTITLE*|*ENTITLEMENT*|*ACF*)
            echo "${UI_BOX}╭─ SELECTED MODULE ─────────────────────────────────────╮${UI_RST}"
            echo "│ ${UI_BOLD}[04] STEAM ENTITLEMENT & ACF ADOPTION ENGINE${UI_RST}"
            echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
            echo "  • Adopt local files, community Steam Input gyro/touchpad & Vulkan shaders."
            echo "  • Register AppID & full DLC entitlements directly to SLSsteam."
            echo "  • Generate appmanifest_<appid>.acf automatically without downloading."
            ;;
        *5*|*CONFIG*|*SETTINGS*|*KONFIGURASI*)
            echo "${UI_BOX}╭─ SELECTED MODULE ─────────────────────────────────────╮${UI_RST}"
            echo "│ ${UI_BOLD}[05] GLOBAL CONFIGURATION${UI_RST}"
            echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
            echo "  • Manage global LAN Persona (Player Name & default SteamID64)."
            echo "  • Set default runtime wrappers (GameMode, MangoHud, Gamescope FSR)."
            echo "  • Configure additional library paths & remote companion sync host."
            ;;
        *6*|*DOCTOR*|*AUDIT*|*DIAGNOSTICS*|*DIAGNOSTIK*)
            echo "${UI_BOX}╭─ SELECTED MODULE ─────────────────────────────────────╮${UI_RST}"
            echo "│ ${UI_BOLD}[06] SYSTEM DIAGNOSTICS (HEALTH AUDIT)${UI_RST}"
            echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
            echo "  • Verify 7-layer system readiness: CLI tools, runners, drivers, templates."
            echo "  • Early detection of GPU hardware limitations & Mesa driver advice."
            ;;
        *)
            echo "${UI_BOX}╭─ NAVIGATION INSTRUCTIONS ─────────────────────────────╮${UI_RST}"
            echo "  Select a module from the left panel using arrow keys or numbers."
            echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
            ;;
    esac
    echo
    echo "${UI_BOX}╭─ HUB CONTROLS ────────────────────────────────────────╮${UI_RST}"
    echo "  ${UI_PILL_ENTER} ${UI_BOLD}Open Selected Module${UI_RST}    ${UI_PILL_ESC} ${UI_BOLD}Exit / Close gamectl${UI_RST}"
    echo "${UI_BOX}╰───────────────────────────────────────────────────────╯${UI_RST}"
}

# Master Dashboard Hub (Two-Panel Interactive TUI)
dashboard_menu() {
    clean_stale_locks

    while true; do
        local game_count
        game_count=$(scan_installed_games 2>/dev/null | wc -l || echo "0")

        local menu_entries
        menu_entries=$(cat <<EOF
1	${UI_PURPLE}[01]${UI_RST} ${UI_BOLD}GAME LIBRARY${UI_RST}	${UI_DIM}Browse, inject and launch installed games${UI_RST}
2	${UI_PURPLE}[02]${UI_RST} ${UI_BOLD}STEAM STORE SEARCH${UI_RST}	${UI_DIM}Search games & check ProtonDB compatibility${UI_RST}
3	${UI_PURPLE}[03]${UI_RST} ${UI_BOLD}DOWNLOAD MONITOR${UI_RST}	${UI_DIM}Track background DepotDownloader logs${UI_RST}
4	${UI_PURPLE}[04]${UI_RST} ${UI_BOLD}STEAM ENTITLEMENT & ACF${UI_RST}	${UI_DIM}Adopt files, Steam Input & shaders (Full DLC)${UI_RST}
5	${UI_PURPLE}[05]${UI_RST} ${UI_BOLD}GLOBAL SETTINGS${UI_RST}	${UI_DIM}Configure LAN persona, default wrappers & remote host${UI_RST}
6	${UI_PURPLE}[06]${UI_RST} ${UI_BOLD}SYSTEM DIAGNOSTICS${UI_RST}	${UI_DIM}Audit 7-layer dependencies, runners & GPU health${UI_RST}
EOF
)

        local selection
        selection=$(echo "$menu_entries" | fzf \
            --delimiter=$'\t' \
            --with-nth=2,3 \
            --border-label="  ╢ gamectl :: Master Dashboard Hub ╟  " \
            --border-label-pos=2 \
            --header="MASTER DASHBOARD (Arrows/Numbers: Select │ Enter: Open │ Esc: Exit)" \
            --prompt="Dashboard > " \
            --preview="$SELF_BIN --preview-dashboard {1} $game_count" \
            --preview-window=right:55%:border-rounded:wrap \
        ) || break

        local sel_key
        sel_key=$(echo "$selection" | awk -F'\t' '{print $1}')

        case "$sel_key" in
            1)
                library_menu false
                ;;
            2)
                search_steam
                ;;
            3)
                list_downloads_interactive
                ;;
            4)
                unlock_interactive
                ;;
            5)
                configure_global
                ;;
            6)
                doctor_audit
                read -r -p "Press [ENTER] to return to Dashboard..."
                ;;
            *)
                break
                ;;
        esac
    done
}

# Main Library View
library_menu() {
    local standalone="${1:-false}"
    clean_stale_locks

    while true; do
        local selection
        selection=$(scan_installed_games --formatted | fzf \
            --delimiter=$'\t' \
            --with-nth=1,2,3 \
            --border-label="  ╢ gamectl :: Game Library ╟  " \
            --border-label-pos=2 \
            --header=$'GAME LIBRARY (Enter: Launch │ Esc: Dashboard Hub)\nShortcuts: Ctrl-F (Search Store) │ Ctrl-D (Downloads) │ Ctrl-I (Inject GBE) │ Ctrl-O (Wrappers) │ Ctrl-P (LAN ID) │ Ctrl-S (Sync) │ Ctrl-B (Backup)' \
            --prompt="Library > " \
            --preview="$SELF_BIN --preview {1} {2} {3} {4} {5}" \
            --preview-window=right:55%:border-rounded:wrap \
            --bind="ctrl-f:execute($SELF_BIN --search)+reload($SELF_BIN list-formatted)" \
            --bind="ctrl-d:execute($SELF_BIN downloads)+reload($SELF_BIN list-formatted)" \
            --bind="ctrl-o:execute($SELF_BIN configure-wrappers {4} {2})+reload($SELF_BIN list-formatted)" \
            --bind="ctrl-p:execute($SELF_BIN set-id-interactive {4} {2})+reload($SELF_BIN list-formatted)" \
            --bind="ctrl-i:execute($SELF_BIN inject {4} {1}; $SELF_BIN sync-steam {1} {2} {4}; bash -c 'read -n 1 -s -r -p \"Press any key to return to library...\"')+reload($SELF_BIN list-formatted)" \
            --bind="ctrl-s:execute($SELF_BIN --sync {4} {2}; bash -c 'read -n 1 -s -r -p \"Press any key to continue...\"')" \
            --bind="ctrl-b:execute($SELF_BIN --backup {4}; bash -c 'read -n 1 -s -r -p \"Press any key to continue...\"')" \
        ) || break

        if [ -n "$selection" ]; then
            local sel_dir sel_bin sel_title
            sel_dir=$(echo "$selection" | awk -F'\t' '{print $4}')
            sel_bin=$(echo "$selection" | awk -F'\t' '{print $5}')
            sel_title=$(echo "$selection" | awk -F'\t' '{print $2}')
            local launch_rc=0
            launch_game "$sel_dir" "$sel_bin" "$sel_title" || launch_rc=$?
            if [ "$launch_rc" -eq 10 ]; then
                # User selected return directly to Master Dashboard
                break
            fi
        fi
    done

    if [ "$standalone" = "true" ]; then
        dashboard_menu
    fi
}

# Live Steam Search View (Actionable TUI Search)
search_steam() {
    local query_raw=""
    query_raw=$(echo "Search Steam Store catalog (Type title and press ENTER)" | fzf \
        --print-query \
        --border-label="  ╢ gamectl :: Steam Store Search ╟  " \
        --border-label-pos=2 \
        --header="Type game title to search (Enter: Search │ Esc: Cancel)" \
        --prompt="Search Store > " \
        --height=20% \
        --reverse 2>/dev/null) || return 0

    local query
    query=$(echo "$query_raw" | head -n 1 | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    [ -z "$query" ] && return 0

    echo "[INFO] Searching '$query' on Steam Store API..."
    local encoded_query
    encoded_query=$(python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))" "$query")
    local raw_results
    raw_results=$(curl -s --connect-timeout 5 "https://store.steampowered.com/api/storesearch/?term=${encoded_query}&l=english&cc=US" 2>/dev/null)

    local items
    items=$(echo "$raw_results" | jq -r '.items[]? | "\(.id)\t\(.name)"' 2>/dev/null || true)

    if [ -z "$items" ]; then
        echo "[INFO] Game not found."
        sleep 1
        return
    fi

    # Build list with local installed status across all libraries via scan_installed_games
    local results=""
    declare -A installed_by_id=()
    declare -A installed_by_title=()
    declare -A installed_dir=()

    local sc_id sc_name sc_st sc_dir sc_bin
    while IFS=$'\t' read -r sc_id sc_name sc_st sc_dir sc_bin; do
        sc_id="${sc_id//[[:space:]]/}"
        sc_name="${sc_name#"${sc_name%%[![:space:]]*}"}"
        sc_name="${sc_name%"${sc_name##*[![:space:]]}"}"
        sc_dir="${sc_dir//$'\r'/}"
        if [ -n "$sc_id" ] && [ "$sc_id" != "STANDALONE" ]; then
            installed_by_id["$sc_id"]=1
            installed_dir["$sc_id"]="$sc_dir"
        fi
        if [ -n "$sc_name" ]; then
            local clean_title="${sc_name,,}"
            installed_by_title["$clean_title"]=1
            [ -z "${installed_dir["$clean_title"]:-}" ] && installed_dir["$clean_title"]="$sc_dir"
        fi
    done < <(scan_installed_games)

    while IFS=$'\t' read -r appid name; do
        [ -z "$appid" ] && continue
        local is_installed=0
        local clean_name="${name,,}"
        if [[ -v installed_by_id["$appid"] ]] || [[ -v installed_by_title["$clean_name"] ]]; then
            is_installed=1
        fi
        local status="${UI_DIM}[NOT INSTALLED]${UI_RST}"
        [ "$is_installed" -eq 1 ] && status="${UI_GREEN}[INSTALLED]    ${UI_RST}"
        results+="${appid}"$'\t'"${name}"$'\t'"${status}"$'\n'
    done <<< "$items"

    while true; do
        local fzf_out
        fzf_out=$(echo -n "$results" | fzf \
            --delimiter=$'\t' \
            --with-nth=1,2,3 \
            --expect=ctrl-a,ctrl-u,ctrl-s,ctrl-d \
            --bind="ctrl-a:accept,ctrl-u:accept,ctrl-s:accept,ctrl-d:accept" \
            --border-label="  ╢ gamectl :: Steam Store Catalog ╟  " \
            --border-label-pos=2 \
            --header="STEAM CATALOG (Enter: Actions │ Ctrl-A: All-in-One │ Ctrl-U: Entitle │ Ctrl-S: Standalone │ Esc: Back)" \
            --prompt="Steam Store > " \
            --preview='
                appid={1}
                title={2}
                status={3}
                echo -e "\033[38;5;60m╭─ STEAM METADATA & PROTONDB AUDIT ───────────────────╮\033[0m"
                echo -e "│ \033[1m$title\033[0m \033[38;5;244m(AppID: $appid)\033[0m"
                echo -e "\033[38;5;60m╰─────────────────────────────────────────────────────╯\033[0m"
                echo -e "  \033[1;38;5;117mLocal State\033[0m : $status"
                details=$(fetch_cached_json "https://store.steampowered.com/api/appdetails?appids=$appid&filters=platforms,genres" "steam_details_$appid" 3600 2>/dev/null | jq -r ".\"$appid\".data // empty" 2>/dev/null)
                if [ -n "$details" ]; then
                    is_linux=$(echo "$details" | jq -r ".platforms.linux // false" 2>/dev/null)
                    is_win=$(echo "$details" | jq -r ".platforms.windows // false" 2>/dev/null)
                    genres=$(echo "$details" | jq -r "[.genres[]?.description] | join(\", \")" 2>/dev/null)
                    [ -n "$genres" ] && echo -e "  \033[1;38;5;117mGenres     \033[0m : \033[38;5;244m$genres\033[0m"
                    if [ "$is_linux" = "true" ]; then
                        echo -e "  \033[1;38;5;117mPlatform   \033[0m : \033[1;38;5;120mNative Linux ELF available\033[0m"
                    elif [ "$is_win" = "true" ]; then
                        echo -e "  \033[1;38;5;117mPlatform   \033[0m : \033[1;38;5;141mWindows PE (Requires Proton/Wine)\033[0m"
                    fi
                fi
                echo
                echo -e "\033[38;5;60m╭─ COMMUNITY COMPATIBILITY ───────────────────────────╮\033[0m"
                pdb=$(fetch_cached_json "https://www.protondb.com/api/v1/reports/summaries/$appid.json" "protondb_$appid" 3600 2>/dev/null)
                if [ -n "$pdb" ] && [ "$pdb" != "null" ]; then
                    tier=$(echo "$pdb" | jq -r ".tier // \"Unknown\"" 2>/dev/null)
                    score=$(echo "$pdb" | jq -r ".score // \"-\"" 2>/dev/null)
                    conf=$(echo "$pdb" | jq -r ".confidence // \"-\"" 2>/dev/null)
                    tier_upper="${tier^^}"
                    c_tier="\033[1;38;5;120m[$tier_upper]\033[0m"
                    case "$tier_upper" in
                        *PLATINUM*) c_tier="\033[1;38;5;153m[PLATINUM]\033[0m" ;;
                        *GOLD*)     c_tier="\033[1;38;5;221m[GOLD]\033[0m" ;;
                        *SILVER*)   c_tier="\033[1;38;5;248m[SILVER]\033[0m" ;;
                        *BRONZE*)   c_tier="\033[1;38;5;173m[BRONZE]\033[0m" ;;
                        *BORKED*)   c_tier="\033[1;38;5;203m[BORKED]\033[0m" ;;
                    esac
                    echo -e "  \033[1;38;5;117mProtonDB Tier \033[0m: $c_tier"
                    echo -e "  \033[1;38;5;117mRating Score  \033[0m: \033[1m$score\033[0m \033[38;5;244m(Confidence: $conf)\033[0m"
                else
                    echo -e "  \033[1;38;5;117mProtonDB Tier \033[0m: \033[38;5;244m[NO REPORTS YET]\033[0m"
                fi
                echo -e "\033[38;5;60m╰─────────────────────────────────────────────────────╯\033[0m"
            ' \
            --preview-window=right:52%:border-rounded:wrap \
        ) || break

        local trigger_key selection
        trigger_key=$(echo "$fzf_out" | sed -n '1p')
        selection=$(echo "$fzf_out" | sed -n '2,$p')

        [ -z "$selection" ] && continue

        local sel_id sel_name sel_status
        sel_id=$(echo "$selection" | awk -F'\t' '{print $1}')
        sel_name=$(echo "$selection" | awk -F'\t' '{print $2}')
        sel_status=$(echo "$selection" | awk -F'\t' '{print $3}')

        local gdir=""
        local clean_sel_name="${sel_name,,}"
        if [[ "$sel_status" =~ INSTALLED ]] && [[ ! "$sel_status" =~ NOT ]]; then
            if [ -n "${installed_dir["$sel_id"]:-}" ] && [ -d "${installed_dir["$sel_id"]}" ]; then
                gdir="${installed_dir["$sel_id"]}"
            elif [ -n "${installed_dir["$clean_sel_name"]:-}" ] && [ -d "${installed_dir["$clean_sel_name"]}" ]; then
                gdir="${installed_dir["$clean_sel_name"]}"
            elif [ -d "$HOME/Games/$sel_name" ]; then
                gdir="$HOME/Games/$sel_name"
            fi
        fi

        # Resolve optimal destination library and target OS platform for uninstalled games
        local dest_dir target_os="linux"
        if [[ ! "$sel_status" =~ INSTALLED ]] || [[ "$sel_status" =~ NOT ]]; then
            dest_dir="$(resolve_target_library_dir "$sel_name")"
            target_os="$(detect_app_platform_os "$sel_id")"
        fi

        # Direct hotkey triggers
        if [ "$trigger_key" = "ctrl-a" ]; then
            if [[ "$sel_status" =~ INSTALLED ]] && [[ ! "$sel_status" =~ NOT ]]; then
                echo "[INFO] Shortcut <Ctrl-A>: Injecting GBE + Syncing Steam for $sel_name..."
                inject_game "$gdir" "$sel_id"
            else
                echo "[INFO] Shortcut <Ctrl-A>: Starting All-in-One Background Download for $sel_name ($target_os)..."
                download_game "$sel_id" "$dest_dir" "$sel_name" --all --background --os "$target_os"
            fi
            sleep 1.2
        elif [ "$trigger_key" = "ctrl-u" ]; then
            if [[ "$sel_status" =~ INSTALLED ]] && [[ ! "$sel_status" =~ NOT ]]; then
                echo "[INFO] Shortcut <Ctrl-U>: Synchronizing Steam Entitlement & ACF for $sel_name..."
                sync_steam "$sel_id" "$sel_name" "$gdir"
            else
                echo "[INFO] Shortcut <Ctrl-U>: Adopting Steam Entitlement & ACF for $sel_name..."
                unlock_game "$sel_id" "$sel_name"
            fi
            sleep 1.2
        elif [ "$trigger_key" = "ctrl-s" ]; then
            if [[ "$sel_status" =~ INSTALLED ]] && [[ ! "$sel_status" =~ NOT ]]; then
                echo "[INFO] Shortcut <Ctrl-S>: Injecting Standalone GBE Fork for $sel_name..."
                inject_game "$gdir" "$sel_id" --no-sync
            else
                echo "[INFO] Shortcut <Ctrl-S>: Starting Standalone Background Download for $sel_name ($target_os)..."
                download_game "$sel_id" "$dest_dir" "$sel_name" --inject-only --background --os "$target_os"
            fi
            sleep 1.2
        elif [ "$trigger_key" = "ctrl-d" ]; then
            if [[ "$sel_status" =~ INSTALLED ]] && [[ ! "$sel_status" =~ NOT ]]; then
                local gbin
                gbin=$(find_game_binary "$gdir" 2>/dev/null || echo "")
                if [ -n "$gbin" ]; then
                    local launch_rc=0
                    launch_game "$gdir" "$gbin" "$sel_name" || launch_rc=$?
                    if [ "$launch_rc" -eq 10 ]; then
                        break
                    fi
                else
                    echo "[ERROR] Binary executable not found in $gdir."
                    sleep 1.2
                fi
            else
                echo "[INFO] Shortcut <Ctrl-D>: Starting All-in-One Live Stream Download for $sel_name ($target_os)..."
                download_game "$sel_id" "$dest_dir" "$sel_name" --all --foreground --os "$target_os"
            fi
        else
            # Enter key: Open Modal Action Palette
            if [[ "$sel_status" =~ INSTALLED ]] && [[ ! "$sel_status" =~ NOT ]]; then
                local action_palette
                action_palette=$(cat <<EOF
1	Launch Game Directly
2	Inject GBE Fork Only (Standalone ./saves & DLC.txt)
3	Inject GBE + Sync Steam Client (All-in-One Full DLC)
4	Sync to Steam Client Entitlement Only (ACF & Steam Input)
5	Cancel / Return
EOF
)
                local action_sel
                action_sel=$(echo "$action_palette" | fzf \
                    --delimiter=$'\t' \
                    --with-nth=2 \
                    --border-label="  ╢ Action Palette: $sel_name ╟  " \
                    --border-label-pos=2 \
                    --header="ACTION PALETTE (Enter: Execute │ Esc: Return)" \
                    --prompt="Action > " \
                    --height=40% \
                    --reverse 2>/dev/null) || action_sel="5"

                local act_opt
                act_opt=$(echo "$action_sel" | awk -F'\t' '{print $1}')

                case "$act_opt" in
                    1)
                        local gbin
                        gbin=$(find_game_binary "$gdir" 2>/dev/null || echo "")
                        if [ -n "$gbin" ]; then
                            local launch_rc=0
                            launch_game "$gdir" "$gbin" "$sel_name" || launch_rc=$?
                            if [ "$launch_rc" -eq 10 ]; then
                                break
                            fi
                        else
                            echo "[ERROR] Binary executable not found in $gdir."
                            sleep 1.2
                        fi
                        ;;
                    2)
                        inject_game "$gdir" "$sel_id" --no-sync
                        ;;
                    3)
                        inject_game "$gdir" "$sel_id"
                        ;;
                    4)
                        sync_steam "$sel_id" "$sel_name" "$gdir"
                        ;;
                    *)
                        ;;
                esac
            else
                local not_installed_palette
                not_installed_palette=$(cat <<EOF
1	[All-in-One] Download + Inject GBE + Sync Steam (Background)
2	[All-in-One] Download + Inject GBE + Sync Steam (Live Stream)
3	[Standalone] Download + Inject GBE only (Steam-free)
4	[Steam Entitlement & ACF] Adopt files, Steam Input & Shaders (Full DLC)
5	[Raw Download] Download raw depot assets only
6	Cancel / Return
EOF
)
                local pkg_sel
                pkg_sel=$(echo "$not_installed_palette" | fzf \
                    --delimiter=$'\t' \
                    --with-nth=2 \
                    --border-label="  ╢ Action Palette: $sel_name ╟  " \
                    --border-label-pos=2 \
                    --header="PACKAGE SELECTION (Enter: Execute │ Esc: Return)" \
                    --prompt="Package > " \
                    --height=45% \
                    --reverse 2>/dev/null) || pkg_sel="6"

                local opt
                opt=$(echo "$pkg_sel" | awk -F'\t' '{print $1}')
                case "$opt" in
                    1)
                        download_game "$sel_id" "$dest_dir" "$sel_name" --all --background --os "$target_os"
                        ;;
                    2)
                        download_game "$sel_id" "$dest_dir" "$sel_name" --all --foreground --os "$target_os"
                        ;;
                    3)
                        download_game "$sel_id" "$dest_dir" "$sel_name" --inject-only --background --os "$target_os"
                        ;;
                    4)
                        unlock_game "$sel_id" "$sel_name"
                        ;;
                    5)
                        download_game "$sel_id" "$dest_dir" "$sel_name" --raw --background --os "$target_os"
                        ;;
                    *)
                        ;;
                esac
            fi
        fi
    done
}


# --- [MODULE] src/main.sh ---
# Export functions for subshells in fzf
export -f preview_game sync_save_remote sync_to_companion sync_to_tuf backup_save inject_game fetch_dlc download_game ensure_downloader resolve_target_library_dir detect_app_platform_os sync_steam list_downloads list_downloads_interactive unlock_game unlock_interactive entitle_game entitle_interactive adopt_steam get_remote_host get_gbe_template find_game_binary find_runner get_wineserver_bin launch_game game_controller_hud is_haswell_gpu get_native_resolution get_default_gamescope_args get_steam_root get_steam_primary_apps get_steam_libraries build_wrapper_command configure_wrappers configure_global doctor_audit cli_launch generate_steamid64 resolve_active_steamid get_game_persona set_id set_id_interactive preview_dashboard dashboard_menu scan_installed_games detect_dll_overrides setup_onlinefix proton_list proton_install proton_remove manage_prefix query_protondb create_desktop_entry get_steam_grid_dir fetch_steam_artwork get_steam_shortcuts_vdf add_steam_shortcut check_steam_active fetch_cached_json check_systemd_scope_support detect_dgpu_vendor build_sandbox_command

# Top-level Menu
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
case "${1:-}" in
    proton-list|proton)
        proton_list
        ;;
    proton-install)
        proton_install "${2:-latest}" "${@:3}"
        ;;
    proton-remove)
        if [ -n "${2:-}" ]; then
            proton_remove "$2" "${@:3}"
        else
            echo "Usage: gamectl proton-remove <tag> [-y|--yes]"
            exit 1
        fi
        ;;
    mod-overrides|onlinefix|onlinefix-setup)
        if [ -n "${2:-}" ]; then
            setup_onlinefix "$2" "${@:3}"
        else
            echo "Usage: gamectl mod-overrides <game_dir> [--yes|-y] (alias: onlinefix)"
            exit 1
        fi
        ;;
    detect-overrides|dll-overrides)
        if [ -n "${2:-}" ]; then
            detect_dll_overrides "$2" "${3:-}"
        else
            echo "Usage: gamectl detect-overrides <game_dir> [existing_overrides]"
            exit 1
        fi
        ;;
    pfx|prefix)
        if [ -n "${2:-}" ]; then
            manage_prefix "$2" "${3:-}" "${@:4}"
        else
            echo "Usage: gamectl pfx <game_dir> [winecfg|regedit|cmd|shell|kill|clean|winetricks] [args...]"
            exit 1
        fi
        ;;
    protondb|pdb)
        if [ -n "${2:-}" ]; then
            query_protondb "$2"
        else
            echo "Usage: gamectl protondb <appid|game_dir>"
            exit 1
        fi
        ;;
    make-desktop|desktop-entry)
        if [ -n "${2:-}" ]; then
            create_desktop_entry "$2" "${3:-}"
        else
            echo "Usage: gamectl make-desktop <game_dir> [title]"
            exit 1
        fi
        ;;
    fetch-art|fetch-artwork|get-art)
        if [ -n "${2:-}" ]; then
            fetch_steam_artwork "$2" "${3:-}"
        else
            echo "Usage: gamectl fetch-art <game_dir|appid> [appid]"
            exit 1
        fi
        ;;
    get-steam-grid)
        get_steam_grid_dir
        ;;
    add-to-steam|add-steam|shortcut-steam)
        if [ -n "${2:-}" ]; then
            add_steam_shortcut "$2" "${3:-}"
        else
            echo "Usage: gamectl add-to-steam <game_dir> [title]"
            exit 1
        fi
        ;;
    get-steam-shortcuts)
        get_steam_shortcuts_vdf
        ;;
    dashboard|menu|--dashboard)
        dashboard_menu
        ;;
    library|list-ui)
        library_menu true
        ;;
    config|config-global|configure)
        configure_global
        ;;
    doctor|audit)
        doctor_audit
        ;;
    check-scope|systemd-scope)
        if check_systemd_scope_support; then
            echo "[INFO] cgroups v2 / systemd-run user scope isolation is supported and active."
            exit 0
        else
            echo "[WARN] cgroups v2 / systemd-run user scope isolation is not supported on this host."
            exit 1
        fi
        ;;
    detect-gpu|gpu-detect|dgpu)
        vend="$(detect_dgpu_vendor)"
        echo "[INFO] Detected secondary discrete GPU vendor: $vend"
        if [ "$vend" != "none" ]; then
            exit 0
        else
            exit 1
        fi
        ;;
    check-sandbox|sandbox-check)
        if command -v bwrap >/dev/null 2>&1; then
            echo "[INFO] bubblewrap (bwrap) is installed and available for security sandboxing."
            exit 0
        else
            echo "[WARN] bubblewrap (bwrap) is not found in PATH."
            exit 1
        fi
        ;;
    --preview-dashboard)
        preview_dashboard "${2:-1}" "${3:-}"
        ;;
    set-id)
        if [ -n "${2:-}" ]; then
            set_id "${@:2}"
        else
            echo "Usage: gamectl set-id <player_name> [steamid] [game_dir] [--broadcast <ip>] [--global]"
            exit 1
        fi
        ;;
    generate-steamid)
        generate_steamid64
        ;;
    get-gamescope-args)
        get_default_gamescope_args
        ;;
    get-resolution)
        get_native_resolution
        ;;
    get-steam-root)
        get_steam_root
        ;;
    get-steam-libraries|steam-libs)
        get_steam_libraries
        ;;
    get-wineserver)
        get_wineserver_bin "${2:-}"
        ;;
    resolve-library|get-target-library)
        resolve_target_library_dir "${2:-game}"
        ;;
    detect-os)
        detect_app_platform_os "${2:-}"
        ;;
    check-steam|check-steam-active)
        check_steam_active "${2:-Manual check}"
        ;;
    cache-json|fetch-cached-json)
        fetch_cached_json "${2:-}" "${3:-}" "${4:-3600}"
        ;;
    set-id-interactive)
        if [ -n "${2:-}" ]; then
            set_id_interactive "$2" "${3:-}"
        else
            echo "Usage: gamectl set-id-interactive <game_dir> [title]"
            exit 1
        fi
        ;;
    launch|run|--launch)
        if [ -n "${2:-}" ]; then
            cli_launch "${@:2}"
        else
            echo "Usage: gamectl launch <game_dir> [binary] [title] [--hud] [--gamemode] [--gamescope] [--fsr]"
            exit 1
        fi
        ;;
    configure-wrappers)
        if [ -n "${2:-}" ]; then
            configure_wrappers "$2" "${3:-}"
        else
            echo "Usage: gamectl configure-wrappers <game_dir> [title]"
            exit 1
        fi
        ;;
    inject|--inject)
        if [ -n "${2:-}" ]; then
            inject_game "$2" "${3:-}" "${4:-all}"
        else
            echo "Usage: gamectl inject <game_dir> [appid] [--no-sync|--all]"
            exit 1
        fi
        ;;
    fetch-dlc|--fetch-dlc)
        if [ -n "${2:-}" ]; then
            fetch_dlc "$2" "${3:-}"
        else
            echo "Usage: gamectl fetch-dlc <game_dir> [appid]"
            exit 1
        fi
        ;;
    download|--download)
        if [ -n "${2:-}" ]; then
            download_game "$2" "${@:3}"
        else
            echo "Usage: gamectl download <appid> [dir] [title] [--raw|--inject-only|--all] [--foreground|-f] [--os <linux|windows|all>]"
            exit 1
        fi
        ;;
    unlock|add-steam|entitle|adopt-steam|--unlock|--entitle)
        if [ -n "${2:-}" ]; then
            unlock_game "$2" "${3:-}"
        else
            if [ -t 0 ]; then
                unlock_interactive
            else
                echo "Usage: gamectl entitle <appid> [title] (aliases: unlock, adopt-steam)"
                exit 1
            fi
        fi
        ;;
    downloads|--downloads)
        if [ -t 0 ]; then
            list_downloads_interactive
        else
            list_downloads
        fi
        ;;
    sync-steam|--sync-steam)
        if [ -n "${2:-}" ]; then
            sync_steam "$2" "${3:-}" "${4:-}"
        else
            echo "Usage: gamectl sync-steam <appid> [title] [game_dir]"
            exit 1
        fi
        ;;
    ensure-downloader)
        ensure_downloader
        ;;
    --preview)
        preview_game "${2:-}" "${3:-}" "${4:-}" "${5:-}" "${6:-}"
        ;;
    --backup)
        if [ -n "${2:-}" ]; then
            backup_save "$2"
        fi
        ;;
    --search)
        search_steam
        ;;
    --sync|sync|sync-remote|sync-companion|sync-tuf)
        if [ -n "${2:-}" ]; then
            sync_save_remote "$2" "${3:-Game}" "${4:-}"
        else
            echo "Usage: gamectl --sync <game_dir> [title] [remote_host]"
        fi
        ;;
    --list)
        scan_installed_games
        ;;
    list-formatted|--list-formatted)
        scan_installed_games --formatted
        ;;
    --version|-v)
        echo "gamectl v1.2.1 (sovereign native TUI)"
        ;;
    --help|-h)
        cat <<EOF
gamectl - Sovereign TUI Game Manager & Launcher (Zero-Bloat)

Usage:
  gamectl [menu]      Open Master Dashboard Hub TUI (alias: dashboard)
  gamectl library     Open Game Library TUI directly (alias: list-ui)
  gamectl config      Open global configuration menu (~/.config/gamectl/) (alias: configure)
  gamectl doctor      Run 7-layer system & GPU health diagnostics (alias: audit)
  gamectl launch <dir> [bin] [title] [--hud] [--gamemode] [--gamescope] [--fsr] [--glthread] [--scope|--no-scope] [--prime|--no-prime] [--sandbox|--no-sandbox]
                      Launch game with isolated prefix and runtime wrapper options
  gamectl configure-wrappers <dir> [title]
                      Configure per-game wrappers (GameMode/MangoHud/Gamescope FSR/MesaGL)
  gamectl download <appid> [dir] [title] [--raw|--inject-only|--all] [-f] [--os <linux|windows|all>]
                      Headless game downloader via DepotDownloader
  gamectl downloads   Monitor active & recent download processes
  gamectl entitle <appid> [title]
                      Adopt local assets, Steam Input & shaders via Steam entitlement & ACF (aliases: unlock, adopt-steam)
  gamectl unlock <appid> [title] (Alias for entitle)
  gamectl inject <dir> [appid] [--no-sync|--all]
                      Inject decentralized LAN runtime & portable saves
  gamectl mod-overrides <dir>
                      Setup P2P multiplayer compatibility & mod DLL overrides (alias: onlinefix)
  gamectl onlinefix <dir> (Alias for mod-overrides)
  gamectl proton-list List local & latest upstream GE-Proton releases
  gamectl proton-install [tag|latest] Headless GE-Proton installer
  gamectl proton-remove <tag> Safely remove an installed GE-Proton version
  gamectl pfx <dir> [action] [args...]
                      Wine prefix Swiss Army knife (winecfg/regedit/cmd/shell/kill/clean/winetricks)
  gamectl protondb <appid|dir>
                      Query ProtonDB community rating & launch recommendations
  gamectl make-desktop <dir> [title]
                      Generate FreeDesktop .desktop application shortcut
  gamectl add-to-steam <dir> [title]
                      Register standalone game as non-Steam shortcut in Steam Deck Game Mode
  gamectl fetch-art <dir|appid> [appid]
                      Download official Steam capsule, banner, hero, & logo artwork
  gamectl set-id <player> [steamid] [dir] [--broadcast <ip>] [--global]
                      Configure LAN player name & SteamID for offline co-op
  gamectl fetch-dlc <dir> [appid] Fetch & generate steam_settings/DLC.txt
  gamectl sync-steam <appid> [title] [dir] Sync Steam Client & SLSsteam entitlements
  gamectl get-resolution Print detected native display resolution
  gamectl get-gamescope-args Print dynamically scaled Gamescope FSR parameters
  gamectl get-steam-root   Print detected active Steam root directory
  gamectl get-steam-libraries Print all detected Steam library folders
  gamectl detect-gpu       Audit and print detected secondary discrete GPU vendor
  gamectl check-scope      Check if cgroups v2 / systemd-run user scope isolation is supported
  gamectl check-sandbox    Check if bubblewrap (bwrap) rootless security sandbox is available
  gamectl --search    Search Steam Store catalog & audit ProtonDB rating
  gamectl --list      Print detected installed games list
  gamectl list-formatted  Print formatted games list with ANSI badges
  gamectl --sync <dir> [title] [host]  Sync saves to remote companion host
  gamectl --backup <dir>        Create manual savegame backup snapshot
  gamectl --help      Show this help documentation
  gamectl --version   Print active version
EOF
        ;;
    *)
        dashboard_menu
        ;;
esac
fi

