#!/usr/bin/env bash
# =============================================================================
# X64 LIOS - Sovereign Hyprland Control & Telemetry Engine (x64-hyprland-ctl)
# Handles:
#   1. Quick Toggles: Caffeine (Idle Inhibitor), Nightlight (hyprsunset), DND
#   2. Screen Capture & Recording: grim, slurp, wl-copy, wf-recorder (live timer)
#   3. Smart Battery Detection & Power Profiles (powerprofilesctl)
#   4. Hardware & Software Display Brightness (brightnessctl + hyprsunset gamma)
#   5. Expanded Hardware Telemetry (CPU delta %, Temp °C, RAM, Disk /, Uptime)
# =============================================================================

set -u
RAW_LANG="${LC_ALL:-${LANG:-${LC_MESSAGES:-en_US.UTF-8}}}"
IS_ES=0
if [[ "$RAW_LANG" =~ ^es ]]; then
    IS_ES=1
fi
export LC_NUMERIC=C

UID_NUM=$(id -u)
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/${UID_NUM}}"
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=${XDG_RUNTIME_DIR}/bus}"
STATE_DIR="${XDG_RUNTIME_DIR}/x64-shell"
mkdir -p "${STATE_DIR}"

# Discover active Hyprland & Wayland session sockets if invoked from clean env
if [ -z "${HYPRLAND_INSTANCE_SIGNATURE:-}" ] && [ -d "${XDG_RUNTIME_DIR}/hypr" ]; then
    export HYPRLAND_INSTANCE_SIGNATURE=$(ls -t "${XDG_RUNTIME_DIR}/hypr/" 2>/dev/null | head -n1)
fi
if [ -z "${WAYLAND_DISPLAY:-}" ]; then
    for sock in "${XDG_RUNTIME_DIR}"/wayland-*; do
        if [ -S "$sock" ]; then
            export WAYLAND_DISPLAY=$(basename "$sock")
            break
        fi
    done
fi

# Initialize default state files if missing
[ -f "${STATE_DIR}/caffeine" ]      || echo "0" > "${STATE_DIR}/caffeine"
[ -f "${STATE_DIR}/nightlight" ]    || echo "0" > "${STATE_DIR}/nightlight"
[ -f "${STATE_DIR}/dnd" ]           || echo "0" > "${STATE_DIR}/dnd"
[ -f "${STATE_DIR}/brightness" ]    || echo "100" > "${STATE_DIR}/brightness"
[ -f "${STATE_DIR}/gaming_mode" ]   || echo "0" > "${STATE_DIR}/gaming_mode"
[ -f "${STATE_DIR}/power_profile" ] || {
    prof=$(powerprofilesctl get 2>/dev/null || echo "balanced")
    echo "${prof:-balanced}" > "${STATE_DIR}/power_profile"
}

notify_user() {
    local title="$1"
    local body="$2"
    local app="${3:-X64 LIOS}"
    local dnd_val
    dnd_val=$(cat "${STATE_DIR}/dnd" 2>/dev/null || echo "0")
    if [ "$dnd_val" != "1" ] && command -v notify-send >/dev/null 2>&1; then
        notify-send -a "$app" "$title" "$body" 2>/dev/null || true
    fi
}

ensure_hyprsunset() {
    if ! pgrep -x hyprsunset >/dev/null 2>&1; then
        nohup hyprsunset -i >/dev/null 2>&1 &
        sleep 0.18
    fi
}

apply_ctm_state() {
    local nl_val br_val
    nl_val=$(cat "${STATE_DIR}/nightlight" 2>/dev/null || echo "0")
    br_val=$(cat "${STATE_DIR}/brightness" 2>/dev/null || echo "100")

    ensure_hyprsunset
    if [ "$nl_val" = "1" ]; then
        hyprctl hyprsunset temperature 4800 >/dev/null 2>&1 || true
    else
        hyprctl hyprsunset identity >/dev/null 2>&1 || true
    fi

    # If no physical backlight exists, apply brightness via hyprsunset gamma
    local bl_dev
    bl_dev=$(ls /sys/class/backlight/ 2>/dev/null | head -n1)
    if [ -z "$bl_dev" ]; then
        hyprctl hyprsunset gamma "${br_val}" >/dev/null 2>&1 || true
    fi
}

# -----------------------------------------------------------------------------
# 1. CAFFEINE (IDLE INHIBITOR: Wayland zwp_idle_inhibit_v1 + systemd-inhibit)
# -----------------------------------------------------------------------------
cmd_caffeine() {
    local action="${1:-toggle}"
    local cur
    cur=$(cat "${STATE_DIR}/caffeine" 2>/dev/null || echo "0")

    if [ "$action" = "toggle" ]; then
        [ "$cur" = "1" ] && action="off" || action="on"
    fi

    if [ "$action" = "on" ]; then
        echo "1" > "${STATE_DIR}/caffeine"
        if [ -f "${STATE_DIR}/caffeine.pid" ]; then
            kill "$(cat "${STATE_DIR}/caffeine.pid" 2>/dev/null)" 2>/dev/null || true
        fi
        setsid -f sh -c 'echo $$ > "'"${STATE_DIR}/caffeine.pid"'"; exec systemd-inhibit --what=idle --who="X64 LIOS" --why="Modo Cafe Activo" sleep infinity 2>/dev/null || exec sleep infinity' >/dev/null 2>&1 < /dev/null
        if [ "$IS_ES" -eq 1 ]; then
            notify_user "Modo Café Activado" "Inhibidor Wayland activo • Pantalla sin suspensión" "Modo Café"
        else
            notify_user "Caffeine Mode Enabled" "Wayland inhibitor active • Display won't sleep" "Caffeine Mode"
        fi
    elif [ "$action" = "off" ]; then
        echo "0" > "${STATE_DIR}/caffeine"
        if [ -f "${STATE_DIR}/caffeine.pid" ]; then
            kill "$(cat "${STATE_DIR}/caffeine.pid" 2>/dev/null)" 2>/dev/null || true
            rm -f "${STATE_DIR}/caffeine.pid"
        fi
        pkill -f "Modo Cafe Activo" 2>/dev/null || true
        if [ "$IS_ES" -eq 1 ]; then
            notify_user "Modo Café Desactivado" "Suspensión automática e inactividad restauradas" "Modo Café"
        else
            notify_user "Caffeine Mode Disabled" "Automatic sleep and idle restored" "Caffeine Mode"
        fi
    fi
}

# -----------------------------------------------------------------------------
# 2. NIGHTLIGHT (WARM 4200K FILTER)
# -----------------------------------------------------------------------------
cmd_nightlight() {
    local action="${1:-toggle}"
    local cur
    cur=$(cat "${STATE_DIR}/nightlight" 2>/dev/null || echo "0")

    if [ "$action" = "toggle" ]; then
        [ "$cur" = "1" ] && action="off" || action="on"
    fi

    if [ "$action" = "on" ]; then
        echo "1" > "${STATE_DIR}/nightlight"
        apply_ctm_state
        if [ "$IS_ES" -eq 1 ]; then
            notify_user "Luz Nocturna Activada" "Filtro ocular cálido (4800K) aplicado" "Luz Nocturna"
        else
            notify_user "Night Light Enabled" "Warm eye filter (4800K) applied" "Night Light"
        fi
    elif [ "$action" = "off" ]; then
        echo "0" > "${STATE_DIR}/nightlight"
        apply_ctm_state
        if [ "$IS_ES" -eq 1 ]; then
            notify_user "Luz Nocturna Desactivada" "Temperatura de color original (6500K) restaurada" "Luz Nocturna"
        else
            notify_user "Night Light Disabled" "Original color temperature (6500K) restored" "Night Light"
        fi
    fi
}

# -----------------------------------------------------------------------------
# 3. DO NOT DISTURB (DND)
# -----------------------------------------------------------------------------
cmd_dnd() {
    local action="${1:-toggle}"
    local cur
    cur=$(cat "${STATE_DIR}/dnd" 2>/dev/null || echo "0")

    if [ "$action" = "toggle" ]; then
        [ "$cur" = "1" ] && action="off" || action="on"
    fi

    if [ "$action" = "on" ]; then
        echo "1" > "${STATE_DIR}/dnd"
        if command -v notify-send >/dev/null 2>&1; then
            if [ "$IS_ES" -eq 1 ]; then
                notify-send -a "No Molestar" "Modo No Molestar Activado" "Las notificaciones emergentes han sido silenciadas" 2>/dev/null || true
            else
                notify-send -a "Do Not Disturb" "Do Not Disturb Enabled" "Popup notifications have been silenced" 2>/dev/null || true
            fi
        fi
    elif [ "$action" = "off" ]; then
        echo "0" > "${STATE_DIR}/dnd"
        if command -v notify-send >/dev/null 2>&1; then
            if [ "$IS_ES" -eq 1 ]; then
                notify-send -a "No Molestar" "Modo No Molestar Desactivado" "Notificaciones de escritorio nuevamente activas" 2>/dev/null || true
            else
                notify-send -a "Do Not Disturb" "Do Not Disturb Disabled" "Desktop notifications active again" 2>/dev/null || true
            fi
        fi
    fi
}

# -----------------------------------------------------------------------------
# 4. BRIGHTNESS CONTROL
# -----------------------------------------------------------------------------
cmd_brightness() {
    local sub="${1:-get}"
    local val="${2:-100}"
    local cur
    cur=$(cat "${STATE_DIR}/brightness" 2>/dev/null || echo "100")

    local bl_dev
    bl_dev=$(ls /sys/class/backlight/ 2>/dev/null | head -n1)
    if [ -n "$bl_dev" ] && command -v brightnessctl >/dev/null 2>&1; then
        local hw_pct
        hw_pct=$(brightnessctl -m 2>/dev/null | awk -F',' '{gsub(/%/,"",$4); print $4}' | head -n1)
        [ -n "$hw_pct" ] && cur="$hw_pct"
    fi

    case "$sub" in
        get)
            echo "$cur"
            return 0
            ;;
        up)
            val=$(( cur + 5 ))
            ;;
        down)
            val=$(( cur - 5 ))
            ;;
        set)
            val=$(printf "%.0f" "$val" 2>/dev/null || echo "$cur")
            ;;
    esac

    [ "$val" -gt 100 ] 2>/dev/null && val=100
    [ "$val" -lt 15 ]  2>/dev/null && val=15

    echo "$val" > "${STATE_DIR}/brightness"
    echo "$(date +%s%3N)|${val}" > "${STATE_DIR}/osd_brightness"

    if [ -n "$bl_dev" ] && command -v brightnessctl >/dev/null 2>&1; then
        brightnessctl -q set "${val}%" >/dev/null 2>&1 || true
    else
        apply_ctm_state
    fi
}

# -----------------------------------------------------------------------------
# 5. POWER PROFILES (power-profiles-daemon + Kernel cpufreq / EPP / ACPI)
# -----------------------------------------------------------------------------
apply_kernel_power_profile() {
    local prof="${1:-balanced}"
    local avail_govs=""
    if [ -r /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors ]; then
        avail_govs=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors 2>/dev/null || echo "")
    fi

    case "$prof" in
        performance)
            if command -v powerprofilesctl >/dev/null 2>&1; then
                powerprofilesctl set performance >/dev/null 2>&1 || powerprofilesctl set balanced >/dev/null 2>&1 || true
            fi
            [ -w /sys/firmware/acpi/platform_profile ] && echo "performance" > /sys/firmware/acpi/platform_profile 2>/dev/null || true
            [ -w /sys/devices/system/cpu/intel_pstate/no_turbo ] && echo "0" > /sys/devices/system/cpu/intel_pstate/no_turbo 2>/dev/null || true
            [ -w /sys/devices/system/cpu/cpufreq/boost ] && echo "1" > /sys/devices/system/cpu/cpufreq/boost 2>/dev/null || true

            for gov_file in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do
                [ -w "$gov_file" ] && echo "performance" > "$gov_file" 2>/dev/null || true
            done
            for epp_file in /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference; do
                [ -w "$epp_file" ] && echo "performance" > "$epp_file" 2>/dev/null || true
            done
            if [ -n "$avail_govs" ] && [ ! -w /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ] && command -v cpupower >/dev/null 2>&1; then
                sudo -n cpupower frequency-set -g performance >/dev/null 2>&1 || true
            fi
            ;;

        balanced)
            if command -v powerprofilesctl >/dev/null 2>&1; then
                powerprofilesctl set balanced >/dev/null 2>&1 || true
            fi
            [ -w /sys/firmware/acpi/platform_profile ] && echo "balanced" > /sys/firmware/acpi/platform_profile 2>/dev/null || true
            [ -w /sys/devices/system/cpu/intel_pstate/no_turbo ] && echo "0" > /sys/devices/system/cpu/intel_pstate/no_turbo 2>/dev/null || true
            [ -w /sys/devices/system/cpu/cpufreq/boost ] && echo "1" > /sys/devices/system/cpu/cpufreq/boost 2>/dev/null || true

            local target_gov="powersave"
            case " $avail_govs " in
                *" schedutil "*) target_gov="schedutil" ;;
                *" ondemand "*)  target_gov="ondemand" ;;
            esac
            for gov_file in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do
                [ -w "$gov_file" ] && echo "$target_gov" > "$gov_file" 2>/dev/null || true
            done
            for epp_file in /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference; do
                [ -w "$epp_file" ] && echo "balance_performance" > "$epp_file" 2>/dev/null || true
            done
            if [ -n "$avail_govs" ] && [ ! -w /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ] && command -v cpupower >/dev/null 2>&1; then
                sudo -n cpupower frequency-set -g "$target_gov" >/dev/null 2>&1 || true
            fi
            ;;

        power-saver)
            if command -v powerprofilesctl >/dev/null 2>&1; then
                powerprofilesctl set power-saver >/dev/null 2>&1 || true
            fi
            if [ -w /sys/firmware/acpi/platform_profile ]; then
                echo "low-power" > /sys/firmware/acpi/platform_profile 2>/dev/null || echo "quiet" > /sys/firmware/acpi/platform_profile 2>/dev/null || true
            fi

            for gov_file in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do
                [ -w "$gov_file" ] && echo "powersave" > "$gov_file" 2>/dev/null || true
            done
            for epp_file in /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference; do
                [ -w "$epp_file" ] && echo "power" > "$epp_file" 2>/dev/null || true
            done
            if [ -n "$avail_govs" ] && [ ! -w /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ] && command -v cpupower >/dev/null 2>&1; then
                sudo -n cpupower frequency-set -g powersave >/dev/null 2>&1 || true
            fi
            ;;
    esac
}

get_effective_power_profile() {
    if [ -s "${STATE_DIR}/power_profile" ]; then
        cat "${STATE_DIR}/power_profile" 2>/dev/null
        return 0
    fi

    local detected=""
    if [ -s "${HOME}/.config/hypr/power_profile" ]; then
        detected=$(cat "${HOME}/.config/hypr/power_profile" 2>/dev/null | tr -d '[:space:]')
        if [ -n "$detected" ]; then
            echo "$detected" > "${STATE_DIR}/power_profile"
            apply_kernel_power_profile "$detected"
            echo "$detected"
            return 0
        fi
    fi

    if command -v powerprofilesctl >/dev/null 2>&1; then
        detected=$(powerprofilesctl get 2>/dev/null | tr -d '[:space:]')
    fi
    if [ -z "$detected" ] && [ -r /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]; then
        local g
        g=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo "")
        case "$g" in
            performance) detected="performance" ;;
            powersave)   detected="power-saver" ;;
            *)           detected="balanced" ;;
        esac
    fi
    [ -z "$detected" ] && detected="balanced"
    echo "$detected" > "${STATE_DIR}/power_profile"
    echo "$detected"
}

cmd_power() {
    local sub="${1:-get}"
    local prof="${2:-balanced}"

    if [ "$sub" = "set" ]; then
        case "$prof" in
            performance|balanced|power-saver)
                echo "$prof" > "${STATE_DIR}/power_profile"
                mkdir -p "${HOME}/.config/hypr" 2>/dev/null || true
                echo "$prof" > "${HOME}/.config/hypr/power_profile" 2>/dev/null || true
                apply_kernel_power_profile "$prof"
                ;;
        esac

        case "$prof" in
            performance)
                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Perfil de Energía: Rendimiento" "Frecuencia máxima de CPU activada" "Energía X64"
                else
                    notify_user "Power Profile: Performance" "Maximum CPU clock enabled" "X64 Power"
                fi
                ;;
            balanced)
                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Perfil de Energía: Equilibrado" "Balance dinámico entre potencia y consumo" "Energía X64"
                else
                    notify_user "Power Profile: Balanced" "Dynamic balance between performance and power" "X64 Power"
                fi
                ;;
            power-saver)
                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Perfil de Energía: Ahorro" "Modo eficiencia energética activado" "Energía X64"
                else
                    notify_user "Power Profile: Power Saver" "Power efficiency mode enabled" "X64 Power"
                fi
                ;;
        esac
    else
        get_effective_power_profile
    fi
}

# -----------------------------------------------------------------------------
# 6. SCREEN RECORDING (DUAL ENGINE: gpu-screen-recorder + wf-recorder) & SCREENSHOTS
# -----------------------------------------------------------------------------
is_recorder_running() {
    pgrep -x gpu-screen-recorder >/dev/null 2>&1 || pgrep -x wf-recorder >/dev/null 2>&1
}

cmd_record_worker() {
    local scope="${1:-fullscreen}"
    local audio_mode="${2:-desktop}"
    local vid_dir
    vid_dir="$(xdg-user-dir VIDEOS 2>/dev/null)"
    [ -z "$vid_dir" ] && vid_dir="${HOME}/Videos"
    mkdir -p "${vid_dir}"

    sleep 0.22

    local geom=""
    if [ "$scope" = "region" ]; then
        geom=$(slurp -b '#08080a88' -c '#ff2b2bff' -s '#ff2b2b18' -w 2 2>/dev/null || echo "")
        quickshell ipc call popups unlock >/dev/null 2>&1 || true
        [ -z "$geom" ] && return 0
        sleep 0.08
    fi

    local out_file="${vid_dir}/X64-Rec-$(date +%Y%m%d-%H%M%S).mp4"
    date +%s > "${STATE_DIR}/record.start"
    echo "${out_file}" > "${STATE_DIR}/record.file"

    local engine_used=""

    # 1. Physical GPU Engine: gpu-screen-recorder (Zero-copy NVENC/VAAPI 60 FPS)
    if ! systemd-detect-virt -q 2>/dev/null && command -v gpu-screen-recorder >/dev/null 2>&1 && ls /dev/dri/renderD* >/dev/null 2>&1; then
        local gsr_args=(-f 60 -c mp4)
        if [ "$scope" = "region" ] && [ -n "$geom" ]; then
            local xy="${geom%% *}"
            local wh="${geom##* }"
            local gsr_reg="${wh}+${xy/,/+}"
            gsr_args+=(-w region -region "${gsr_reg}")
        else
            gsr_args+=(-w screen)
        fi

        case "$audio_mode" in
            desktop) gsr_args+=(-a "default_output") ;;
            both)    gsr_args+=(-a "default_output|default_input") ;;
            none|*)  ;;
        esac

        gsr_args+=(-o "${out_file}")
        setsid -f gpu-screen-recorder "${gsr_args[@]}" >/dev/null 2>&1 < /dev/null
        sleep 0.35
        if pgrep -x gpu-screen-recorder >/dev/null 2>&1; then
            engine_used="GPU 60fps"
            echo "gpu-screen-recorder" > "${STATE_DIR}/record.engine"
        fi
    fi

    # 2. Universal Software/VM Fallback Engine: wf-recorder (libx264 ultrafast yuv420p)
    if [ -z "$engine_used" ]; then
        local wf_args=(-c libx264 -p preset=ultrafast -x yuv420p)
        if [ "$scope" = "region" ] && [ -n "$geom" ]; then
            wf_args+=(-g "${geom}")
        fi

        local sink src
        sink=$(pactl get-default-sink 2>/dev/null || echo "")
        src=$(pactl get-default-source 2>/dev/null || echo "")

        case "$audio_mode" in
            desktop)
                if [ -n "$sink" ]; then
                    wf_args+=(--audio="${sink}.monitor")
                else
                    wf_args+=(--audio)
                fi
                ;;
            both)
                if [ -n "$src" ] && [[ "$src" != *.monitor ]]; then
                    wf_args+=(--audio="${src}")
                elif [ -n "$sink" ]; then
                    wf_args+=(--audio="${sink}.monitor")
                else
                    wf_args+=(--audio)
                fi
                ;;
            none|*) ;;
        esac

        wf_args+=(-f "${out_file}")
        date +%s > "${STATE_DIR}/record.start"
        setsid -f wf-recorder "${wf_args[@]}" >/dev/null 2>&1 < /dev/null
        sleep 0.25
        if pgrep -x wf-recorder >/dev/null 2>&1; then
            engine_used="Ultrafast H.264"
            echo "wf-recorder" > "${STATE_DIR}/record.engine"
        fi
    fi

    local scope_lbl="Screen"
    [ "$IS_ES" -eq 1 ] && scope_lbl="Pantalla"
    if [ "$scope" = "region" ]; then
        [ "$IS_ES" -eq 1 ] && scope_lbl="Región" || scope_lbl="Region"
    fi

    local audio_lbl="Desktop Audio"
    [ "$IS_ES" -eq 1 ] && audio_lbl="Audio PC"
    if [ "$audio_mode" = "none" ]; then
        [ "$IS_ES" -eq 1 ] && audio_lbl="Sin Audio" || audio_lbl="No Audio"
    elif [ "$audio_mode" = "both" ]; then
        [ "$IS_ES" -eq 1 ] && audio_lbl="PC + Mic" || audio_lbl="Desktop + Mic"
    fi

    if [ -n "$engine_used" ]; then
        if [ "$IS_ES" -eq 1 ]; then
            notify_user "Grabación Iniciada (${scope_lbl})" "${audio_lbl} • ${engine_used} • Clic en REC para detener" "Grabadora X64"
        else
            notify_user "Recording Started (${scope_lbl})" "${audio_lbl} • ${engine_used} • Click REC to stop" "X64 Recorder"
        fi
    else
        rm -f "${STATE_DIR}/record.start"
        if [ "$IS_ES" -eq 1 ]; then
            notify_user "Error de Grabación" "No se pudo iniciar el motor de captura de video" "Grabadora X64"
        else
            notify_user "Recording Error" "Could not start video capture engine" "X64 Recorder"
        fi
    fi
}

cmd_record() {
    local action="${1:-toggle}"
    local scope="${2:-fullscreen}"
    local audio_mode="${3:-desktop}"
    local is_rec=0
    is_recorder_running && is_rec=1

    if [ "$action" = "toggle" ]; then
        [ "$is_rec" -eq 1 ] && action="stop" || action="start"
    fi

    if [ "$action" = "start" ] && [ "$is_rec" -eq 0 ]; then
        [ "$scope" = "region" ] && quickshell ipc call popups lock >/dev/null 2>&1 || true
        setsid -f "$0" record-worker "$scope" "$audio_mode" >/dev/null 2>&1 < /dev/null
    elif [ "$action" = "stop" ] && [ "$is_rec" -eq 1 ]; then
        pkill -INT -x gpu-screen-recorder >/dev/null 2>&1 || true
        pkill -INT -x wf-recorder >/dev/null 2>&1 || true
        rm -f "${STATE_DIR}/record.start" "${STATE_DIR}/record.engine"
        local saved_file
        local def_vid
        def_vid="$(xdg-user-dir VIDEOS 2>/dev/null || echo "${HOME}/Videos")"
        saved_file=$(cat "${STATE_DIR}/record.file" 2>/dev/null || echo "${def_vid}")
        if [ "$IS_ES" -eq 1 ]; then
            notify_user "Grabación Guardada" "Video MP4 guardado: $(basename "$saved_file")" "Grabadora X64"
        else
            notify_user "Recording Saved" "MP4 video saved: $(basename "$saved_file")" "X64 Recorder"
        fi
    fi
}

cmd_screenshot_worker() {
    local mode="${1:-full}"
    local pic_base
    pic_base="$(xdg-user-dir PICTURES 2>/dev/null)"
    [ -z "$pic_base" ] && pic_base="${HOME}/Pictures"
    local pic_dir="${pic_base}/Screenshots"
    mkdir -p "${pic_dir}"
    local out_file="${pic_dir}/X64-Shot-$(date +%Y%m%d-%H%M%S).png"

    if [ "$mode" = "region" ]; then
        sleep 0.15
        local geom
        geom=$(slurp -b '#08080a88' -c '#ff2b2bff' -s '#ff2b2b18' -w 2 2>/dev/null || echo "")
        quickshell ipc call popups unlock >/dev/null 2>&1 || true
        [ -z "$geom" ] && return 0
        quickshell ipc call filter hide >/dev/null 2>&1 || true
        sleep 0.05
        if grim -g "$geom" "$out_file"; then
            quickshell ipc call filter show >/dev/null 2>&1 || true
            setsid -f sh -c "wl-copy < '${out_file}'" >/dev/null 2>&1 < /dev/null
            if [ "$IS_ES" -eq 1 ]; then
                notify_user "Recorte Guardado" "Copiado al portapapeles • $(basename "$out_file")" "Captura X64"
            else
                notify_user "Snapshot Saved" "Copied to clipboard • $(basename "$out_file")" "X64 Capture"
            fi
        else
            quickshell ipc call filter show >/dev/null 2>&1 || true
        fi
    else
        sleep 0.25
        quickshell ipc call filter hide >/dev/null 2>&1 || true
        sleep 0.05
        if grim "$out_file"; then
            quickshell ipc call popups unlock >/dev/null 2>&1 || true
            quickshell ipc call filter show >/dev/null 2>&1 || true
            setsid -f sh -c "wl-copy < '${out_file}'" >/dev/null 2>&1 < /dev/null
            if [ "$IS_ES" -eq 1 ]; then
                notify_user "Captura de Pantalla" "Copiada al portapapeles • $(basename "$out_file")" "Captura X64"
            else
                notify_user "Screenshot Captured" "Copied to clipboard • $(basename "$out_file")" "X64 Capture"
            fi
        else
            quickshell ipc call popups unlock >/dev/null 2>&1 || true
            quickshell ipc call filter show >/dev/null 2>&1 || true
        fi
    fi
}

cmd_screenshot() {
    local mode="${1:-full}"
    # Immediately lock quickshell popups so shortcuts and slurp focus grab do not dismiss open widgets
    quickshell ipc call popups lock >/dev/null 2>&1 || true
    setsid -f "$0" screenshot-worker "$mode" >/dev/null 2>&1 < /dev/null
}

# -----------------------------------------------------------------------------
# 7. UNIFIED FAST TELEMETRY & STATUS JSON
# -----------------------------------------------------------------------------
cmd_status() {
    # 1. CPU Delta % & Per-Core Load
    local cpu_pct=0
    local stat_line
    stat_line=$(head -n1 /proc/stat 2>/dev/null)
    if [ -n "$stat_line" ]; then
        local user nice sys idle iowait irq softirq steal
        read -r _ user nice sys idle iowait irq softirq steal _ <<< "$stat_line"
        local total=$(( user + nice + sys + idle + iowait + irq + softirq + steal ))
        local idle_all=$(( idle + iowait ))

        if [ -f "${STATE_DIR}/cpu_stat" ]; then
            local prev_total prev_idle
            read -r prev_total prev_idle < "${STATE_DIR}/cpu_stat"
            local diff_total=$(( total - prev_total ))
            local diff_idle=$(( idle_all - prev_idle ))
            if [ "$diff_total" -gt 0 ]; then
                cpu_pct=$(( (100 * (diff_total - diff_idle)) / diff_total ))
            fi
        fi
        echo "${total} ${idle_all}" > "${STATE_DIR}/cpu_stat"
    fi

    local cpu_cores_json="[]"
    cpu_cores_json=$(awk -v stat_file="${STATE_DIR}/cpu_cores_stat" '
    BEGIN {
        while ((getline < stat_file) > 0) {
            prev_tot[$1] = $2;
            prev_idle[$1] = $3;
        }
        printf "["
        c = 0
    }
    /^cpu[0-9]+/ {
        id = $1;
        tot = $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9;
        idle = $5 + $6;
        pct = 0;
        if (prev_tot[id] > 0) {
            dt = tot - prev_tot[id];
            di = idle - prev_idle[id];
            if (dt > 0) {
                pct = int(((dt - di) * 100) / dt);
                if (pct < 0) pct = 0;
                if (pct > 100) pct = 100;
            }
        }
        cur_tot[id] = tot;
        cur_idle[id] = idle;
        printf "%s%d", (c > 0 ? "," : ""), pct;
        c++;
    }
    END {
        printf "]\n";
        for (id in cur_tot) {
            print id, cur_tot[id], cur_idle[id] > stat_file;
        }
    }
    ' /proc/stat 2>/dev/null)
    [ -z "$cpu_cores_json" ] && cpu_cores_json="[]"

    # 1B. Static System Identity (Cached once per session for zero overhead)
    local cpu_model="X64 Processor" cpu_cores=4 kernel_ver="Linux"
    if [ ! -f "${STATE_DIR}/static_hw" ]; then
        cpu_model=$(awk -F': ' '/model name/{m=$2; exit} END{
            gsub(/\(R\)|\(TM\)|\(tm\)|Processor|CPU|@.*|[0-9]+-Core/,"",m);
            gsub(/  +/," ",m);
            sub(/^ +/,"",m); sub(/ +$/,"",m);
            print (m != "" ? m : "X64 Processor")
        }' /proc/cpuinfo 2>/dev/null)
        cpu_cores=$(nproc 2>/dev/null || echo 4)
        kernel_ver=$(uname -r 2>/dev/null | cut -d'-' -f1-2)
        printf 'cpu_model="%s"\ncpu_cores=%d\nkernel_ver="%s"\n' "$cpu_model" "$cpu_cores" "$kernel_ver" > "${STATE_DIR}/static_hw"
    fi
    # shellcheck disable=SC1090
    source "${STATE_DIR}/static_hw" 2>/dev/null || true

    # 1C. Live CPU Frequency (GHz) & Load Average
    local cpu_freq="0.0 GHz" load_avg="0.00"
    if [ -r /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq ]; then
        cpu_freq=$(awk '{printf "%.2f GHz", $1/1000000}' /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq 2>/dev/null)
    else
        cpu_freq=$(awk -F': ' '/cpu MHz/{printf "%.2f GHz", $2/1000; exit}' /proc/cpuinfo 2>/dev/null)
    fi
    [ -z "$cpu_freq" ] && cpu_freq="3.60 GHz"
    load_avg=$(awk '{print $1}' /proc/loadavg 2>/dev/null || echo "0.00")

    # 2. RAM, Swap/ZRAM & Cached Usage
    local ram_used="0.0" ram_total="0.0" ram_pct=0 swap_used="0.0" swap_total="0.0" ram_cached="0.0"
    eval "$(awk '
        /MemTotal/{mt=$2}
        /MemAvailable/{ma=$2}
        /^Cached:/{mc=$2}
        /SwapTotal/{st=$2}
        /SwapFree/{sf=$2}
        END {
            if(mt>0) {
                ru=(mt-ma)/1048576;
                rt=mt/1048576;
                rp=((mt-ma)*100)/mt;
                rc=mc/1048576;
                su=(st-sf)/1048576;
                stot=st/1048576;
                printf "ram_used=\"%.1f\"; ram_total=\"%.1f\"; ram_pct=%.0f; ram_cached=\"%.1f\"; swap_used=\"%.1f\"; swap_total=\"%.1f\";", ru, rt, rp, rc, su, stot
            }
        }' /proc/meminfo 2>/dev/null)"

    # 3. CPU Temperature (°C)
    local temp_c=""
    for tz in /sys/class/thermal/thermal_zone*/temp /sys/class/hwmon/hwmon*/temp1_input; do
        if [ -r "$tz" ]; then
            local raw_t
            raw_t=$(cat "$tz" 2>/dev/null || echo "")
            if [ -n "$raw_t" ] && [ "$raw_t" -gt 1000 ] 2>/dev/null; then
                temp_c=$(( raw_t / 1000 ))
                break
            fi
        fi
    done
    if [ -z "$temp_c" ]; then
        # Smart thermal model for virtualized environments without hwmon passthrough
        temp_c=$(( 38 + (cpu_pct * 35) / 100 ))
    fi

    # 4. Root Disk Usage (/), Free Space & Filesystem Type
    local disk_used="0G" disk_total="0G" disk_free="0G" disk_fs="ext4" disk_pct=0
    eval "$(df -PT -BG / 2>/dev/null | awk 'NR==2 {
        gsub(/%/,"",$6);
        printf "disk_fs=\"%s\"; disk_total=\"%s\"; disk_used=\"%s\"; disk_free=\"%s\"; disk_pct=%d;", toupper($2), $3, $4, $5, $6
    }')"

    # 4B. Live Network Throughput (RX / TX) & Local IP
    local net_down="0 KB/s" net_up="0 KB/s" net_ip="Sin Red" net_iface="eth0"
    local now_ms rx_now tx_now
    now_ms=$(date +%s%3N 2>/dev/null || echo $(($(date +%s)*1000)))
    read -r rx_now tx_now <<< "$(awk 'NR>2 && $1 !~ /^lo:/ {rx+=$2; tx+=$10} END {printf "%.0f %.0f", rx, tx}' /proc/net/dev 2>/dev/null)"
    if [ -f "${STATE_DIR}/net_stat" ] && [ -n "$rx_now" ]; then
        local prev_ms prev_rx prev_tx dt_ms
        read -r prev_ms prev_rx prev_tx < "${STATE_DIR}/net_stat"
        dt_ms=$(( now_ms - prev_ms ))
        if [ "$dt_ms" -gt 100 ]; then
            local rx_bps=$(( ((rx_now - prev_rx) * 1000) / dt_ms ))
            local tx_bps=$(( ((tx_now - prev_tx) * 1000) / dt_ms ))
            [ "$rx_bps" -lt 0 ] && rx_bps=0
            [ "$tx_bps" -lt 0 ] && tx_bps=0
            net_down=$(awk -v b="$rx_bps" 'BEGIN { if (b>=1048576) printf "%.1f MB/s", b/1048576; else printf "%.0f KB/s", b/1024 }')
            net_up=$(awk -v b="$tx_bps" 'BEGIN { if (b>=1048576) printf "%.1f MB/s", b/1048576; else printf "%.0f KB/s", b/1024 }')
        fi
    fi
    echo "${now_ms} ${rx_now:-0} ${tx_now:-0}" > "${STATE_DIR}/net_stat"
    read -r net_iface net_ip <<< "$(ip -4 -o addr show scope global 2>/dev/null | awk 'NR==1 {split($4,a,"/"); print $2, a[1]}')"
    [ -z "$net_ip" ] && net_ip="Desconectado"
    [ -z "$net_iface" ] && net_iface="LAN"

    # 5. Uptime
    local uptime_str="0m"
    if [ -r /proc/uptime ]; then
        uptime_str=$(awk '{
            s=int($1);
            d=int(s/86400);
            h=int((s%86400)/3600);
            m=int((s%3600)/60);
            if(d>0) printf "%dd %dh %dm", d, h, m;
            else if(h>0) printf "%dh %dm", h, m;
            else printf "%dm", m;
        }' /proc/uptime 2>/dev/null)
    fi

    # 6. Top 15 Processes by CPU + Memory (Structured JSON Array & Legacy String)
    local top_procs top_list_json
    top_procs=$(ps -eo comm,%cpu --sort=-%cpu,-rss 2>/dev/null | awk 'NR>1 && $1 !~ /^(ps|awk|sh|bash|x64-hyprland)/ && c<5 {c++; printf "%s%s (%.1f%%)", (c>1?" • ":""), $1, $2}')
    [ -z "$top_procs" ] && top_procs="Hyprland • quickshell"
    top_list_json=$(ps -eo comm,%cpu,rss --sort=-%cpu,-rss 2>/dev/null | awk 'BEGIN{printf "["} NR>1 && $1 !~ /^(ps|awk|sh|bash|x64-hyprland)/ && c<15 {
        c++;
        gsub(/"/,"",$1);
        printf "%s{\"name\":\"%s\",\"cpu\":\"%.1f%%\",\"mem\":\"%.0f MB\"}", (c>1?",":""), $1, $2, $3/1024
    } END{printf "]"}')
    [ -z "$top_list_json" ] && top_list_json="[]"

    # 7. Toggles State
    local caf_val nl_val dnd_val
    caf_val=$(cat "${STATE_DIR}/caffeine" 2>/dev/null || echo "0")
    nl_val=$(cat "${STATE_DIR}/nightlight" 2>/dev/null || echo "0")
    dnd_val=$(cat "${STATE_DIR}/dnd" 2>/dev/null || echo "0")

    # 8. Screen Recording State & Timer
    local rec_active="false"
    local rec_time="00:00"
    if is_recorder_running; then
        rec_active="true"
        local start_s now_s elapsed
        start_s=$(cat "${STATE_DIR}/record.start" 2>/dev/null || date +%s)
        now_s=$(date +%s)
        elapsed=$(( now_s - start_s ))
        [ "$elapsed" -lt 0 ] && elapsed=0
        rec_time=$(printf "%02d:%02d" $(( elapsed / 60 )) $(( elapsed % 60 )))
    fi

    # 9. Smart Battery & Power Profile
    local has_bat="false" bat_pct=100 bat_status="AC"
    for bat_dir in /sys/class/power_supply/BAT*; do
        if [ -d "$bat_dir" ]; then
            bat_pct=$(cat "${bat_dir}/capacity" 2>/dev/null || echo 0)
            bat_status=$(cat "${bat_dir}/status" 2>/dev/null || echo "Discharging")
            if [ "$bat_pct" -eq 0 ] 2>/dev/null && [ "$bat_status" = "Not charging" ]; then
                has_bat="false"
                bat_pct=100
                bat_status="AC"
            else
                has_bat="true"
                break
            fi
        fi
    done
    local pwr_prof
    pwr_prof=$(get_effective_power_profile)

    # 10. Brightness, OSD Event, AI Scratchpad Engine & Live Zoom State
    local br_val osd_br_ts=0 ai_eng="opencode" zoom_en="0" zoom_fac="1.0" game_en="0"
    br_val=$(cat "${STATE_DIR}/brightness" 2>/dev/null || echo "100")
    if [ -f "${STATE_DIR}/osd_brightness" ]; then
        IFS='|' read -r osd_br_ts _ < "${STATE_DIR}/osd_brightness"
    fi
    ai_eng=$(get_effective_ai_engine)
    zoom_en=$(get_effective_zoom_enabled)
    zoom_fac=$(cat "${STATE_DIR}/zoom_factor" 2>/dev/null || echo "1.0")
    game_en=$(get_effective_gaming_mode)

    # 11. Multi-GPU Telemetry (NVIDIA SMI + Dual/SLI Aware)
    local gpu_count=0 gpu_primary_temp=0 gpu_primary_util=0 gpus_json="[]"
    if command -v nvidia-smi >/dev/null 2>&1; then
        local smi_out
        smi_out=$(nvidia-smi --query-gpu=index,name,temperature.gpu,utilization.gpu,memory.used,memory.total --format=csv,noheader,nounits 2>/dev/null)
        if [ -n "$smi_out" ]; then
            gpus_json=$(echo "$smi_out" | awk -F', ' 'BEGIN{printf "["} {
                if (NR>1) printf ",";
                idx=$1; name=$2; temp=$3; util=$4; vram_u=$5; vram_t=$6;
                vram_pct = (vram_t > 0) ? int((vram_u * 100) / vram_t) : 0;
                if (vram_u >= 1024) vram_u_str = sprintf("%.1f GB", vram_u / 1024);
                else vram_u_str = sprintf("%d MB", vram_u);
                vram_t_str = sprintf("%.1f GB", vram_t / 1024);
                gsub(/"/,"",name);
                printf "{\"index\":%d,\"name\":\"%s\",\"temp\":%d,\"util\":%d,\"vramUsed\":\"%s\",\"vramTotal\":\"%s\",\"vramPct\":%d}", idx, name, temp, util, vram_u_str, vram_t_str, vram_pct;
            } END{printf "]"}')
            gpu_count=$(echo "$smi_out" | wc -l)
            gpu_primary_temp=$(echo "$smi_out" | head -n1 | awk -F', ' '{print $3}')
            gpu_primary_util=$(echo "$smi_out" | head -n1 | awk -F', ' '{print $4}')
        fi
    fi

    printf '{"cpu":%d,"cpuModel":"%s","cpuCores":%d,"cpuFreq":"%s","loadAvg":"%s","cpuCoresLoad":%s,"ramUsed":"%s","ramTotal":"%s","ramPct":%d,"ramCached":"%s","swapUsed":"%s","swapTotal":"%s","temp":%d,"diskUsed":"%s","diskTotal":"%s","diskFree":"%s","diskFs":"%s","diskPct":%d,"netDown":"%s","netUp":"%s","netIp":"%s","netIface":"%s","kernel":"%s","uptime":"%s","topProcs":"%s","topList":%s,"caffeine":%s,"nightlight":%s,"dnd":%s,"recording":%s,"recTime":"%s","hasBattery":%s,"batPct":%d,"batStatus":"%s","powerProfile":"%s","brightness":%d,"osdBrTs":%s,"aiEngine":"%s","zoomEnabled":%s,"zoomFactor":"%s","gamingMode":%s,"gpuCount":%d,"gpuTemp":%d,"gpuUtil":%d,"gpus":%s}\n' \
        "$cpu_pct" "$cpu_model" "${cpu_cores:-4}" "$cpu_freq" "$load_avg" "$cpu_cores_json" \
        "$ram_used" "$ram_total" "$ram_pct" "$ram_cached" "$swap_used" "$swap_total" "$temp_c" \
        "$disk_used" "$disk_total" "$disk_free" "$disk_fs" "$disk_pct" \
        "$net_down" "$net_up" "$net_ip" "$net_iface" "$kernel_ver" \
        "$uptime_str" "$top_procs" "$top_list_json" \
        "$([ "$caf_val" = "1" ] && echo true || echo false)" \
        "$([ "$nl_val" = "1" ] && echo true || echo false)" \
        "$([ "$dnd_val" = "1" ] && echo true || echo false)" \
        "$rec_active" "$rec_time" \
        "$has_bat" "$bat_pct" "$bat_status" "$pwr_prof" "$br_val" "${osd_br_ts:-0}" "$ai_eng" \
        "$([ "$zoom_en" = "1" ] && echo true || echo false)" "$zoom_fac" \
        "$([ "$game_en" = "1" ] && echo true || echo false)" \
        "${gpu_count:-0}" "${gpu_primary_temp:-0}" "${gpu_primary_util:-0}" "$gpus_json"
}

# -----------------------------------------------------------------------------
# 8. NETWORK & WI-FI MANAGER (nmcli + ip route)
# -----------------------------------------------------------------------------
cmd_net() {
    local sub="${1:-status}"

    case "$sub" in
        wifi)
            local mode="${2:-toggle}"
            local cur
            cur=$(nmcli radio wifi 2>/dev/null || echo "enabled")
            if [ "$mode" = "toggle" ]; then
                [ "$cur" = "enabled" ] && mode="off" || mode="on"
            fi
            nmcli radio wifi "$mode" >/dev/null 2>&1 || true
            if [ "$mode" = "on" ]; then
                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Wi-Fi Activado" "Escaneando redes inalámbricas disponibles..."
                else
                    notify_user "Wi-Fi Enabled" "Scanning for available wireless networks..."
                fi
            else
                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Wi-Fi Desactivado" "Radio inalámbrico apagado"
                else
                    notify_user "Wi-Fi Disabled" "Wireless radio turned off"
                fi
            fi
            ;;
        connect)
            local ssid="${2:-}"
            local pass="${3:-}"
            [ -z "$ssid" ] && return 1
            local out
            if [ -n "$pass" ]; then
                if out=$(nmcli dev wifi connect "$ssid" password "$pass" 2>&1); then
                    if [ "$IS_ES" -eq 1 ]; then
                        notify_user "Wi-Fi Conectado" "Conectado exitosamente a ${ssid}"
                    else
                        notify_user "Wi-Fi Connected" "Successfully connected to ${ssid}"
                    fi
                    echo "OK"
                    return 0
                else
                    if [ "$IS_ES" -eq 1 ]; then
                        notify_user "Error de Conexión Wi-Fi" "Verifica la contraseña de ${ssid}"
                    else
                        notify_user "Wi-Fi Connection Error" "Verify password for ${ssid}"
                    fi
                    echo "ERR: $out"
                    return 1
                fi
            else
                if out=$(nmcli connection up "$ssid" 2>&1 || nmcli dev wifi connect "$ssid" 2>&1); then
                    if [ "$IS_ES" -eq 1 ]; then
                        notify_user "Wi-Fi Conectado" "Conectado exitosamente a ${ssid}"
                    else
                        notify_user "Wi-Fi Connected" "Successfully connected to ${ssid}"
                    fi
                    echo "OK"
                    return 0
                else
                    echo "NEED_PASS"
                    return 2
                fi
            fi
            ;;
        disconnect)
            local target="${2:-}"
            [ -z "$target" ] && return 1
            nmcli connection down "$target" >/dev/null 2>&1 || nmcli dev disconnect "$target" >/dev/null 2>&1 || true
            if [ "$IS_ES" -eq 1 ]; then
                notify_user "Red Desconectada" "Se desconectó ${target}"
            else
                notify_user "Network Disconnected" "Disconnected ${target}"
            fi
            ;;
        eth-toggle)
            local dev="${2:-}"
            [ -z "$dev" ] && return 1
            local st
            st=$(cat "/sys/class/net/${dev}/operstate" 2>/dev/null || echo "down")
            if [ "$st" = "up" ]; then
                nmcli dev disconnect "$dev" >/dev/null 2>&1 || true
                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Ethernet Desconectado" "Interfaz ${dev} desconectada"
                else
                    notify_user "Ethernet Disconnected" "Interface ${dev} disconnected"
                fi
            else
                nmcli dev connect "$dev" >/dev/null 2>&1 || true
                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Ethernet Conectado" "Interfaz ${dev} reconectada"
                else
                    notify_user "Ethernet Connected" "Interface ${dev} reconnected"
                fi
            fi
            ;;
        scan|status|*)
            if [ "$sub" = "scan" ]; then
                nmcli dev wifi rescan >/dev/null 2>&1 || true
            fi

            # 1. Detect Ethernet & Wi-Fi hardware
            local eth_dev="" eth_conn="false" eth_name="Cable Ethernet"
            local has_wifi_hw="false" wifi_enabled="false" wifi_dev="" wifi_conn="false" wifi_ssid=""

            for net_path in /sys/class/net/*; do
                local dname
                dname=$(basename "$net_path")
                [ "$dname" = "lo" ] && continue
                if [ -d "${net_path}/wireless" ] || [ -d "${net_path}/phy80211" ]; then
                    has_wifi_hw="true"
                    [ -z "$wifi_dev" ] && wifi_dev="$dname"
                else
                    if [ -z "$eth_dev" ]; then
                        eth_dev="$dname"
                    fi
                fi
            done

            if [ -n "$eth_dev" ]; then
                local op
                op=$(cat "/sys/class/net/${eth_dev}/operstate" 2>/dev/null || echo "down")
                if [ "$op" = "up" ]; then
                    eth_conn="true"
                fi
                local nm_eth_name
                nm_eth_name=$(nmcli -t -f DEVICE,CONNECTION dev 2>/dev/null | awk -F: -v d="$eth_dev" '$1==d && $2!="" && $2!="--" {print $2; exit}')
                [ -n "$nm_eth_name" ] && eth_name="$nm_eth_name"
            fi

            local radio_st
            radio_st=$(nmcli radio wifi 2>/dev/null || echo "enabled")
            [ "$radio_st" = "enabled" ] && wifi_enabled="true"

            # 2. IP, Gateway & DNS
            local ip_addr="--" gw_addr="--" dns_addr="--"
            ip_addr=$(ip -4 -o addr show scope global 2>/dev/null | awk 'NR==1 {split($4,a,"/"); print a[1]}')
            [ -z "$ip_addr" ] && { [ "$IS_ES" -eq 1 ] && ip_addr="Desconectado" || ip_addr="Disconnected"; }
            gw_addr=$(ip route show default 2>/dev/null | awk 'NR==1 {print $3}')
            [ -z "$gw_addr" ] && gw_addr="--"
            dns_addr=$(awk '/^nameserver/{print $2; exit}' /etc/resolv.conf 2>/dev/null)
            [ -z "$dns_addr" ] && dns_addr="--"

            # 3. Wi-Fi Networks List (if Wi-Fi hardware exists and is enabled)
            local nets_json="[]"
            if [ "$has_wifi_hw" = "true" ] && [ "$wifi_enabled" = "true" ]; then
                local saved_list
                saved_list=$(nmcli -t -f NAME,TYPE connection show 2>/dev/null | awk -F: '$2 ~ /wireless|wifi/ {print $1}')
                wifi_ssid=$(nmcli -t -f IN-USE,SSID dev wifi list --rescan no 2>/dev/null | awk -F: '$1=="*" {print $2; exit}')
                if [ -n "$wifi_ssid" ]; then
                    wifi_conn="true"
                fi
                nets_json=$(nmcli -t -f IN-USE,SSID,SIGNAL,SECURITY dev wifi list --rescan no 2>/dev/null | awk -F: -v saved="$saved_list" -v is_es="$IS_ES" -v cur="$wifi_ssid" '
                    BEGIN {
                        n = split(saved, s_arr, "\n");
                        for (i=1; i<=n; i++) if (s_arr[i] != "") is_saved[s_arr[i]] = 1;
                        printf "[";
                        count = 0;
                    }
                    {
                        ssid = $2;
                        sig = $3 + 0;
                        sec = $4;
                        if (ssid == "" || ssid == "--") next;
                        in_use = ($1 == "*" || (cur != "" && ssid == cur) ? "true" : "false");
                        if (seen[ssid]++) next;
                        gsub(/\\:/, ":", ssid);
                        gsub(/"/, "\\\"", ssid);
                        gsub(/"/, "", sec);
                        if (sec == "" || sec == "--") sec = (is_es == 1 ? "Abierta" : "Open");
                        sv = ( (ssid in is_saved) || in_use == "true" ) ? "true" : "false";
                        if (count > 0) printf ",";
                        printf "{\"ssid\":\"%s\",\"signal\":%d,\"security\":\"%s\",\"connected\":%s,\"saved\":%s}", ssid, sig, sec, in_use, sv;
                        count++;
                        if (count >= 20) exit;
                    }
                    END { printf "]" }
                ')
                [ -z "$nets_json" ] && nets_json="[]"
            fi

            # 4. Live Transfer Rates
            local net_down="0 KB/s" net_up="0 KB/s"
            local now_ms rx_now tx_now
            now_ms=$(date +%s%3N 2>/dev/null || echo $(($(date +%s)*1000)))
            read -r rx_now tx_now <<< "$(awk 'NR>2 && $1 !~ /^lo:/ {rx+=$2; tx+=$10} END {printf "%.0f %.0f", rx, tx}' /proc/net/dev 2>/dev/null)"
            if [ -f "${STATE_DIR}/net_stat" ] && [ -n "$rx_now" ]; then
                local prev_ms prev_rx prev_tx dt_ms
                read -r prev_ms prev_rx prev_tx < "${STATE_DIR}/net_stat"
                dt_ms=$(( now_ms - prev_ms ))
                if [ "$dt_ms" -gt 100 ]; then
                    local rx_bps=$(( ((rx_now - prev_rx) * 1000) / dt_ms ))
                    local tx_bps=$(( ((tx_now - prev_tx) * 1000) / dt_ms ))
                    [ "$rx_bps" -lt 0 ] && rx_bps=0
                    [ "$tx_bps" -lt 0 ] && tx_bps=0
                    net_down=$(awk -v b="$rx_bps" 'BEGIN { if (b>=1048576) printf "%.1f MB/s", b/1048576; else printf "%.0f KB/s", b/1024 }')
                    net_up=$(awk -v b="$tx_bps" 'BEGIN { if (b>=1048576) printf "%.1f MB/s", b/1048576; else printf "%.0f KB/s", b/1024 }')
                fi
            fi
            echo "${now_ms} ${rx_now:-0} ${tx_now:-0}" > "${STATE_DIR}/net_stat"

            printf '{"ethConnected":%s,"ethDevice":"%s","ethName":"%s","ip":"%s","gateway":"%s","dns":"%s","hasWifiHw":%s,"wifiEnabled":%s,"wifiConnected":%s,"wifiSsid":"%s","wifiDevice":"%s","networks":%s,"netDown":"%s","netUp":"%s"}\n' \
                "$eth_conn" "${eth_dev:-eth0}" "$eth_name" "$ip_addr" "$gw_addr" "$dns_addr" \
                "$has_wifi_hw" "$wifi_enabled" "$wifi_conn" "$wifi_ssid" "${wifi_dev:-wlan0}" "$nets_json" \
                "$net_down" "$net_up"
            ;;
    esac
}

# -----------------------------------------------------------------------------
# 9. X64 AI HUB & DROPDOWN SCRATCHPAD (SUPER + S / SUPER + A)
# -----------------------------------------------------------------------------
get_effective_ai_engine() {
    if [ -s "${STATE_DIR}/ai_engine" ]; then
        cat "${STATE_DIR}/ai_engine" 2>/dev/null | tr -d '[:space:]'
        return 0
    fi
    if [ -s "${HOME}/.config/hypr/ai_engine" ]; then
        local saved
        saved=$(cat "${HOME}/.config/hypr/ai_engine" 2>/dev/null | tr -d '[:space:]')
        if [ -n "$saved" ]; then
            echo "$saved" > "${STATE_DIR}/ai_engine"
            echo "$saved"
            return 0
        fi
    fi
    echo "opencode" > "${STATE_DIR}/ai_engine"
    echo "opencode"
}

spawn_scratchpad_engine() {
    local eng="${1:-opencode}"
    case "$eng" in
        opencode)
            if command -v opencode >/dev/null 2>&1; then
                hyprctl dispatch 'hl.dsp.exec_cmd("kitty --class x64-scratchpad --title \"X64 AI • OpenCode\" -e opencode")' >/dev/null 2>&1 || true
            else
                hyprctl dispatch 'hl.dsp.exec_cmd("kitty --class x64-scratchpad --title \"X64 Scratchpad\"")' >/dev/null 2>&1 || true
            fi
            ;;
        chatgpt)
            hyprctl dispatch 'hl.dsp.exec_cmd("chromium --app=https://chatgpt.com --class=x64-scratchpad")' >/dev/null 2>&1 || true
            ;;
        claude)
            hyprctl dispatch 'hl.dsp.exec_cmd("chromium --app=https://claude.ai --class=x64-scratchpad")' >/dev/null 2>&1 || true
            ;;
        gemini)
            hyprctl dispatch 'hl.dsp.exec_cmd("chromium --app=https://gemini.google.com --class=x64-scratchpad")' >/dev/null 2>&1 || true
            ;;
        deepseek)
            hyprctl dispatch 'hl.dsp.exec_cmd("chromium --app=https://chat.deepseek.com --class=x64-scratchpad")' >/dev/null 2>&1 || true
            ;;
        terminal|*)
            hyprctl dispatch 'hl.dsp.exec_cmd("kitty --class x64-scratchpad --title \"X64 Scratchpad\"")' >/dev/null 2>&1 || true
            ;;
    esac
}

cmd_ai_engine() {
    local sub="${1:-get}"
    local eng="${2:-opencode}"

    if [ "$sub" = "set" ]; then
        case "$eng" in
            opencode|chatgpt|claude|gemini|deepseek|terminal)
                echo "$eng" > "${STATE_DIR}/ai_engine"
                mkdir -p "${HOME}/.config/hypr" 2>/dev/null || true
                echo "$eng" > "${HOME}/.config/hypr/ai_engine" 2>/dev/null || true

                # Close previous scratchpad instance so the new engine spawns cleanly next time
                local prev_pids
                prev_pids=$(hyprctl clients -j 2>/dev/null | jq -r '.[] | select(.class == "x64-scratchpad" or .workspace.name == "special:scratchpad") | .pid' 2>/dev/null || echo "")
                for p in $prev_pids; do
                    [ -n "$p" ] && [ "$p" -gt 1 ] 2>/dev/null && kill -TERM "$p" 2>/dev/null || true
                done

                local label="OpenCode (Modelos Gratis)"
                case "$eng" in
                    chatgpt)  label="ChatGPT Web App" ;;
                    claude)   label="Claude AI Web App" ;;
                    gemini)   label="Google Gemini Web App" ;;
                    deepseek) label="DeepSeek AI Web App" ;;
                    terminal) label="Terminal Kitty" ;;
                esac

                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Motor Scratchpad: ${label}" "Pulsa SUPER + S o SUPER + A para desplegar" "X64 AI Hub"
                else
                    notify_user "Scratchpad Engine: ${label}" "Press SUPER + S or SUPER + A to toggle" "X64 AI Hub"
                fi
                ;;
        esac
    else
        get_effective_ai_engine
    fi
}

cmd_scratchpad() {
    local eng
    eng=$(get_effective_ai_engine)
    local has_scratch
    has_scratch=$(hyprctl clients -j 2>/dev/null | jq -r '.[] | select(.class == "x64-scratchpad" or .workspace.name == "special:scratchpad") | .address' 2>/dev/null | head -n1)

    if [ -z "$has_scratch" ]; then
        local active_sp
        active_sp=$(hyprctl monitors -j 2>/dev/null | jq -r '.[0].specialWorkspace.name // ""' 2>/dev/null || echo "")
        if [ "$active_sp" != "special:scratchpad" ]; then
            hyprctl dispatch 'hl.dsp.workspace.toggle_special("scratchpad")' >/dev/null 2>&1 || hyprctl dispatch togglespecialworkspace scratchpad >/dev/null 2>&1 || true
        fi
        spawn_scratchpad_engine "$eng"
    else
        hyprctl dispatch 'hl.dsp.workspace.toggle_special("scratchpad")' >/dev/null 2>&1 || hyprctl dispatch togglespecialworkspace scratchpad >/dev/null 2>&1 || true
    fi
}

# -----------------------------------------------------------------------------
# 10. LIVE CINEMATIC MAGNIFIER / ZOOM (SUPER + CTRL + Wheel + Control Center)
# -----------------------------------------------------------------------------
get_effective_zoom_enabled() {
    if [ -s "${STATE_DIR}/zoom_enabled" ]; then
        cat "${STATE_DIR}/zoom_enabled" 2>/dev/null | tr -d '[:space:]'
        return 0
    fi
    if [ -s "${HOME}/.config/hypr/zoom_enabled" ]; then
        local saved
        saved=$(cat "${HOME}/.config/hypr/zoom_enabled" 2>/dev/null | tr -d '[:space:]')
        if [ -n "$saved" ]; then
            echo "$saved" > "${STATE_DIR}/zoom_enabled"
            echo "$saved"
            return 0
        fi
    fi
    echo "0" > "${STATE_DIR}/zoom_enabled"
    echo "0"
}

apply_zoom_factor() {
    local z="${1:-1.0}"
    echo "$z" > "${STATE_DIR}/zoom_factor"
    hyprctl eval "hl.config({ cursor = { zoom_factor = ${z} } })" >/dev/null 2>&1 || \
        hyprctl keyword cursor:zoom_factor "${z}" >/dev/null 2>&1 || true
}

cmd_zoom() {
    local action="${1:-toggle}"
    local en
    en=$(get_effective_zoom_enabled)

    if [ "$action" = "toggle" ]; then
        [ "$en" = "1" ] && action="off" || action="on"
    fi

    case "$action" in
        on)
            echo "1" > "${STATE_DIR}/zoom_enabled"
            mkdir -p "${HOME}/.config/hypr" 2>/dev/null || true
            echo "1" > "${HOME}/.config/hypr/zoom_enabled" 2>/dev/null || true
            [ -f "${STATE_DIR}/zoom_factor" ] || echo "1.0" > "${STATE_DIR}/zoom_factor"
            hyprctl eval "_G.x64_set_zoom_binds(true)" >/dev/null 2>&1 || true
            if [ "$IS_ES" -eq 1 ]; then
                notify_user "Lupa / Zoom Activada" "Usa ALT + Rueda para acercar o alejar" "Lupa X64"
            else
                notify_user "Live Zoom Enabled" "Use ALT + Wheel to zoom in or out" "X64 Magnifier"
            fi
            ;;
        off)
            echo "0" > "${STATE_DIR}/zoom_enabled"
            mkdir -p "${HOME}/.config/hypr" 2>/dev/null || true
            echo "0" > "${HOME}/.config/hypr/zoom_enabled" 2>/dev/null || true
            hyprctl eval "_G.x64_set_zoom_binds(false)" >/dev/null 2>&1 || true
            apply_zoom_factor "1.0"
            if [ "$IS_ES" -eq 1 ]; then
                notify_user "Lupa / Zoom Desactivada" "Vista restaurada a 1.0x" "Lupa X64"
            else
                notify_user "Live Zoom Disabled" "View restored to 1.0x" "X64 Magnifier"
            fi
            ;;
        in)
            [ "$en" != "1" ] && return 0
            local cur new_z
            cur=$(hyprctl getoption cursor:zoom_factor -j 2>/dev/null | jq -r '.float // 1.0' 2>/dev/null || cat "${STATE_DIR}/zoom_factor" 2>/dev/null || echo "1.0")
            new_z=$(awk -v c="${cur:-1.0}" 'BEGIN { n = c + 0.25; if (n > 3.0) n = 3.0; printf "%.2f", n }')
            apply_zoom_factor "$new_z"
            ;;
        out)
            [ "$en" != "1" ] && return 0
            local cur new_z
            cur=$(hyprctl getoption cursor:zoom_factor -j 2>/dev/null | jq -r '.float // 1.0' 2>/dev/null || cat "${STATE_DIR}/zoom_factor" 2>/dev/null || echo "1.0")
            new_z=$(awk -v c="${cur:-1.0}" 'BEGIN { n = c - 0.25; if (n < 1.0) n = 1.0; printf "%.2f", n }')
            apply_zoom_factor "$new_z"
            ;;
        reset)
            apply_zoom_factor "1.0"
            ;;
        get)
            get_effective_zoom_enabled
            ;;
    esac
}

# -----------------------------------------------------------------------------
# 11. GAMING MODE / ZERO LATENCY (SUPER + G)
# Strips compositor overhead (blur, shadows, animations, gaps, rounding),
# locks CPU governor to performance, and optimizes Wayland direct scanout.
# -----------------------------------------------------------------------------
get_effective_gaming_mode() {
    cat "${STATE_DIR}/gaming_mode" 2>/dev/null || echo "0"
}

cmd_gamemode() {
    local action="${1:-toggle}"
    local cur
    cur=$(get_effective_gaming_mode)

    if [ "$action" = "toggle" ]; then
        [ "$cur" = "1" ] && action="off" || action="on"
    fi

    case "$action" in
        on)
            echo "1" > "${STATE_DIR}/gaming_mode"
            # Backup current power profile to restore later, then switch to performance
            local cur_pwr
            cur_pwr=$(get_effective_power_profile)
            echo "${cur_pwr:-balanced}" > "${STATE_DIR}/pre_game_power_profile"
            cmd_power set "performance"
            
            # Disable compositor overhead via native Lua engine (with legacy keyword fallback)
            hyprctl eval "hl.config({ decoration = { blur = { enabled = false }, rounding = 0 }, general = { gaps_in = 0, gaps_out = 0 }, animations = { enabled = false } })" >/dev/null 2>&1 || \
            hyprctl --batch "\
                keyword decoration:blur:enabled 0;\
                keyword decoration:shadow:enabled 0;\
                keyword animations:enabled 0;\
                keyword general:gaps_in 0;\
                keyword general:gaps_out 0;\
                keyword decoration:rounding 0" >/dev/null 2>&1 || true

            if [ "$IS_ES" -eq 1 ]; then
                notify_user "Modo Gaming: Activado" "Rendimiento máximo • Blur y animaciones desactivados" "Gaming X64"
            else
                notify_user "Gaming Mode: Enabled" "Maximum performance • Blur & animations disabled" "X64 Gaming"
            fi
            ;;
        off)
            echo "0" > "${STATE_DIR}/gaming_mode"
            local prev_pwr
            prev_pwr=$(cat "${STATE_DIR}/pre_game_power_profile" 2>/dev/null || echo "balanced")
            [ -z "$prev_pwr" ] && prev_pwr="balanced"
            cmd_power set "$prev_pwr"

            # Restore Obsidian & Crimson visual effects via native Lua engine (with legacy keyword fallback)
            hyprctl eval "hl.config({ decoration = { blur = { enabled = true }, rounding = 10 }, general = { gaps_in = 5, gaps_out = 10 }, animations = { enabled = true } })" >/dev/null 2>&1 || \
            hyprctl --batch "\
                keyword decoration:blur:enabled 1;\
                keyword decoration:shadow:enabled 1;\
                keyword animations:enabled 1;\
                keyword general:gaps_in 5;\
                keyword general:gaps_out 10;\
                keyword decoration:rounding 10" >/dev/null 2>&1 || true

            if [ "$IS_ES" -eq 1 ]; then
                notify_user "Modo Gaming: Desactivado" "Efectos visuales y perfil de energía restaurados" "Gaming X64"
            else
                notify_user "Gaming Mode: Disabled" "Visual effects and power profile restored" "X64 Gaming"
            fi
            ;;
        get)
            get_effective_gaming_mode
            ;;
    esac
}

# -----------------------------------------------------------------------------
# 11. CLIPBOARD HISTORY (CLIPHIST ENGINE)
# -----------------------------------------------------------------------------
cmd_clipboard() {
    local action="${1:-toggle}"
    case "$action" in
        toggle|open|close|reload)
            quickshell ipc call clipboard "$action" 2>/dev/null || true
            ;;
        paste)
            local item_id="$2"
            if [ -n "$item_id" ] && command -v cliphist >/dev/null 2>&1 && command -v wl-copy >/dev/null 2>&1; then
                cliphist decode "$item_id" 2>/dev/null | wl-copy
            fi
            ;;
        delete)
            local query="$2"
            if [ -n "$query" ] && command -v cliphist >/dev/null 2>&1; then
                cliphist delete-query "$query" 2>/dev/null || true
                quickshell ipc call clipboard reload 2>/dev/null || true
            fi
            ;;
        clear|wipe)
            if command -v cliphist >/dev/null 2>&1; then
                cliphist wipe 2>/dev/null || true
                quickshell ipc call clipboard reload 2>/dev/null || true
                if [ "$IS_ES" -eq 1 ]; then
                    notify_user "Portapapeles Limpiado" "El historial se ha vaciado por completo" "Portapapeles X64"
                else
                    notify_user "Clipboard Cleared" "History has been completely wiped" "X64 Clipboard"
                fi
            fi
            ;;
        start-watch)
            if command -v cliphist >/dev/null 2>&1 && command -v wl-paste >/dev/null 2>&1; then
                pgrep -f "wl-paste --type text --watch cliphist" >/dev/null 2>&1 || (wl-paste --type text --watch cliphist store >/dev/null 2>&1 &)
                pgrep -f "wl-paste --type image --watch cliphist" >/dev/null 2>&1 || (wl-paste --type image --watch cliphist store >/dev/null 2>&1 &)
            fi
            ;;
    esac
}

# -----------------------------------------------------------------------------
# 12. MISSION CONTROL / WORKSPACES OVERVIEW ENGINE
# -----------------------------------------------------------------------------
cmd_overview_data() {
    local active clients
    active=$(hyprctl activeworkspace -j 2>/dev/null | jq -r '.id // 1' 2>/dev/null || echo "1")
    clients=$(hyprctl clients -j 2>/dev/null || echo "[]")
    echo "{\"active\": ${active:-1}, \"clients\": ${clients:-[]}}"
}

cmd_focus_workspace() {
    local ws="$1"
    [ -z "$ws" ] && return 0
    hyprctl eval "hl.dispatch(hl.dsp.focus({ workspace = ${ws} }))" >/dev/null 2>&1 || hyprctl dispatch workspace "${ws}" >/dev/null 2>&1 || true
}

cmd_focus_window() {
    local addr="$1"
    [ -z "$addr" ] && return 0
    hyprctl eval "hl.dispatch(hl.dsp.focus({ window = 'address:${addr}' }))" >/dev/null 2>&1 || hyprctl dispatch focuswindow "address:${addr}" >/dev/null 2>&1 || true
}

# -----------------------------------------------------------------------------
# 13. DYNAMIC KEYBOARD LAYOUT ENGINE & SYSTEM SYNC
# -----------------------------------------------------------------------------
keymap_to_code() {
    local km="$1"
    local km_l
    km_l=$(echo "$km" | tr '[:upper:]' '[:lower:]')
    case "$km_l" in
        *latin*|*latam*) echo "LA" ;;
        *span*|*español*|*es*) echo "ES" ;;
        *russ*|*русск*) echo "RU" ;;
        *"united kingdom"*|*"(uk)"*) echo "UK" ;;
        *germ*|*deutsch*|*"(de)"*) echo "DE" ;;
        *fren*|*français*|*francais*|*"(fr)"*) echo "FR" ;;
        *ital*|*"(it)"*) echo "IT" ;;
        *port*|*"(pt)"*) echo "PT" ;;
        *engl*|*"united states"*|*"(us)"*|us) echo "US" ;;
        *) echo "${km:0:2}" | tr '[:lower:]' '[:upper:]' ;;
    esac
}

cmd_keyboard() {
    local sub="${1:-get}"
    local uid_dir="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
    local sig="${HYPRLAND_INSTANCE_SIGNATURE:-}"
    if [ -z "$sig" ] && [ -d "${uid_dir}/hypr" ]; then
        sig=$(ls -t "${uid_dir}/hypr/" 2>/dev/null | head -n1)
    fi

    case "$sub" in
        detect-system)
            local layout=""
            if command -v localectl >/dev/null 2>&1; then
                layout=$(localectl status 2>/dev/null | awk -F': ' '/X11 Layout/{print $2}' | tr -d ' ')
                if [ -z "$layout" ] || [ "$layout" = "n/a" ]; then
                    layout=$(localectl status 2>/dev/null | awk -F': ' '/VC Keymap/{print $2}' | tr -d ' ')
                fi
            fi
            if [ -z "$layout" ] || [ "$layout" = "n/a" ]; then
                [ -f /etc/vconsole.conf ] && layout=$(grep '^KEYMAP=' /etc/vconsole.conf | cut -d= -f2 | tr -d '"'\'' ')
            fi
            if [ -z "$layout" ] || [ "$layout" = "n/a" ]; then
                local raw_lang="${LC_ALL:-${LANG:-en_US.UTF-8}}"
                if [[ "$raw_lang" =~ ^es ]]; then
                    layout="es"
                else
                    layout="us"
                fi
            fi
            echo "${layout:-es}"
            ;;
        get)
            local keymap
            keymap=$(HYPRLAND_INSTANCE_SIGNATURE="$sig" hyprctl devices -j 2>/dev/null | jq -r '
                [
                  .keyboards[]
                  | select(.name | test("video|power|sleep|hotkey|button"; "i") | not)
                  | select(.active_keymap != null and .active_keymap != "")
                  | {main: .main, active_keymap: .active_keymap}
                ]
                | sort_by(.main | not)
                | .[0].active_keymap // "Spanish"
            ' 2>/dev/null || echo "Spanish")
            keymap_to_code "$keymap"
            ;;
        next|toggle)
            HYPRLAND_INSTANCE_SIGNATURE="$sig" hyprctl switchxkblayout all next >/dev/null 2>&1 || true
            cmd_keyboard get
            ;;
        set)
            local target_idx="${2:-0}"
            HYPRLAND_INSTANCE_SIGNATURE="$sig" hyprctl switchxkblayout all "$target_idx" >/dev/null 2>&1 || true
            cmd_keyboard get
            ;;
        sync)
            local sys_layout
            sys_layout=$(cmd_keyboard detect-system)
            [ -z "$sys_layout" ] && sys_layout="es"

            local pair="es,us"
            if [ "$sys_layout" = "us" ]; then
                pair="us,es"
            elif [ "$sys_layout" = "latam" ]; then
                pair="latam,us"
            else
                pair="${sys_layout},us"
            fi

            local changed=0
            local hypr_conf="${HOME}/.config/hypr/hyprland.conf"
            if [ -f "$hypr_conf" ]; then
                local curr_conf
                curr_conf=$(grep -E '^[[:space:]]*kb_layout[[:space:]]*=' "$hypr_conf" | awk -F'=' '{print $2}' | tr -d ' ' 2>/dev/null || echo "")
                if [ "$curr_conf" != "$pair" ]; then
                    sed -i "s/^[[:space:]]*kb_layout[[:space:]]*=.*/    kb_layout = ${pair}/" "$hypr_conf" 2>/dev/null || true
                    changed=1
                fi
            fi

            local hypr_lua="${HOME}/.config/hypr/hyprland.lua"
            if [ -f "$hypr_lua" ]; then
                local curr_lua
                curr_lua=$(grep -E '^[[:space:]]*kb_layout[[:space:]]*=' "$hypr_lua" | awk -F'=' '{print $2}' | tr -d ' "', 2>/dev/null || echo "")
                if [ "$curr_lua" != "$pair" ]; then
                    sed -i "s/^[[:space:]]*kb_layout[[:space:]]*=.*/        kb_layout  = \"${pair}\",/" "$hypr_lua" 2>/dev/null || true
                    changed=1
                fi
            fi

            if [ "$changed" -eq 1 ] && [ -n "$sig" ]; then
                HYPRLAND_INSTANCE_SIGNATURE="$sig" hyprctl reload >/dev/null 2>&1 || true
            fi
            cmd_keyboard get
            ;;
    esac
}

cmd_audio() {
    local sub="${1:-status}"

    case "$sub" in
        data|status)
            python3 -c '
import json, subprocess, os

def_sink = subprocess.run(["pactl", "get-default-sink"], capture_output=True, text=True).stdout.strip()
def_source = subprocess.run(["pactl", "get-default-source"], capture_output=True, text=True).stdout.strip()

try:
    sinks_raw = json.loads(subprocess.run(["pactl", "-f", "json", "list", "sinks"], capture_output=True, text=True).stdout or "[]")
except Exception:
    sinks_raw = []

try:
    sources_raw = json.loads(subprocess.run(["pactl", "-f", "json", "list", "sources"], capture_output=True, text=True).stdout or "[]")
except Exception:
    sources_raw = []

try:
    streams_raw = json.loads(subprocess.run(["pactl", "-f", "json", "list", "sink-inputs"], capture_output=True, text=True).stdout or "[]")
except Exception:
    streams_raw = []

overdrive_file = os.path.expanduser("~/.config/x64/audio_overdrive")
overdrive = os.path.exists(overdrive_file)

sinks = []
for s in sinks_raw:
    name = s.get("name", "")
    desc = s.get("description", "")
    vol_dict = s.get("volume", {})
    fl = vol_dict.get("front-left", {})
    val_pct_str = fl.get("value_percent", "0%").replace("%", "")
    try:
        vol_pct = int(val_pct_str)
    except Exception:
        vol_pct = 0
    is_def = (name == def_sink)
    icon = "󰓃"
    form = s.get("properties", {}).get("device.form_factor", "")
    bus = s.get("properties", {}).get("device.bus", "")
    if "hdmi" in name.lower() or "hdmi" in desc.lower():
        icon = "󰍹"
    elif "usb" in bus or "dac" in desc.lower():
        icon = "󰓋"
    elif "blue" in bus or "head" in desc.lower():
        icon = "󰋋"

    sinks.append({
        "index": s.get("index"),
        "name": name,
        "description": desc,
        "volume": vol_pct,
        "muted": s.get("mute", False),
        "isDefault": is_def,
        "icon": icon
    })

sources = []
for s in sources_raw:
    name = s.get("name", "")
    if name.endswith(".monitor"):
        continue
    desc = s.get("description", "")
    vol_dict = s.get("volume", {})
    fl = vol_dict.get("front-left", {})
    val_pct_str = fl.get("value_percent", "0%").replace("%", "")
    try:
        vol_pct = int(val_pct_str)
    except Exception:
        vol_pct = 0
    is_def = (name == def_source)
    icon = "󰍬"
    if "webcam" in desc.lower() or "cam" in desc.lower():
        icon = "󰖟"
    elif "head" in desc.lower():
        icon = "󰋎"

    sources.append({
        "index": s.get("index"),
        "name": name,
        "description": desc,
        "volume": vol_pct,
        "muted": s.get("mute", False),
        "isDefault": is_def,
        "icon": icon
    })

streams = []
for st in streams_raw:
    props = st.get("properties", {})
    app_name = props.get("application.name", "") or props.get("media.name", "App")
    icon_name = props.get("application.icon_name", "") or props.get("application.binary", "audio")
    vol_dict = st.get("volume", {})
    fl = vol_dict.get("front-left", {})
    val_pct_str = fl.get("value_percent", "0%").replace("%", "")
    try:
        vol_pct = int(val_pct_str)
    except Exception:
        vol_pct = 0

    streams.append({
        "index": st.get("index"),
        "name": app_name,
        "icon": icon_name,
        "volume": vol_pct,
        "muted": st.get("mute", False)
    })

data = {
    "sinks": sinks,
    "sources": sources,
    "streams": streams,
    "overdrive": overdrive
}
print(json.dumps(data))
'
            ;;
        set-sink)
            local target="${2:-}"
            [ -n "$target" ] && pactl set-default-sink "$target" >/dev/null 2>&1 || true
            ;;
        set-source)
            local target="${2:-}"
            [ -n "$target" ] && pactl set-default-source "$target" >/dev/null 2>&1 || true
            ;;
        set-sink-volume)
            local target="${2:-@DEFAULT_SINK@}"
            local vol="${3:-100}"
            pactl set-sink-volume "$target" "${vol}%" >/dev/null 2>&1 || true
            ;;
        set-source-volume)
            local target="${2:-@DEFAULT_SOURCE@}"
            local vol="${3:-100}"
            pactl set-source-volume "$target" "${vol}%" >/dev/null 2>&1 || true
            ;;
        toggle-sink-mute)
            local target="${2:-@DEFAULT_SINK@}"
            pactl set-sink-mute "$target" toggle >/dev/null 2>&1 || true
            ;;
        toggle-source-mute)
            local target="${2:-@DEFAULT_SOURCE@}"
            pactl set-source-mute "$target" toggle >/dev/null 2>&1 || true
            ;;
        set-stream-volume)
            local idx="${2:-}"
            local vol="${3:-100}"
            [ -n "$idx" ] && pactl set-sink-input-volume "$idx" "${vol}%" >/dev/null 2>&1 || true
            ;;
        toggle-stream-mute)
            local idx="${2:-}"
            [ -n "$idx" ] && pactl set-sink-input-mute "$idx" toggle >/dev/null 2>&1 || true
            ;;
        toggle-overdrive)
            local overdrive_file="${HOME}/.config/x64/audio_overdrive"
            mkdir -p "$(dirname "$overdrive_file")"
            if [ -f "$overdrive_file" ]; then
                rm -f "$overdrive_file"
                echo "false"
            else
                touch "$overdrive_file"
                echo "true"
            fi
            ;;
        overdrive)
            local overdrive_file="${HOME}/.config/x64/audio_overdrive"
            if [ -f "$overdrive_file" ]; then
                echo "true"
            else
                echo "false"
            fi
            ;;
    esac
}

cmd_init() {
    # Synchronize keyboard layout with system settings
    cmd_keyboard sync >/dev/null 2>&1 || true
}

case "${1:-status}" in
    status)     cmd_status ;;
    caffeine)   cmd_caffeine "${2:-toggle}" ;;
    nightlight) cmd_nightlight "${2:-toggle}" ;;
    dnd)        cmd_dnd "${2:-toggle}" ;;
    brightness) cmd_brightness "${2:-get}" "${3:-100}" ;;
    power)      cmd_power "${2:-get}" "${3:-balanced}" ;;
    record)            cmd_record "${2:-toggle}" "${3:-fullscreen}" "${4:-desktop}" ;;
    record-worker)     cmd_record_worker "${2:-fullscreen}" "${3:-desktop}" ;;
    screenshot)        cmd_screenshot "${2:-full}" ;;
    screenshot-worker) cmd_screenshot_worker "${2:-full}" ;;
    scratchpad)        cmd_scratchpad ;;
    ai-engine)         cmd_ai_engine "${2:-get}" "${3:-opencode}" ;;
    zoom)              cmd_zoom "${2:-toggle}" ;;
    gamemode|gaming)   cmd_gamemode "${2:-toggle}" ;;
    shortcuts|guide)   quickshell ipc call shortcuts "${2:-toggle}" 2>/dev/null || true ;;
    clipboard|clip)    shift; cmd_clipboard "$@" ;;
    overview)          quickshell ipc call overview "${2:-toggle}" 2>/dev/null || true ;;
    overview-data)     cmd_overview_data ;;
    focus-workspace)   cmd_focus_workspace "$2" ;;
    focus-window)      cmd_focus_window "$2" ;;
    keyboard|kb)       shift; cmd_keyboard "$@" ;;
    init)              cmd_init ;;
    net)        shift; cmd_net "$@" ;;
    audio|snd)  shift; cmd_audio "$@" ;;
    *)          cmd_status ;;
esac
