#!/usr/bin/env fish
# ==============================================================================
# X64 LIOS - SERVER & RESCUE DASHBOARD (TTY1)
# Official Management Center for Server / CLI Installations and Recovery
# Centro de Mando Oficial para Instalaciones Server / CLI y Recuperación
# ==============================================================================

# Regional localization detection (Default: en_US, Fallback: es_* when $LANG =~ ^es)
set -g is_es 0
if string match -qr '^es' "$LANG"; or string match -qr '^es' "$LC_ALL"; or string match -qr '^es' "$LC_MESSAGES"
    set -g is_es 1
end

# Detection helper: KDE Plasma 6 desktop environment
# (plasma-workspace provides plasmashell and startplasma-wayland for portals, but only plasma-desktop provides the actual full desktop environment)
function is_kde_installed
    test -d /usr/share/plasma/shells/org.kde.plasma.desktop; or pacman -Q plasma-desktop >/dev/null 2>&1; or pacman -Q plasma-workspace >/dev/null 2>&1; or test -f /usr/share/wayland-sessions/plasma.desktop
end

# Detection helper: Active graphical desktop session (Kitty, Konsole, Gnome-Terminal, etc.)
# Returns 0 (true) if running inside a local graphical terminal window (Wayland or X11 without SSH),
# where stopping the display manager or removing active GUI packages would abruptly abort the process.
function is_graphical_session
    if test -n "$SSH_CLIENT"; or test -n "$SSH_TTY"
        return 1
    end
    test -n "$WAYLAND_DISPLAY"; or test -n "$DISPLAY"
end

# Dynamic Detection Helper: Determine the active virtual terminal (VT) of the graphical desktop
function get_graphical_vt
    # 1. Query loginctl for active graphical sessions (Wayland or X11)
    for s in (loginctl list-sessions --no-legend 2>/dev/null | awk '{print $1}')
        set -l s_type (loginctl show-session $s -p Type --value 2>/dev/null)
        set -l s_vt (loginctl show-session $s -p VTNr --value 2>/dev/null)
        if test "$s_type" = "wayland"; or test "$s_type" = "x11"
            if test -n "$s_vt"; and test "$s_vt" -gt 0
                echo $s_vt
                return 0
            end
        end
    end
    # 2. Inspect active graphical processes for assigned tty (startplasma-wayland, Xorg, etc.)
    set -l p_tty (ps -eo tty,args 2>/dev/null | grep -E 'startplasma|kwin|gnome-shell|Xorg' | grep -oE 'tty[0-9]+' | head -n 1 | tr -d 'tty')
    if test -n "$p_tty"; and test "$p_tty" -gt 0
        echo $p_tty
        return 0
    end
    # 3. Fallback to VT1 (standard Wayland user session on Arch Linux)
    echo 1
end

function draw_dashboard
    clear
    # Breathing room for header
    echo ""
    echo ""

    set -l border "\e[1;31m"
    set -l reset "\e[0m"
    set -l title "\e[1;37m"
    set -l val "\e[0;37m"
    set -l warn "\e[1;33m"
    set -l green "\e[1;32m"
    set -l red "\e[1;31m"
    set -l cyan "\e[1;36m"

    # Real-time telemetry
    set -l os_name (cat /etc/os-release 2>/dev/null | grep "^PRETTY_NAME=" | cut -d '=' -f 2 | tr -d '"')
    test -z "$os_name"; and set os_name "X64 LIOS Linux"
    set -l kernel_ver (uname -r)
    set -l host_node (hostname)
    set -l current_time (date '+%Y-%m-%d %H:%M:%S')
    set -l uptime_str (uptime -p | sed 's/up //')
    set -l ip_addr (ip route get 1.1.1.1 2>/dev/null | awk '{print $7}')
    if test -z "$ip_addr"
        set ip_addr (test $is_es -eq 1; and echo "Desconectado"; or echo "Disconnected")
    end
    set -l mem_used (free -m | awk '/Mem:/ {print $3}')
    set -l mem_total (free -m | awk '/Mem:/ {print $2}')
    set -l ram_str "$mem_used MiB / $mem_total MiB"
    set -l disk_free (df -h / | awk 'NR==2 {print $4}')(test $is_es -eq 1; and echo " libres"; or echo " free")

    # Service status
    set -l ssh_status (systemctl is-active sshd 2>/dev/null)
    set -l ufw_status (systemctl is-active ufw 2>/dev/null)

    set -l active_tag (test $is_es -eq 1; and echo "[ ACTIVO ]"; or echo "[ ACTIVE ]")
    set -l inactive_tag (test $is_es -eq 1; and echo "[ INACTIVO ]"; or echo "[ INACTIVE ]")
    set -l ssh_txt (test "$ssh_status" = "active"; and echo "$active_tag"; or echo "$inactive_tag")
    set -l ufw_txt (test "$ufw_status" = "active"; and echo "$active_tag"; or echo "$inactive_tag")
    set -l ssh_color (test "$ssh_status" = "active"; and echo "\e[1;32m"; or echo "\e[1;30m")
    set -l ufw_color (test "$ufw_status" = "active"; and echo "\e[1;32m"; or echo "\e[1;30m")

    # Official X64 LIOS ASCII Logo
    echo -e "$red    ██╗  ██╗ ██████╗ ██╗  ██╗    ██╗     ██╗ ██████╗ ███████╗$reset"
    echo -e "$red    ╚██╗██╔╝██╔════╝ ██║  ██║    ██║     ██║██╔═══██╗██╔════╝$reset"
    echo -e "$red     ╚███╔╝ ███████╗ ███████║    ██║     ██║██║   ██║███████╗$reset"
    echo -e "$red     ██╔██╗ ██╔═══██╗╚════██║    ██║     ██║██║   ██║╚════██║$reset"
    echo -e "$red    ██╔╝ ██╗╚██████╔╝     ██║    ███████╗██║╚██████╔╝███████║$reset"
    echo -e "$red    ╚═╝  ╚═╝ ╚═════╝      ╚═╝    ╚══════╝╚═╝ ╚═════╝ ╚══════╝$reset"
    if test $is_es -eq 1
        echo -e "          $title C O N S O L E   //   C E N T R O   D E   M A N D O$reset\n"
    else
        echo -e "          $title C O N S O L E   //   C O N T R O L   C E N T E R$reset\n"
    end

    # Section 1: System Telemetry
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
    if test $is_es -eq 1
        echo -e "   $title TELEMETRÍA DEL SISTEMA$reset"
    else
        echo -e "   $title SYSTEM TELEMETRY$reset"
    end
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
    set -l lbl_time (test $is_es -eq 1; and echo "[HORA]"; or echo "[TIME]")
    set -l lbl_disk (test $is_es -eq 1; and echo "[DISCO]"; or echo "[DISK]")

    printf "    \e[1;36m%-8s\e[0m \e[0;37m%-24s\e[0m \e[1;36m%-9s\e[0m \e[0;37m%-28s\e[0m\n" "[OS]" "$os_name" "[KERNEL]" "$kernel_ver"
    printf "    \e[1;36m%-8s\e[0m \e[0;37m%-24s\e[0m \e[1;36m%-9s\e[0m \e[0;37m%-28s\e[0m\n" "[HOST]" "$host_node" "[UPTIME]" "$uptime_str"
    printf "    \e[1;36m%-8s\e[0m \e[1;32m%-24s\e[0m \e[1;36m%-9s\e[0m \e[0;37m%-28s\e[0m\n" "[IP]" "$ip_addr" "$lbl_time" "$current_time"
    printf "    \e[1;36m%-8s\e[0m \e[0;37m%-24s\e[0m \e[1;36m%-9s\e[0m \e[0;37m%-28s\e[0m\n" "[RAM]" "$ram_str" "$lbl_disk" "$disk_free"
    printf "    \e[1;36m%-8s\e[0m $ssh_color%-24s\e[0m \e[1;36m%-9s\e[0m $ufw_color%-28s\e[0m\n" "[SSH]" "$ssh_txt" "[UFW]" "$ufw_txt"

    # Section 2: Graphical Environment
    set -g desktop_names
    set -g desktop_dms

    if test (count (pacman -Qq x64-hyprland-settings 2>/dev/null)) -gt 0
        set -a desktop_names "Hyprland (X64 Cyberpunk Edition - Wayland)"
        set -a desktop_dms "sddm"
    end
    if test -d /usr/share/omarchy
        set -a desktop_names "X64 LIOS + Omarchy (Flagship Shell - Wayland)"
        set -a desktop_dms "sddm"
    end
    if type -q gnome-shell
        set -a desktop_names "GNOME (X64 Stealth Edition - Wayland)"
        set -a desktop_dms "gdm"
    end
    if is_kde_installed
        set -a desktop_names "KDE Plasma 6 (X64 Gaming Edition - Wayland)"
        set -a desktop_dms "sddm"
    end
    if type -q cosmic-session
        set -a desktop_names "COSMIC Desktop (Rust Next-Gen - Wayland)"
        set -a desktop_dms "cosmic-greeter"
    end
    if type -q niri-session
        set -a desktop_names (test $is_es -eq 1; and echo "Niri (Scroll-infinito - Wayland)"; or echo "Niri (Infinite Scroll - Wayland)")
        set -a desktop_dms "sddm"
    end
    if type -q cinnamon-session
        set -a desktop_names "Cinnamon (Classic Desktop)"
        set -a desktop_dms "lightdm"
    end
    if type -q xfce4-session
        set -a desktop_names "Xfce4 (Ultra Lightweight)"
        set -a desktop_dms "lightdm"
    end

    # Prioritize currently running graphical session to index 1
    set -l active_de_idx 0
    if pgrep -x plasmashell >/dev/null 2>&1; or pgrep -x kwin_wayland >/dev/null 2>&1
        for i in (seq (count $desktop_names))
            if string match -q "*KDE*" "$desktop_names[$i]"
                set active_de_idx $i
                break
            end
        end
    else if pgrep -x gnome-shell >/dev/null 2>&1
        for i in (seq (count $desktop_names))
            if string match -q "*GNOME*" "$desktop_names[$i]"
                set active_de_idx $i
                break
            end
        end
    else if pgrep -x cosmic-comp >/dev/null 2>&1; or pgrep -x cosmic-session >/dev/null 2>&1
        for i in (seq (count $desktop_names))
            if string match -q "*COSMIC*" "$desktop_names[$i]"
                set active_de_idx $i
                break
            end
        end
    else if pgrep -x niri >/dev/null 2>&1
        for i in (seq (count $desktop_names))
            if string match -q "*Niri*" "$desktop_names[$i]"
                set active_de_idx $i
                break
            end
        end
    else if pgrep -f cinnamon-session >/dev/null 2>&1; or pgrep -x cinnamon >/dev/null 2>&1
        for i in (seq (count $desktop_names))
            if string match -q "*Cinnamon*" "$desktop_names[$i]"
                set active_de_idx $i
                break
            end
        end
    else if pgrep -x xfce4-session >/dev/null 2>&1
        for i in (seq (count $desktop_names))
            if string match -q "*Xfce4*" "$desktop_names[$i]"
                set active_de_idx $i
                break
            end
        end
    else if pgrep -xi Hyprland >/dev/null 2>&1
        for i in (seq (count $desktop_names))
            if test -d /usr/share/omarchy; and string match -q "*Omarchy*" "$desktop_names[$i]"
                set active_de_idx $i
                break
            else if string match -q "*Hyprland*" "$desktop_names[$i]"
                set active_de_idx $i
                break
            end
        end
    end

    if test $active_de_idx -gt 1
        set -l top_name $desktop_names[$active_de_idx]
        set -l top_dm $desktop_dms[$active_de_idx]
        set -e desktop_names[$active_de_idx]
        set -e desktop_dms[$active_de_idx]
        set -p desktop_names "$top_name"
        set -p desktop_dms "$top_dm"
    end

    set -g has_desktop (count $desktop_names)
    set -l dm_active ""
    set -l short_de ""
    if test $has_desktop -gt 0
        set dm_active (systemctl is-active $desktop_dms[1] 2>/dev/null)
        set short_de (string match -r '^[^(]+' "$desktop_names[1]" | string trim)
    end

    echo -e "\n  $border─────────────────────────────────────────────────────────────────────────────$reset"
    if test $is_es -eq 1
        if test "$dm_active" = "active"
            echo -e "   $title ENTORNO GRÁFICO: \e[1;37m$short_de\e[0m \e[1;32m[EN EJECUCIÓN ●]\e[0m$reset"
        else
            echo -e "   $title ENTORNO GRÁFICO$reset"
        end
    else
        if test "$dm_active" = "active"
            echo -e "   $title GRAPHICAL ENVIRONMENT: \e[1;37m$short_de\e[0m \e[1;32m[RUNNING ●]\e[0m$reset"
        else
            echo -e "   $title GRAPHICAL ENVIRONMENT$reset"
        end
    end
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"

    if test $has_desktop -eq 0
        if test $is_es -eq 1
            echo -e "    \e[1;33m[!]\e[0m \e[0;37mNo hay ningún entorno gráfico instalado (Modo Server / CLI puro).\e[0m"
            echo -e "    \e[1;33m[1]\e[0m \e[1;37mInstalar un Entorno de Escritorio Oficial (Hyprland, GNOME, etc.)\e[0m"
        else
            echo -e "    \e[1;33m[!]\e[0m \e[0;37mNo graphical environment installed (Pure Server / CLI Mode).\e[0m"
            echo -e "    \e[1;33m[1]\e[0m \e[1;37mInstall an Official Desktop Environment (Hyprland, GNOME, etc.)\e[0m"
        end
    else
        if test "$dm_active" = "active"
            if test $is_es -eq 1
                printf "    \e[1;32m[1]\e[0m \e[0;37mVolver al Escritorio Gráfico (\e[1;32m%s\e[0m\e[0;37m)\e[0m\n" "$short_de"
                printf "    \e[1;31m[D]\e[0m \e[0;37mDetener Entorno Gráfico y liberar memoria RAM\e[0m\n"
            else
                printf "    \e[1;32m[1]\e[0m \e[0;37mReturn to Graphical Desktop (\e[1;32m%s\e[0m\e[0;37m)\e[0m\n" "$short_de"
                printf "    \e[1;31m[D]\e[0m \e[0;37mStop Graphical Environment and free RAM\e[0m\n"
            end
        else
            if test $is_es -eq 1
                printf "    \e[1;32m[1]\e[0m \e[0;37mIniciar %s\e[0m\n" "$desktop_names[1]"
            else
                printf "    \e[1;32m[1]\e[0m \e[0;37mStart %s\e[0m\n" "$desktop_names[1]"
            end
        end
        if test $is_es -eq 1
            echo -e "    \e[1;33m[I]\e[0m \e[1;37mInstalar o alternar a otro Entorno de Escritorio adicional\e[0m"
        else
            echo -e "    \e[1;33m[I]\e[0m \e[1;37mInstall or switch to another Desktop Environment\e[0m"
        end
    end

    # Section 3: Server & Maintenance Tools
    echo -e "\n  $border─────────────────────────────────────────────────────────────────────────────$reset"
    if test $is_es -eq 1
        echo -e "   $title HERRAMIENTAS DE SERVIDOR Y MANTENIMIENTO$reset"
    else
        echo -e "   $title SERVER & MAINTENANCE TOOLS$reset"
    end
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"

    if test $is_es -eq 1
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m \e[1;36m%-4s\e[0m \e[0;37m%-30s\e[0m\n" "[2]" "Monitor de Recursos (btop)" "[5]" "Diagnóstico y Red Wi-Fi"
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m \e[1;36m%-4s\e[0m \e[0;37m%-30s\e[0m\n" "[3]" "Acceso Remoto SSH y Firewall" "[6]" "Mantenimiento y Limpieza"
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m \e[1;36m%-4s\e[0m \e[0;37m%-30s\e[0m\n" "[4]" "Actualizar Sistema (Pacman)" "[7]" "Diagnóstico de Errores y Boot"
    else
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m \e[1;36m%-4s\e[0m \e[0;37m%-30s\e[0m\n" "[2]" "Resource Monitor (btop)" "[5]" "Network & Wi-Fi Diagnostics"
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m \e[1;36m%-4s\e[0m \e[0;37m%-30s\e[0m\n" "[3]" "Remote SSH & Firewall" "[6]" "Maintenance & Cleanup"
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m \e[1;36m%-4s\e[0m \e[0;37m%-30s\e[0m\n" "[4]" "System Update (Pacman)" "[7]" "Error & Boot Diagnostics"
    end

    # Section 4: System Control
    echo -e "\n  $border─────────────────────────────────────────────────────────────────────────────$reset"
    if test $is_es -eq 1
        echo -e "   $title CONTROL DEL SISTEMA$reset"
    else
        echo -e "   $title SYSTEM CONTROL$reset"
    end
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"

    if test $is_es -eq 1
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m \e[1;36m%-4s\e[0m \e[0;37m%-30s\e[0m\n" "[8]" "Consola Pura (Fish Shell)" "[9]" "Reiniciar el Servidor"
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m\n" "[0]" "Apagar el Servidor"
    else
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m \e[1;36m%-4s\e[0m \e[0;37m%-30s\e[0m\n" "[8]" "Pure Console (Fish Shell)" "[9]" "Reboot System"
        printf "    \e[1;36m%-4s\e[0m \e[0;37m%-32s\e[0m\n" "[0]" "Shut Down System"
    end
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
end

function sanitize_user_dirs_and_configs
    # 1. Sincronizar configuraciones de /etc/skel/.config con sobrescritura para aplicar el tema del nuevo escritorio
    if test -d /etc/skel/.config
        mkdir -p $HOME/.config 2>/dev/null
        cp -rf /etc/skel/.config/. $HOME/.config/ 2>/dev/null
    end

    # 2. Inicializar y reparar directorios XDG según el idioma activo del sistema (evitando XDG_DESKTOP_DIR="$HOME")
    if type -q xdg-user-dirs-update
        xdg-user-dirs-update --force 2>/dev/null
    end

    if test $is_es -eq 1
        mkdir -p $HOME/Escritorio $HOME/Descargas $HOME/Documentos $HOME/Imágenes $HOME/Música $HOME/Plantillas $HOME/Público $HOME/Vídeos 2>/dev/null
        if test -f $HOME/.config/user-dirs.dirs
            sed -i 's|XDG_DESKTOP_DIR="\$HOME/\?"|XDG_DESKTOP_DIR="\$HOME/Escritorio"|g' $HOME/.config/user-dirs.dirs 2>/dev/null
            sed -i 's|XDG_TEMPLATES_DIR="\$HOME/\?"|XDG_TEMPLATES_DIR="\$HOME/Plantillas"|g' $HOME/.config/user-dirs.dirs 2>/dev/null
            sed -i 's|XDG_PUBLICSHARE_DIR="\$HOME/\?"|XDG_PUBLICSHARE_DIR="\$HOME/Público"|g' $HOME/.config/user-dirs.dirs 2>/dev/null
        end

        # 3. Unificar y limpiar carpetas duplicadas en inglés si el sistema está en español
        for pair in "Downloads:Descargas" "Pictures:Imágenes" "Videos:Vídeos" "Documents:Documentos" "Music:Música" "Desktop:Escritorio" "Templates:Plantillas" "Public:Público" "Projects:Proyectos"
            set -l en_dir (string split ":" $pair)[1]
            set -l es_dir (string split ":" $pair)[2]
            if test -d "$HOME/$en_dir"; and test -d "$HOME/$es_dir"
                # Mover cualquier archivo existente sin sobrescribir antes de eliminar el directorio vacío en inglés
                find "$HOME/$en_dir" -mindepth 1 -maxdepth 1 -exec mv -n '{}' "$HOME/$es_dir/" \; 2>/dev/null
                rmdir "$HOME/$en_dir" 2>/dev/null
            end
        end

        # Limpiar marcadores GTK rotos que apunten a carpetas en inglés ya unificadas
        if test -f $HOME/.config/gtk-3.0/bookmarks
            sed -i '/\/Downloads /d; /\/Pictures /d; /\/Videos /d; /\/Projects /d' $HOME/.config/gtk-3.0/bookmarks 2>/dev/null
        end
    else
        mkdir -p $HOME/Desktop $HOME/Downloads $HOME/Documents $HOME/Pictures $HOME/Music $HOME/Templates $HOME/Public $HOME/Videos 2>/dev/null
        if test -f $HOME/.config/user-dirs.dirs
            sed -i 's|XDG_DESKTOP_DIR="\$HOME/\?"|XDG_DESKTOP_DIR="\$HOME/Desktop"|g' $HOME/.config/user-dirs.dirs 2>/dev/null
            sed -i 's|XDG_TEMPLATES_DIR="\$HOME/\?"|XDG_TEMPLATES_DIR="\$HOME/Templates"|g' $HOME/.config/user-dirs.dirs 2>/dev/null
            sed -i 's|XDG_PUBLICSHARE_DIR="\$HOME/\?"|XDG_PUBLICSHARE_DIR="\$HOME/Public"|g' $HOME/.config/user-dirs.dirs 2>/dev/null
        end
    end

    # 4. Purgar cachés de iconos y de Plasma para garantizar carga limpia del tema de iconos activo
    rm -f $HOME/.cache/icon-cache.kcache $HOME/.cache/ksycoca6* 2>/dev/null
    rm -rf $HOME/.cache/plasmashell 2>/dev/null
end

function configure_desktop_boot_mode -a dm_service desktop_name
    sanitize_user_dirs_and_configs
    clear
    echo ""
    echo ""

    set -l border "\e[1;31m"
    set -l reset "\e[0m"
    set -l title "\e[1;37m"

    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
    if test $is_es -eq 1
        echo -e "   $title CONFIGURACIÓN DE ARRANQUE DEL SISTEMA$reset"
    else
        echo -e "   $title SYSTEM BOOT CONFIGURATION$reset"
    end
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"

    if test $is_es -eq 1
        echo -e "    \e[1;32m¡$desktop_name instalado con éxito!\e[0m\n"
        echo -e "    ¿Cómo deseas que arranque este equipo a partir de ahora?\n"
        echo -e "    \e[1;33m[1]\e[0m \e[1;37mModo Servidor / Consola (Recomendado)\e[0m"
        echo -e "        \e[0;37mArrancar siempre en el Centro de Mando TTY1 e iniciar el escritorio bajo demanda.\e[0m\n"
        echo -e "    \e[1;36m[2]\e[0m \e[1;37mModo Escritorio Completo (PC de uso diario)\e[0m"
        echo -e "        \e[0;37mArrancar automáticamente en la pantalla gráfica de inicio de sesión ($dm_service).\e[0m\n"
    else
        echo -e "    \e[1;32m$desktop_name installed successfully!\e[0m\n"
        echo -e "    How would you like this system to boot from now on?\n"
        echo -e "    \e[1;33m[1]\e[0m \e[1;37mServer / Console Mode (Recommended)\e[0m"
        echo -e "        \e[0;37mAlways boot into TTY1 Control Center and start desktop on demand.\e[0m\n"
        echo -e "    \e[1;36m[2]\e[0m \e[1;37mFull Desktop Mode (Daily Driver PC)\e[0m"
        echo -e "        \e[0;37mAutomatically boot into graphical login screen ($dm_service).\e[0m\n"
    end
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"

    echo ""
    set -l prompt_boot (test $is_es -eq 1; and echo "  \e[1;31m> Selecciona el modo de arranque [1, 2]: \e[0m"; or echo "  \e[1;31m> Select boot mode [1, 2]: \e[0m")
    read -l -P (echo -e "$prompt_boot") boot_choice

    if test "$boot_choice" = "2"
        for other_dm in sddm gdm lightdm cosmic-greeter
            if test "$other_dm" != "$dm_service"
                sudo systemctl disable $other_dm 2>/dev/null
            end
        end
        sudo systemctl enable $dm_service
        sudo systemctl set-default graphical.target
        if test $is_es -eq 1
            echo -e "\n    \e[1;32m[OK] Modo Escritorio Automático activado ($dm_service habilitado al inicio).\e[0m"
        else
            echo -e "\n    \e[1;32m[OK] Automatic Desktop Mode activated ($dm_service enabled at boot).\e[0m"
        end
    else
        sudo systemctl disable $dm_service 2>/dev/null
        sudo systemctl set-default multi-user.target 2>/dev/null
        if test $is_es -eq 1
            echo -e "\n    \e[1;33m[OK] Modo Servidor / Consola preservado (TTY1 por defecto).\e[0m"
            echo -e "    \e[0;37mPodrás iniciar tu escritorio desde la opción [1] del Centro de Mando.\e[0m"
        else
            echo -e "\n    \e[1;33m[OK] Server / Console Mode preserved (TTY1 default).\e[0m"
            echo -e "    \e[0;37mYou can start your desktop anytime from option [1] in the Control Center.\e[0m"
        end
    end
    echo -e "\n  $border─────────────────────────────────────────────────────────────────────────────$reset"
    set -l prompt_back (test $is_es -eq 1; and echo "  Presiona Enter para volver..."; or echo "  Press Enter to return...")
    read -l -P "$prompt_back" dummy
end

function clean_previous_desktops -a target_id
    if test $is_es -eq 1
        echo -e "\n  \e[1;33m[*] Retirando entorno anterior para mantener la pureza del sistema...\e[0m"
    else
        echo -e "\n  \e[1;33m[*] Removing previous desktop environment to maintain 100% system purity...\e[0m"
    end

    # Stop and disable previous display managers
    sudo systemctl stop sddm gdm lightdm cosmic-greeter 2>/dev/null
    sudo systemctl disable sddm gdm lightdm cosmic-greeter 2>/dev/null

    # Remove packages from previous desktop with safe recursive cascade (-Rcs)
    if test "$target_id" != "1"; and test (count (pacman -Qq x64-hyprland-settings hyprland 2>/dev/null)) -gt 0
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Desinstalando Hyprland Nativo y componentes...\e[0m"
        else
            echo -e "  \e[0;37m-> Uninstalling Native Hyprland and components...\e[0m"
        end
        if test "$target_id" = "8"
            set -l hypr_pkgs (pacman -Qq x64-hyprland-settings papirus-icon-theme dolphin ark hyprpwcenter swaybg loupe gnome-text-editor kdegraphics-thumbnailers ffmpegthumbs 2>/dev/null | sort -u)
            if test (count $hypr_pkgs) -gt 0
                sudo pacman -Rcs --noconfirm $hypr_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $hypr_pkgs 2>/dev/null
            end
            sudo rm -f /usr/share/wayland-sessions/hyprland-uwsm.desktop /usr/share/wayland-sessions/x64-lios-omarchy.desktop 2>/dev/null
            if test -f /usr/share/wayland-sessions/hyprland.desktop
                if not grep -q "NoDisplay=true" /usr/share/wayland-sessions/hyprland.desktop
                    sudo sh -c 'echo "NoDisplay=true" >> /usr/share/wayland-sessions/hyprland.desktop'
                end
            end
        else
            set -l hypr_pkgs (pacman -Qq x64-hyprland-settings hyprland uwsm quickshell swaybg hyprlock hypridle hyprpolkitagent hyprpwcenter hyprpicker hyprsunset gpu-screen-recorder wf-recorder grim slurp cliphist xdg-desktop-portal-hyprland papirus-icon-theme blueman qalculate-gtk loupe papers gnome-text-editor gnome-disk-utility adw-gtk-theme xdg-terminal-exec hyprland-preview-share-picker qtengine 2>/dev/null | sort -u)
            if test (count $hypr_pkgs) -gt 0
                sudo pacman -Rcs --noconfirm $hypr_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $hypr_pkgs 2>/dev/null
            end
            sudo rm -f /usr/share/wayland-sessions/hyprland.desktop /usr/share/wayland-sessions/hyprland-uwsm.desktop /usr/share/wayland-sessions/x64-lios-omarchy.desktop 2>/dev/null
        end
        sudo rm -rf /etc/skel/.config/hypr /etc/skel/.config/quickshell /etc/xdg/hypr 2>/dev/null
        sudo rm -f /etc/environment.d/10-qt.conf /usr/lib/environment.d/10-qt.conf /usr/bin/papirus-folders 2>/dev/null
        for udir in /home/*
            if test -d $udir
                rm -rf $udir/.config/hypr $udir/.config/hypr.x64-native.bak $udir/.config/quickshell $udir/.config/quickshell.x64-native.bak 2>/dev/null
                rm -f $udir/.config/systemd/user/graphical-session.target.wants/hyprpolkitagent.service 2>/dev/null
            end
        end
    end

    set -l has_omarchy 0
    test -d /usr/share/omarchy; and set has_omarchy 1
    test -f /etc/profile.d/omarchy.sh; and set has_omarchy 1
    test -d /etc/mise; and set has_omarchy 1
    test -f /etc/pam.d/omarchy-lock-password; and set has_omarchy 1
    test (count (pacman -Qq omacalc omacut omasnap omawrite omarchy-nvim omarchy-speedtest omarchy-keyring owe monologue herdr hype signed superwhisper-bin gliff mise-bin mise folio plain hyprland-preview-share-picker qtengine tzupdate ufw-docker yaru-icon-theme google-chrome cmake 2>/dev/null)) -gt 0; and set has_omarchy 1

    if test "$target_id" != "8"; and test $has_omarchy -eq 1
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Purgando paquetes, webapps y configuraciones de X64 LIOS + Omarchy...\e[0m"
        else
            echo -e "  \e[0;37m-> Purging packages, webapps, and configurations of X64 LIOS + Omarchy...\e[0m"
        end
        # 1. Purgar paquetes específicos y suite de aplicaciones de Omarchy (incluyendo mise y hyprland si no vamos a Hyprland nativo)
        set -l oma_extra_hypr
        if test "$target_id" != "1"
            set oma_extra_hypr hyprland uwsm quickshell swaybg hyprlock hypridle hyprpolkitagent hyprpwcenter hyprpicker hyprsunset xdg-desktop-portal-hyprland yaru-icon-theme hyprland-preview-share-picker qtengine
        end
        set -l oma_pkgs (pacman -Qq omacalc omacut omasnap omawrite omarchy-nvim omarchy-screensaver omarchy-speedtest omarchy-local-ai owe monologue herdr hype signed superwhisper-bin foot imv gliff asdcontrol cliamp disktree-bin ttfx tobi-try ttf-ia-writer omarchy-keyring aether obsidian localsend pinta moonlight-qt nautilus nautilus-python libreoffice-fresh mise-bin mise folio plain tzupdate ufw-docker yaru-icon-theme google-chrome cmake $oma_extra_hypr 2>/dev/null | sort -u)
        if test (count $oma_pkgs) -gt 0
            sudo pacman -Rcs --noconfirm $oma_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $oma_pkgs 2>/dev/null
        end
        if test "$target_id" != "1"
            sudo rm -f /usr/share/wayland-sessions/hyprland.desktop /usr/share/wayland-sessions/hyprland-uwsm.desktop 2>/dev/null
        else
            if test -f /usr/share/wayland-sessions/hyprland.desktop
                sudo sed -i '/NoDisplay=true/d' /usr/share/wayland-sessions/hyprland.desktop 2>/dev/null
            end
            sudo rm -f /usr/share/wayland-sessions/hyprland-uwsm.desktop 2>/dev/null
        end

        # 2. Eliminar directorios, wrappers maestros, symlinks en /usr/bin y assets del sistema
        sudo rm -rf /usr/share/omarchy /etc/profile.d/omarchy.sh /usr/share/wayland-sessions/x64-lios-omarchy.desktop /usr/share/wayland-sessions/omarchy.desktop 2>/dev/null
        sudo rm -f /usr/local/bin/omarchy* /usr/bin/omarchy /usr/bin/omarchy-* /usr/local/bin/x64-launch-tiled-terminal /usr/share/bash-completion/completions-fallback/mise.bash 2>/dev/null
        sudo rm -rf /etc/skel/.config/omarchy /etc/skel/.local/state/omarchy /etc/skel/Fondos /etc/skel/Temas /usr/share/fonts/omarchy 2>/dev/null
        sudo rm -rf /etc/mise /var/lib/pacman/sync/omarchy.* 2>/dev/null
        sudo fc-cache -f /usr/share/fonts 2>/dev/null

        # 3. Eliminar servicios systemd y drop-ins
        systemctl --user stop omarchy-crash-watch omarchy-fcitx5 omarchy-sleep-lock owed 2>/dev/null
        systemctl --user disable omarchy-crash-watch omarchy-fcitx5 omarchy-sleep-lock owed 2>/dev/null
        sudo rm -f /usr/lib/systemd/user/omarchy-*.service /usr/lib/systemd/user/owed.service 2>/dev/null
        sudo rm -rf /usr/lib/systemd/user/owed.service.d /etc/systemd/user/owed.service.d 2>/dev/null
        sudo rm -f /usr/lib/systemd/user/wireplumber.service.d/10-omarchy-camera-access.conf 2>/dev/null
        sudo rm -f /etc/systemd/user.conf.d/20-omarchy-nofile.conf /etc/systemd/oomd.conf.d/10-omarchy.conf /etc/systemd/system.conf.d/20-omarchy-nofile.conf 2>/dev/null
        sudo rm -rf /etc/systemd/system/cups-browsed.service.d/10-omarchy.conf /etc/systemd/system/proc-sys-fs-binfmt_misc.mount.d/10-omarchy-conditions.conf 2>/dev/null
        sudo rm -f /etc/systemd/user/graphical-session.target.wants/owed.service 2>/dev/null
        sudo rm -f /etc/systemd/logind.conf.d/20-inhibit-delay.conf 2>/dev/null
        sudo rm -f /usr/lib/systemd/system-sleep/force-igpu /usr/lib/systemd/system-sleep/fprintd-resume /usr/lib/systemd/system-sleep/keyboard-backlight /usr/lib/systemd/system-sleep/unmount-fuse 2>/dev/null
        sudo systemctl daemon-reload 2>/dev/null

        # 4. Eliminar sudoers, tmpfiles, sysctl, udev, modprobe, pam y hooks
        sudo rm -f /etc/pam.d/omarchy-* 2>/dev/null
        sudo rm -f /etc/sudoers.d/omarchy-* /etc/sudoers.d/zz-asdcontrol 2>/dev/null
        sudo rm -f /etc/tmpfiles.d/omarchy-*.conf 2>/dev/null
        sudo rm -f /usr/share/libalpm/hooks/05-omarchy-passwordless-revoke.hook 2>/dev/null
        sudo rm -f /etc/modprobe.d/omarchy-usb-autosuspend.conf 2>/dev/null
        sudo rm -f /etc/sysctl.d/90-omarchy-*.conf /etc/sysctl.d/99-omarchy-sysctl.conf 2>/dev/null
        sudo rm -f /etc/udev/rules.d/60-omarchy-*.rules 2>/dev/null

        # 5. Limpiar /etc/environment y repositorio [omarchy] en /etc/pacman.conf
        sudo sed -i '/OMARCHY_PATH/d' /etc/environment 2>/dev/null
        sudo python3 -c "
import re
try:
    with open('/etc/pacman.conf', 'r') as f:
        c = f.read()
    c = re.sub(r'\[omarchy\]\s*\n(?:(?!\[).*\n)*', '', c)
    with open('/etc/pacman.conf', 'w') as f:
        f.write(c)
except Exception:
    pass
" 2>/dev/null

        # 6. Limpiar /etc/skel/.config/hypr de módulos Lua residuales de Omarchy
        sudo rm -f /etc/skel/.config/hypr/autostart.lua /etc/skel/.config/hypr/bindings.lua /etc/skel/.config/hypr/input.lua /etc/skel/.config/hypr/looknfeel.lua /etc/skel/.config/hypr/monitors.lua /etc/skel/.config/hypr/xdph.conf /etc/skel/.config/hypr/.luarc.json /etc/skel/.config/hypr/hyprsunset.conf 2>/dev/null

        # 7. Limpiar en los directorios de usuario (/home/*) las WebApps, configs, shims, skills y temas
        for udir in /home/*
            if test -d $udir
                for wapp in (find $udir/.local/share/applications -maxdepth 1 -name "*.desktop" 2>/dev/null)
                    if grep -q "omarchy" $wapp 2>/dev/null
                        rm -f $wapp 2>/dev/null
                    end
                end
                rm -f $udir/.local/share/applications/foot.desktop $udir/.local/share/applications/imv.desktop $udir/.local/share/applications/mpv.desktop $udir/.local/share/applications/intent.cache 2>/dev/null
                update-desktop-database $udir/.local/share/applications 2>/dev/null
                rm -rf $udir/.config/omarchy $udir/.local/state/omarchy $udir/.cache/omarchy 2>/dev/null
                rm -rf $udir/.local/share/mise $udir/.config/mise $udir/.local/state/mise $udir/.cache/mise 2>/dev/null
                rm -rf $udir/.local/share/fcitx5/themes/omarchy 2>/dev/null
                rm -f $udir/.config/hypr/autostart.lua $udir/.config/hypr/bindings.lua $udir/.config/hypr/input.lua $udir/.config/hypr/looknfeel.lua $udir/.config/hypr/monitors.lua $udir/.config/hypr/xdph.conf $udir/.config/hypr/.luarc.json $udir/.config/hypr/hyprsunset.conf 2>/dev/null
                rm -f $udir/.config/systemd/user/*.wants/omarchy-* $udir/.config/systemd/user/*/*.wants/omarchy-* 2>/dev/null
                rm -f $udir/.config/uwsm/env.d/*omarchy* 2>/dev/null
                rm -f $udir/.config/nvim/lua/plugins/omarchy-theme-hotreload.lua 2>/dev/null
                find $udir/.config -name "com.omarchy.*" -delete 2>/dev/null
                rm -rf $udir/.agents/skills/omarchy* $udir/.claude/skills/omarchy* $udir/.claude/themes/omarchy* $udir/.codex/skills/omarchy* $udir/.pi/agent/skills/omarchy* $udir/.pi/agent/themes/omarchy* $udir/.gemini/config/skills/omarchy* $udir/.hermes/skills/omarchy* 2>/dev/null
                rm -f $udir/.gemini/config/skills/diagnose-crash 2>/dev/null
                test -d $udir/.gemini/config/skills; and find -L $udir/.gemini/config/skills -xtype l -delete 2>/dev/null
                rmdir $udir/Fondos $udir/Temas $udir/Work/tries $udir/Work 2>/dev/null
            end
        end
    end

    if test "$target_id" != "2"; and test (count (pacman -Qq gnome-shell x64-gnome-settings 2>/dev/null)) -gt 0
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Desinstalando suite completa de GNOME...\e[0m"
        else
            echo -e "  \e[0;37m-> Uninstalling full GNOME suite...\e[0m"
        end
        set -l gnome_pkgs (pacman -Qq x64-gnome-settings gnome-shell gdm gnome-session gnome-control-center gnome-tweaks gnome-shell-extensions nautilus loupe papers showtime decibels simple-scan snapshot sushi baobab file-roller gnome-calculator gnome-text-editor gnome-disk-utility gnome-backgrounds gnome-user-docs gnome-user-share gnome-color-manager gnome-bluetooth-3.0 mutter gnome-menus resources gvfs gvfs-afc gvfs-dnssd gvfs-goa gvfs-gphoto2 gvfs-mtp gvfs-nfs gvfs-smb adw-gtk-theme gnome-screenshot gnome-themes-extra gnome-desktop-4 gnome-desktop-common 2>/dev/null | sort -u)
        if test (count $gnome_pkgs) -gt 0
            sudo pacman -Rcs --noconfirm $gnome_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $gnome_pkgs 2>/dev/null
        end
        sudo rm -f /usr/share/gnome-shell/gnome-shell-theme.gresource* 2>/dev/null
    end

    if test "$target_id" != "3"; and is_kde_installed
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Desinstalando suite completa de KDE Plasma 6...\e[0m"
        else
            echo -e "  \e[0;37m-> Uninstalling full KDE Plasma 6 suite...\e[0m"
        end
        set -l kde_pkgs (pacman -Qq x64-kde-settings plasma-desktop plasma-workspace plasma-integration xdg-desktop-portal-kde plasma-systemmonitor plasma-nm plasma-pa plasma-disks plasma-firewall plasma-vault plasma-thunderbolt plasma-browser-integration plasma-workspace-wallpapers sddm-kcm dolphin konsole ark discover filelight gwenview haruna kate kcalc okular partitionmanager skanpage spectacle bluedevil kdeconnect kinfocenter kscreen kwalletmanager print-manager kde-gtk-config kdeplasma-addons ffmpegthumbs kdegraphics-thumbnailers kdegraphics-mobipocket kdialog kio-admin kio-fuse kwallet kwallet-pam phonon-qt6-vlc phonon-qt6 breeze-gtk xsettingsd 2>/dev/null | sort -u)
        if test (count $kde_pkgs) -gt 0
            sudo pacman -Rcs --noconfirm $kde_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $kde_pkgs 2>/dev/null
        end
        sudo rm -f /usr/share/wayland-sessions/plasma.desktop /usr/share/xsessions/plasma.desktop 2>/dev/null
    end

    if test "$target_id" != "4"; and type -q cosmic-session
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Desinstalando suite completa de COSMIC Desktop...\e[0m"
        else
            echo -e "  \e[0;37m-> Uninstalling full COSMIC Desktop suite...\e[0m"
        end
        set -l cosmic_pkgs (pacman -Qq x64-cosmic-settings cosmic-session cosmic-greeter cosmic-comp cosmic-panel cosmic-app-library cosmic-applets cosmic-bg cosmic-workspaces cosmic-launcher cosmic-notifications cosmic-osd cosmic-settings cosmic-settings-daemon cosmic-randr cosmic-files cosmic-terminal cosmic-text-editor cosmic-viewer cosmic-player cosmic-monitor cosmic-screenshot cosmic-icon-theme cosmic-wallpapers xdg-desktop-portal-cosmic 2>/dev/null | sort -u)
        if test (count $cosmic_pkgs) -gt 0
            sudo pacman -Rcs --noconfirm $cosmic_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $cosmic_pkgs 2>/dev/null
        end
    end

    if test "$target_id" != "5"; and type -q niri-session
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Desinstalando Niri y componentes...\e[0m"
        else
            echo -e "  \e[0;37m-> Uninstalling Niri and components...\e[0m"
        end
        set -l niri_pkgs (pacman -Qq x64-niri-settings niri noctalia nautilus dolphin fuzzel waybar 2>/dev/null | sort -u)
        if test (count $niri_pkgs) -gt 0
            sudo pacman -Rcs --noconfirm $niri_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $niri_pkgs 2>/dev/null
        end
    end

    if test "$target_id" != "6"; and type -q cinnamon-session
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Desinstalando suite completa de Cinnamon...\e[0m"
        else
            echo -e "  \e[0;37m-> Uninstalling full Cinnamon suite...\e[0m"
        end
        set -l cin_pkgs (pacman -Qq x64-cinnamon-settings cinnamon cinnamon-translations nemo lightdm lightdm-slick-greeter gnome-terminal 2>/dev/null | sort -u)
        if test (count $cin_pkgs) -gt 0
            sudo pacman -Rcs --noconfirm $cin_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $cin_pkgs 2>/dev/null
        end
    end

    if test "$target_id" != "7"; and test (count (pacman -Qq xfce4-session xfce4-settings libxfce4ui 2>/dev/null)) -gt 0
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Desinstalando suite completa de Xfce4...\e[0m"
        else
            echo -e "  \e[0;37m-> Uninstalling full Xfce4 suite...\e[0m"
        end
        set -l xfce_pkgs (pacman -Qq x64-xfce4-settings xfce4 xfce4-goodies xfce4-session xfce4-panel xfce4-settings xfce4-power-manager xfce4-screensaver xfce4-notifyd xfce4-taskmanager xfce4-terminal xfce4-appfinder xfwm4 xfconf exo garcon tumbler mousepad parole xfburn libxfce4ui libxfce4util thunar ristretto file-roller lightdm-slick-greeter lightdm-gtk-greeter labwc 2>/dev/null | sort -u)
        if test (count $xfce_pkgs) -gt 0
            sudo pacman -Rcs --noconfirm $xfce_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $xfce_pkgs 2>/dev/null
        end
    end

    if test "$target_id" = "9"
        if test $is_es -eq 1
            echo -e "  \e[0;37m-> Desinstalando gestores de pantalla y navegador gráfico (Chromium)...\e[0m"
        else
            echo -e "  \e[0;37m-> Uninstalling display managers and graphical browser (Chromium)...\e[0m"
        end
        set -l dm_pkgs (pacman -Qq sddm lightdm gdm cosmic-greeter x64-sddm-theme chromium 2>/dev/null | sort -u)
        if test (count $dm_pkgs) -gt 0
            sudo pacman -Rcs --noconfirm $dm_pkgs 2>/dev/null; or sudo pacman -Rc --noconfirm $dm_pkgs 2>/dev/null
        end
    end

    if test $is_es -eq 1
        echo -e "  \e[1;32m[OK] Limpieza de entorno anterior completada con éxito.\e[0m"
    else
        echo -e "  \e[1;32m[OK] Previous desktop cleanup completed successfully.\e[0m"
    end
end

function install_desktop_menu
    clear
    echo ""
    echo ""

    set -l border "\e[1;31m"
    set -l reset "\e[0m"
    set -l title "\e[1;37m"
    set -l val "\e[0;37m"

    set -l hypr_tag ""
    set -l gnome_tag ""
    set -l kde_tag ""
    set -l cosmic_tag ""
    set -l niri_tag ""
    set -l cinnamon_tag ""
    set -l xfce_tag ""
    set -l omarchy_tag ""
    set -l nodesktop_tag ""

    set -l active_lbl (test $is_es -eq 1; and echo " \e[1;32m[ACTIVO]\e[0m"; or echo " \e[1;32m[ACTIVE]\e[0m")
    test (count (pacman -Qq x64-hyprland-settings 2>/dev/null)) -gt 0; and set hypr_tag "$active_lbl"
    type -q gnome-shell; and set gnome_tag "$active_lbl"
    is_kde_installed; and set kde_tag "$active_lbl"
    type -q cosmic-session; and set cosmic_tag "$active_lbl"
    type -q niri-session; and set niri_tag "$active_lbl"
    type -q cinnamon-session; and set cinnamon_tag "$active_lbl"
    type -q xfce4-session; and set xfce_tag "$active_lbl"
    test -d /usr/share/omarchy; and set omarchy_tag "$active_lbl"
    test $has_desktop -eq 0; and set nodesktop_tag "$active_lbl"

    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
    if test $is_es -eq 1
        echo -e "   $title X64 LIOS - GESTIÓN Y MUTACIÓN DE ENTORNOS DE ESCRITORIO$reset"
        echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"
        echo -e "  Selecciona el escritorio oficial que deseas configurar en este equipo:\n"
        echo -e "    \e[1;33m[1]\e[0m $title Hyprland$reset          $val(X64 Cyberpunk Edition - Nativo, animaciones fluidas)$reset$hypr_tag"
        echo -e "    \e[1;33m[2]\e[0m $title GNOME$reset             $val(X64 Stealth Edition - Moderno, sobrio y pulido)$reset$gnome_tag"
        echo -e "    \e[1;33m[3]\e[0m $title KDE Plasma 6$reset      $val(X64 Gaming Edition - Máximo rendimiento y control)$reset$kde_tag"
        echo -e "    \e[1;33m[4]\e[0m $title COSMIC$reset            $val(Next-Gen Rust Desktop desarrollado por System76)$reset$cosmic_tag"
        echo -e "    \e[1;33m[5]\e[0m $title Niri$reset              $val(Tiling con scroll infinito horizontal innovador)$reset$niri_tag"
        echo -e "    \e[1;33m[6]\e[0m $title Cinnamon$reset          $val(Entorno tradicional clásico de alta estabilidad)$reset$cinnamon_tag"
        echo -e "    \e[1;33m[7]\e[0m $title Xfce4$reset             $val(Ligero y ultrarrápido con mínimo consumo de RAM)$reset$xfce_tag"
        echo -e "    \e[1;33m[8]\e[0m $title X64 LIOS + Omarchy$reset $val(Flagship Shell Basecamp adaptado con temas y español)$reset$omarchy_tag"
        echo -e "    \e[1;33m[9]\e[0m $title No Desktop$reset        $val(Modo Servidor / TTY puro sin entorno gráfico)$reset$nodesktop_tag\n"
        echo -e "    \e[1;33m[0]\e[0m Volver al Dashboard Principal"
    else
        echo -e "   $title X64 LIOS - DESKTOP MANAGEMENT & MUTATION$reset"
        echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"
        echo -e "  Select the official desktop you wish to configure on this system:\n"
        echo -e "    \e[1;33m[1]\e[0m $title Hyprland$reset          $val(X64 Cyberpunk Edition - Native, fluid animations)$reset$hypr_tag"
        echo -e "    \e[1;33m[2]\e[0m $title GNOME$reset             $val(X64 Stealth Edition - Modern, sleek and polished)$reset$gnome_tag"
        echo -e "    \e[1;33m[3]\e[0m $title KDE Plasma 6$reset      $val(X64 Gaming Edition - Maximum performance and control)$reset$kde_tag"
        echo -e "    \e[1;33m[4]\e[0m $title COSMIC$reset            $val(Next-Gen Rust Desktop developed by System76)$reset$cosmic_tag"
        echo -e "    \e[1;33m[5]\e[0m $title Niri$reset              $val(Innovative infinite horizontal scroll tiling)$reset$niri_tag"
        echo -e "    \e[1;33m[6]\e[0m $title Cinnamon$reset          $val(Classic traditional high-stability environment)$reset$cinnamon_tag"
        echo -e "    \e[1;33m[7]\e[0m $title Xfce4$reset             $val(Ultra-lightweight with minimal RAM footprint)$reset$xfce_tag"
        echo -e "    \e[1;33m[8]\e[0m $title X64 LIOS + Omarchy$reset $val(Flagship Basecamp Shell adapted with themes & Spanish)$reset$omarchy_tag"
        echo -e "    \e[1;33m[9]\e[0m $title No Desktop$reset        $val(Pure Server / TTY Console Mode without GUI)$reset$nodesktop_tag\n"
        echo -e "    \e[1;33m[0]\e[0m Return to Main Dashboard"
    end
    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"

    echo ""
    set -l prompt_choice (test $is_es -eq 1; and echo "  \e[1;31m> Selecciona una opción [1-9, 0]: \e[0m"; or echo "  \e[1;31m> Select an option [1-9, 0]: \e[0m")
    read -l -P (echo -e "$prompt_choice") d_choice
    test $status -ne 0; and return

    if test "$d_choice" = "0"; or test -z "$d_choice"
        return
    end

    # Environment names
    set -l target_name ""
    set -l target_dm ""
    switch $d_choice
        case 1
            set target_name "Hyprland (X64 Cyberpunk Edition)"
            set target_dm "sddm"
        case 2
            set target_name "GNOME (X64 Stealth Edition)"
            set target_dm "gdm"
        case 3
            set target_name "KDE Plasma 6 (X64 Gaming Edition)"
            set target_dm "sddm"
        case 4
            set target_name "COSMIC Desktop (System76 Rust Edition)"
            set target_dm "cosmic-greeter"
        case 5
            set target_name (test $is_es -eq 1; and echo "Niri (X64 Scroll-Infinito Edition)"; or echo "Niri (X64 Infinite-Scroll Edition)")
            set target_dm "sddm"
        case 6
            set target_name "Cinnamon (X64 Classic Edition)"
            set target_dm "lightdm"
        case 7
            set target_name "Xfce4 (X64 Ultra-Lightweight Edition)"
            set target_dm "lightdm"
        case 8
            set target_name "X64 LIOS + Omarchy (Flagship Cyberpunk Shell)"
            set target_dm "sddm"
        case 9
            set target_name (test $is_es -eq 1; and echo "No Desktop (Modo Servidor / Consola TTY Pura)"; or echo "No Desktop (Pure Server / TTY Console Mode)")
            set target_dm "none"
        case '*'
            return
    end

    # Check if target is already current desktop
    set -l is_current 0
    if test "$d_choice" = "1"; and test (count (pacman -Qq x64-hyprland-settings 2>/dev/null)) -gt 0; set is_current 1; end
    if test "$d_choice" = "2"; and type -q gnome-shell; set is_current 1; end
    if test "$d_choice" = "3"; and is_kde_installed; set is_current 1; end
    if test "$d_choice" = "4"; and type -q cosmic-session; set is_current 1; end
    if test "$d_choice" = "5"; and type -q niri-session; set is_current 1; end
    if test "$d_choice" = "6"; and type -q cinnamon-session; set is_current 1; end
    if test "$d_choice" = "7"; and type -q xfce4-session; set is_current 1; end
    if test "$d_choice" = "8"; and test -d /usr/share/omarchy; set is_current 1; end
    if test "$d_choice" = "9"; and test $has_desktop -eq 0; set is_current 1; end

    if test $is_current -eq 1
        clear
        echo ""
        echo ""
        echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
        if test $is_es -eq 1
            echo -e "   $title AVISO: ENTORNO YA ACTIVO EN EL SISTEMA$reset"
            echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"
            echo -e "    \e[1;32m¡$target_name ya es tu escritorio activo actual!\e[0m\n"
            echo -e "    ¿Deseas reinstalar o reparar sus componentes oficiales?\n"
            echo -e "    \e[1;33m[1]\e[0m Reinstalar / Reparar paquetes de $target_name"
            echo -e "    \e[1;36m[2]\e[0m Reconfigurar modo de arranque (Consola TTY vs Inicio Gráfico)"
            echo -e "    \e[1;31m[0]\e[0m Cancelar y volver al Dashboard\n"
        else
            echo -e "   $title NOTICE: ENVIRONMENT ALREADY ACTIVE ON SYSTEM$reset"
            echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"
            echo -e "    \e[1;32m$target_name is already your current active desktop!\e[0m\n"
            echo -e "    Would you like to reinstall or repair its official components?\n"
            echo -e "    \e[1;33m[1]\e[0m Reinstall / Repair $target_name packages"
            echo -e "    \e[1;36m[2]\e[0m Reconfigure boot mode (TTY Console vs Graphical Login)"
            echo -e "    \e[1;31m[0]\e[0m Cancel and return to Dashboard\n"
        end
        echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
        echo ""
        set -l prompt_same (test $is_es -eq 1; and echo "  \e[1;31m> Opción [1, 2, 0]: \e[0m"; or echo "  \e[1;31m> Option [1, 2, 0]: \e[0m")
        read -l -P (echo -e "$prompt_same") same_choice
        if test "$same_choice" = "2"
            configure_desktop_boot_mode $target_dm "$target_name"
            return
        else if test "$same_choice" != "1"
            return
        end
    else
        # If another desktop is installed, execute Clean Transition Protocol
        if test $has_desktop -gt 0
            # Safety Lock: Detect if running inside an active local graphical terminal window
            if is_graphical_session
                clear
                echo ""
                echo ""
                echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
                if test $is_es -eq 1
                    echo -e "   $title BLOQUEO DE SEGURIDAD: TERMINAL GRÁFICA ACTIVA$reset"
                    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"
                    echo -e "    \e[1;31m[!] Estás ejecutando x64-dashboard dentro de tu entorno gráfico actual.\e[0m\n"
                    echo -e "    Para mutar de escritorio, el sistema debe detener el gestor de pantalla ($desktop_dms[1])"
                    echo -e "    y retirar los componentes de \e[1;37m$desktop_names[1]\e[0m. Si procedemos desde aquí:"
                    echo -e "    \e[1;33m• Tu ventana de terminal se cerrará abruptamente al detenerse el compositor.\e[0m"
                    echo -e "    \e[1;33m• Pacman quedará interrumpido en mitad de la instalación con la base bloqueada.\e[0m\n"
                    echo -e "    \e[1;32mPASOS PARA MUTAR DE FORMA 100% SEGURA:\e[0m\n"
                    echo -e "    \e[1;36m1.\e[0m Cambia a una consola virtual TTY pulsando: \e[1;37mCtrl + Alt + F3\e[0m (o F2/F4)"
                    echo -e "    \e[1;36m2.\e[0m Inicia sesión con tu usuario y contraseña habituales de Linux."
                    echo -e "    \e[1;36m3.\e[0m Ejecuta el comando: \e[1;32mx64-dashboard\e[0m"
                    echo -e "    \e[1;36m4.\e[0m Selecciona \e[1;37m$target_name\e[0m para iniciar la transición limpia.\n"
                    echo -e "    \e[0;37m(Para regresar a tu escritorio actual sin cambios, pulsa \e[1;37mCtrl + Alt + F1\e[0m o \e[1;37mF2\e[0m)\e[0m\n"
                else
                    echo -e "   $title SAFETY LOCK: ACTIVE GRAPHICAL TERMINAL DETECTED$reset"
                    echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"
                    echo -e "    \e[1;31m[!] You are running x64-dashboard inside your current graphical desktop.\e[0m\n"
                    echo -e "    To mutate to another desktop, the system must stop the display manager ($desktop_dms[1])"
                    echo -e "    and uninstall \e[1;37m$desktop_names[1]\e[0m. If we proceed from inside this window:"
                    echo -e "    \e[1;33m• Your terminal window will be terminated abruptly as the compositor stops.\e[0m"
                    echo -e "    \e[1;33m• Pacman will be interrupted mid-install and leave the database locked.\e[0m\n"
                    echo -e "    \e[1;32mSTEPS FOR A 100% SAFE TRANSITION:\e[0m\n"
                    echo -e "    \e[1;36m1.\e[0m Switch to a kernel TTY virtual console: \e[1;37mCtrl + Alt + F3\e[0m (or F2/F4)"
                    echo -e "    \e[1;36m2.\e[0m Log in with your standard Linux user and password."
                    echo -e "    \e[1;36m3.\e[0m Run: \e[1;32mx64-dashboard\e[0m"
                    echo -e "    \e[1;36m4.\e[0m Select \e[1;37m$target_name\e[0m to perform the clean mutation.\n"
                    echo -e "    \e[0;37m(To return to your current desktop session, press \e[1;37mCtrl + Alt + F1\e[0m or \e[1;37mF2\e[0m)\e[0m\n"
                end
                echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
                echo ""
                set -l prompt_safe_back (test $is_es -eq 1; and echo "  Presiona Enter para volver de forma segura..."; or echo "  Press Enter to safely return...")
                read -l -P "$prompt_safe_back" dummy
                return
            end

            clear
            echo ""
            echo ""
            echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
            if test $is_es -eq 1
                echo -e "   $title TRANSICIÓN LIMPIA DE ESCRITORIO (MODO PUREZA X64)$reset"
                echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"
                echo -e "    \e[1;33m[!] Entorno actual detectado:\e[0m \e[1;37m$desktop_names[1]\e[0m\n"
                echo -e "    Para evitar duplicación de aplicaciones (múltiples exploradores de archivos,"
                echo -e "    centros de control y reproductores) y colisiones de demonios en segundo plano:\n"
                echo -e "    \e[1;31m1.\e[0m Se desinstalará limpiamente \e[1;33m$desktop_names[1]\e[0m y sus dependencias."
                echo -e "    \e[1;32m2.\e[0m Se instalará y configurará \e[1;37m$target_name\e[0m."
                echo -e "    \e[1;36m3.\e[0m Podrás configurar el modo de arranque (Consola TTY o Gráfico).\n"
            else
                echo -e "   $title CLEAN DESKTOP TRANSITION (X64 PURITY MODE)$reset"
                echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset\n"
                echo -e "    \e[1;33m[!] Current environment detected:\e[0m \e[1;37m$desktop_names[1]\e[0m\n"
                echo -e "    To prevent application bloat (duplicate file managers, control panels,"
                echo -e "    and media players) and background daemon collisions:\n"
                echo -e "    \e[1;31m1.\e[0m Cleanly remove \e[1;33m$desktop_names[1]\e[0m and its dependencies."
                echo -e "    \e[1;32m2.\e[0m Install and configure \e[1;37m$target_name\e[0m."
                echo -e "    \e[1;36m3.\e[0m Configure your boot mode (TTY Console or Graphical).\n"
            end
            echo -e "  $border─────────────────────────────────────────────────────────────────────────────$reset"
            echo ""
            set -l prompt_trans (test $is_es -eq 1; and echo "  \e[1;31m> ¿Proceder con la transición limpia a $target_name? [S/n]: \e[0m"; or echo "  \e[1;31m> Proceed with clean transition to $target_name? [Y/n]: \e[0m")
            read -l -P (echo -e "$prompt_trans") trans_choice
            if test -n "$trans_choice"; and test "$trans_choice" != "s"; and test "$trans_choice" != "S"; and test "$trans_choice" != "y"; and test "$trans_choice" != "Y"
                if test $is_es -eq 1
                    echo -e "\n  \e[1;33m[INFO] Transición cancelada. Tu escritorio actual no ha sido modificado.\e[0m"
                else
                    echo -e "\n  \e[1;33m[INFO] Transition cancelled. Your current desktop was not modified.\e[0m"
                end
                sleep 2
                return
            end

            # Execute previous environment cleanup
            clean_previous_desktops $d_choice
        end
    end

    # Installation of selected desktop suite (1:1 parity with Calamares Master Suites)
    set -l install_ok 0
    switch $d_choice
        case 1
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Instalando Hyprland Nativo Oficial de X64 LIOS (Suite Cyberpunk)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Installing Official X64 LIOS Native Hyprland (Cyberpunk Suite)...\e[0m"
            end
            sudo pacman -Sy --needed --noconfirm --overwrite "*" hyprland sddm x64-sddm-theme dolphin ark ffmpegthumbs kdegraphics-thumbnailers loupe papers gnome-text-editor qalculate-gtk blueman gnome-disk-utility kitty opencode quickshell swaybg hyprlock hypridle hyprpolkitagent hyprpwcenter hyprpicker hyprsunset gpu-screen-recorder cliphist adw-gtk-theme xdg-terminal-exec xdg-desktop-portal-hyprland x64-hyprland-settings chromium
            test $status -eq 0; and set install_ok 1
            if test $install_ok -eq 1
                if test -d $HOME/.config/hypr.x64-native.bak
                    rm -rf $HOME/.config/hypr
                    mv $HOME/.config/hypr.x64-native.bak $HOME/.config/hypr
                else
                    mkdir -p $HOME/.config/hypr
                    if not test -f $HOME/.config/hypr/hyprland.lua; and test -f /etc/xdg/hypr/hyprland.lua
                        cp -f /etc/xdg/hypr/hyprland.lua $HOME/.config/hypr/hyprland.lua
                    end
                    if not test -f $HOME/.config/hypr/custom.lua; and test -f /etc/xdg/hypr/custom.lua
                        cp -f /etc/xdg/hypr/custom.lua $HOME/.config/hypr/custom.lua
                    end
                    if not test -f $HOME/.config/hypr/hyprland.conf; and test -f /etc/xdg/hypr/hyprland.conf
                        cp -f /etc/xdg/hypr/hyprland.conf $HOME/.config/hypr/hyprland.conf
                    end
                    if not test -f $HOME/.config/hypr/hyprlock.conf; and test -f /etc/xdg/hypr/hyprlock.conf
                        cp -f /etc/xdg/hypr/hyprlock.conf $HOME/.config/hypr/hyprlock.conf
                    end
                end
                if test -d $HOME/.config/quickshell.x64-native.bak
                    rm -rf $HOME/.config/quickshell
                    mv $HOME/.config/quickshell.x64-native.bak $HOME/.config/quickshell
                end
                configure_desktop_boot_mode sddm "Hyprland (X64 Cyberpunk Edition)"
            end
        case 2
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Instalando GNOME Oficial de X64 LIOS (Suite Completa Calamares)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Installing Official X64 LIOS GNOME (Full Calamares Suite)...\e[0m"
            end
            sudo pacman -S --needed --noconfirm --overwrite "*" baobab decibels file-roller gdm gnome-backgrounds gnome-bluetooth-3.0 gnome-calculator gnome-color-manager gnome-control-center gnome-disk-utility gnome-keyring gnome-menus gnome-session gnome-settings-daemon gnome-shell gnome-shell-extensions gnome-text-editor gnome-tweaks gnome-user-docs gnome-user-share gvfs gvfs-afc gvfs-dnssd gvfs-goa gvfs-gphoto2 gvfs-mtp gvfs-nfs gvfs-smb loupe mutter nautilus papers resources showtime simple-scan snapshot sushi xdg-user-dirs-gtk x64-gnome-settings adw-gtk-theme kitty chromium
            test $status -eq 0; and set install_ok 1
            if test $install_ok -eq 1
                configure_desktop_boot_mode gdm "GNOME (X64 Stealth Edition)"
            end
        case 3
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Instalando KDE Plasma 6 Oficial de X64 LIOS (Suite Completa Calamares)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Installing Official X64 LIOS KDE Plasma 6 (Full Calamares Suite)...\e[0m"
            end
            sudo pacman -S --needed --noconfirm --overwrite "*" ark bluedevil breeze breeze-icons breeze-gtk discover dolphin ffmpegthumbs filelight flatpak fwupd gwenview haruna kate kcalc kde-gtk-config kdeconnect kdegraphics-thumbnailers kdeplasma-addons kdialog kinfocenter kio-admin kio-fuse konsole kscreen kwallet-pam kwalletmanager okular partitionmanager phonon-qt6-vlc plasma-browser-integration plasma-desktop plasma-disks plasma-firewall plasma-nm plasma-pa plasma-systemmonitor plasma-thunderbolt plasma-vault plasma-workspace-wallpapers powerdevil print-manager sddm sddm-kcm x64-sddm-theme skanpage spectacle tesseract-data-eng xdg-desktop-portal-kde xdg-user-dirs xsettingsd x64-kde-settings chromium
            test $status -eq 0; and set install_ok 1
            if test $install_ok -eq 1
                for f in kdeglobals plasmashellrc plasma-org.kde.plasma.desktop-appletsrc plasmarc kwinrc kscreenlockerrc baloofilerc ksmserverrc
                    if test -f /etc/skel/.config/$f
                        cp -f /etc/skel/.config/$f $HOME/.config/$f 2>/dev/null
                    end
                end
                mkdir -p $HOME/.config/kdedefaults $HOME/.config/gtk-3.0 $HOME/.config/gtk-4.0 2>/dev/null
                for df in kdeglobals kwinrc plasmarc kscreenlockerrc ksmserverrc
                    if test -f /etc/skel/.config/kdedefaults/$df
                        cp -f /etc/skel/.config/kdedefaults/$df $HOME/.config/kdedefaults/$df 2>/dev/null
                    end
                end
                test -f /etc/skel/.config/gtk-3.0/settings.ini; and cp -f /etc/skel/.config/gtk-3.0/settings.ini $HOME/.config/gtk-3.0/settings.ini 2>/dev/null
                test -f /etc/skel/.config/gtk-4.0/settings.ini; and cp -f /etc/skel/.config/gtk-4.0/settings.ini $HOME/.config/gtk-4.0/settings.ini 2>/dev/null
                rm -f $HOME/.config/gtk-3.0/gtk.css $HOME/.config/gtk-4.0/gtk.css $HOME/.cache/icon-cache.kcache $HOME/.cache/ksycoca6* 2>/dev/null
                rm -rf $HOME/.cache/plasmashell 2>/dev/null
                configure_desktop_boot_mode sddm "KDE Plasma 6 (X64 Gaming Edition)"
            end
        case 4
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Instalando COSMIC Desktop Oficial de X64 LIOS (Suite Completa Calamares)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Installing Official X64 LIOS COSMIC Desktop (Full Calamares Suite)...\e[0m"
            end
            sudo pacman -S --needed --noconfirm --overwrite "*" cosmic-session cosmic-greeter cosmic-comp cosmic-panel cosmic-app-library cosmic-applets cosmic-bg cosmic-workspaces cosmic-launcher cosmic-notifications cosmic-osd cosmic-settings cosmic-settings-daemon cosmic-randr cosmic-files cosmic-terminal cosmic-text-editor cosmic-viewer cosmic-player cosmic-monitor cosmic-screenshot cosmic-icon-theme cosmic-wallpapers gnome-keyring xdg-desktop-portal-cosmic xdg-desktop-portal-gtk xorg-xwayland x64-cosmic-settings chromium
            test $status -eq 0; and set install_ok 1
            if test $install_ok -eq 1
                configure_desktop_boot_mode cosmic-greeter "COSMIC Desktop (System76 Rust Edition)"
            end
        case 5
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Instalando Niri Oficial de X64 LIOS (Suite Completa Noctalia Shell)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Installing Official X64 LIOS Niri (Full Noctalia Shell Suite)...\e[0m"
            end
            sudo pacman -S --needed --noconfirm --overwrite "*" niri sddm x64-sddm-theme kitty nautilus noctalia xdg-desktop-portal-gnome x64-niri-settings chromium
            test $status -eq 0; and set install_ok 1
            if test $install_ok -eq 1
                configure_desktop_boot_mode sddm "Niri (X64 Noctalia Shell Edition)"
            end
        case 6
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Instalando Cinnamon Oficial de X64 LIOS (Suite Completa Calamares)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Installing Official X64 LIOS Cinnamon (Full Calamares Suite)...\e[0m"
            end
            sudo pacman -S --needed --noconfirm --overwrite "*" cinnamon cinnamon-translations nemo lightdm lightdm-slick-greeter gnome-keyring gnome-terminal kitty x64-cinnamon-settings chromium
            test $status -eq 0; and set install_ok 1
            if test $install_ok -eq 1
                configure_desktop_boot_mode lightdm "Cinnamon (X64 Classic Edition)"
            end
        case 7
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Instalando Xfce4 Oficial de X64 LIOS (Suite Completa Calamares)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Installing Official X64 LIOS Xfce4 (Full Calamares Suite)...\e[0m"
            end
            sudo pacman -S --needed --noconfirm --overwrite "*" xfce4 xfce4-goodies labwc xorg-xwayland lightdm lightdm-slick-greeter thunar file-roller ristretto network-manager-applet x64-xfce4-settings chromium
            test $status -eq 0; and set install_ok 1
            if test $install_ok -eq 1
                configure_desktop_boot_mode lightdm "Xfce4 (X64 Ultra-Lightweight Edition)"
            end
        case 8
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Instalando X64 LIOS + Omarchy (Flagship Shell Basecamp)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Installing X64 LIOS + Omarchy (Flagship Basecamp Shell)...\e[0m"
            end
            if not test -d /usr/share/omarchy
                if test $is_es -eq 1
                    echo -e "  \e[1;36m-> Desplegando repositorio X64 LIOS + Omarchy (/usr/share/omarchy)...\e[0m"
                else
                    echo -e "  \e[1;36m-> Deploying X64 LIOS + Omarchy repository (/usr/share/omarchy)...\e[0m"
                end
                sudo git clone --depth 1 -b main https://github.com/XzForz3-Dev/X64-LIOS-Omarchy.git /usr/share/omarchy
                sudo git config --system --add safe.directory /usr/share/omarchy 2>/dev/null
            else
                sudo git config --system --add safe.directory /usr/share/omarchy 2>/dev/null
                sudo git -C /usr/share/omarchy pull origin main 2>/dev/null
            end
            # Ejecutar el motor de instalación y configuración oficial de Omarchy
            sudo python3 /usr/share/omarchy/bin/x64-omarchy-setup.py --user $USER --theme "x64-lios-crimson"
            test $status -eq 0; and set install_ok 1
            if test $install_ok -eq 1
                configure_desktop_boot_mode sddm "X64 LIOS + Omarchy (Flagship Shell)"
            end
        case 9
            if test $is_es -eq 1
                echo -e "\n  \e[1;32m[*] Configurando Sistema en Modo No Desktop (Consola TTY Pura)...\e[0m"
            else
                echo -e "\n  \e[1;32m[*] Configuring System in No Desktop Mode (Pure TTY Console)...\e[0m"
            end
            sudo systemctl disable sddm gdm lightdm cosmic-greeter 2>/dev/null
            sudo systemctl set-default multi-user.target 2>/dev/null
            set install_ok 1
            if test $is_es -eq 1
                echo -e "  \e[1;32m[OK] Todos los gestores gráficos han sido deshabilitados.\e[0m"
                echo -e "  \e[1;32m[OK] Target configurado en multi-user.target (Consola TTY).\e[0m\n"
                read -l -P (echo -e "  \e[1;31m¿Deseas reiniciar ahora para entrar en consola TTY? [s/N]: \e[0m") r_ans
            else
                echo -e "  \e[1;32m[OK] All graphical display managers have been disabled.\e[0m"
                echo -e "  \e[1;32m[OK] Target configured to multi-user.target (TTY Console).\e[0m\n"
                read -l -P (echo -e "  \e[1;31mDo you want to reboot now into TTY console? [y/N]: \e[0m") r_ans
            end
            if test "$r_ans" = "s"; or test "$r_ans" = "S"; or test "$r_ans" = "y"; or test "$r_ans" = "Y"
                sudo reboot
            end
        case '*'
            return
    end

    if test $install_ok -ne 1
        if test $is_es -eq 1
            echo -e "\n  \e[1;31m[ERROR] La instalación del entorno falló o fue interrumpida.\e[0m"
            read -l -P "  Presiona Enter para volver..." dummy
        else
            echo -e "\n  \e[1;31m[ERROR] Desktop environment installation failed or was interrupted.\e[0m"
            read -l -P "  Press Enter to return..." dummy
        end
    end

    # Sync official default configurations from /etc/skel to active user directory and sanitize XDG dirs
    sanitize_user_dirs_and_configs
end

# Paginated log viewer for Option [7] (mode: errors | current | previous)
# Pager options are passed directly to less on the command line (no fragile LESS/SYSTEMD_LESS env scoping).
function x64_log_viewer -a mode
    set -l title_es ""
    set -l title_en ""
    set -l j_args
    switch $mode
        case errors
            set title_es "VISOR DE ERRORES CRÍTICOS DEL ARRANQUE (JOURNALCTL -P 3 -XB)"
            set title_en "CRITICAL BOOT ERROR VIEWER (JOURNALCTL -P 3 -XB)"
            set j_args -p 3 -x -b
        case current
            set title_es "REGISTRO COMPLETO DEL ARRANQUE ACTUAL (JOURNALCTL -B)"
            set title_en "FULL CURRENT BOOT LOG (JOURNALCTL -B)"
            set j_args -b
        case previous
            set title_es "REGISTRO DEL ARRANQUE ANTERIOR (JOURNALCTL -B -1)"
            set title_en "PREVIOUS BOOT LOG (JOURNALCTL -B -1)"
            set j_args -b -1
        case '*'
            return 1
    end

    clear
    echo ""
    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
    if test $is_es -eq 1
        echo -e "   \e[1;37m$title_es\e[0m"
    else
        echo -e "   \e[1;37m$title_en\e[0m"
    end
    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"

    # Previous boot may not exist on fresh installations or volatile journals
    if test "$mode" = "previous"
        if test (journalctl -b -1 -n 1 -q --no-pager 2>/dev/null | count) -eq 0
            if test $is_es -eq 1
                echo -e "    \e[1;33m[!] No existe un arranque previo registrado en el journal.\e[0m"
                echo -e "    Esto es normal en una instalación recién hecha o tras limpiar los registros.\n"
            else
                echo -e "    \e[1;33m[!] No previous boot is recorded in the journal.\e[0m"
                echo -e "    This is normal on a fresh installation or after vacuuming the logs.\n"
            end
            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
            set -l prompt_back (test $is_es -eq 1; and echo "  Presiona Enter para volver..."; or echo "  Press Enter to return...")
            read -l -P "$prompt_back" dummy
            return 0
        end
    end

    set -l less_prompt "[ Pulsa q para salir | Flechas arriba y abajo para navegar ]"
    if test $is_es -eq 1
        echo -e "    \e[1;33m[TIP]\e[0m Usa las flechas \e[1;32m↑ / ↓\e[0m (o Re Pág / Av Pág) para desplazarte."
        echo -e "          Pulsa la tecla \e[1;32mq\e[0m para salir del visor y volver al menú.\n"
        read -l -P "  Presiona Enter para abrir el visor..." dummy
    else
        set less_prompt "[ Press q to exit | Up and Down arrows to navigate ]"
        echo -e "    \e[1;33m[TIP]\e[0m Use the \e[1;32m↑ / ↓\e[0m arrows (or PgUp / PgDn) to scroll."
        echo -e "          Press the \e[1;32mq\e[0m key to exit the viewer and return to the menu.\n"
        read -l -P "  Press Enter to open the viewer..." dummy
    end

    if type -q less
        # -R colors, -X keep output on exit, -F auto-exit if it fits one screen, -K Ctrl+C exits, -Ps custom bottom prompt
        SYSTEMD_COLORS=1 journalctl $j_args --no-pager 2>&1 | less -R -X -F -K -Ps"$less_prompt"
    else
        SYSTEMD_COLORS=1 journalctl $j_args --no-pager 2>&1 | tail -n 200
    end

    echo -e "\n  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
    set -l prompt_back (test $is_es -eq 1; and echo "  Presiona Enter para volver al menú de diagnóstico..."; or echo "  Press Enter to return to the diagnostics menu...")
    read -l -P "$prompt_back" dummy
end

# Interactive Dashboard Loop
while true
    draw_dashboard
    echo ""
    set -l prompt_main (test $is_es -eq 1; and echo "  \e[1;31m> Selecciona una opción [1-9, 0]: \e[0m"; or echo "  \e[1;31m> Select an option [1-9, 0]: \e[0m")
    read -l -P (echo -e "$prompt_main") choice
    test $status -ne 0; and break

    switch $choice
        case 8 'c' 'C'
            clear
            if test -f /etc/fastfetch/config-tty.jsonc
                fastfetch --config /etc/fastfetch/config-tty.jsonc
            else
                fastfetch 2>/dev/null
            end
            echo ""
            if test $is_es -eq 1
                echo -e "  \e[0;37m(Escribe \e[1;33mx64-dashboard\e[0m \e[0;37men cualquier momento para volver al Centro de Mando)\e[0m\n"
            else
                echo -e "  \e[0;37m(Type \e[1;33mx64-dashboard\e[0m \e[0;37mat any time to return to the Control Center)\e[0m\n"
            end
            break
        case 9 'r' 'R'
            clear
            echo ""
            echo ""
            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
            if test $is_es -eq 1
                echo -e "   \e[1;37mREINICIAR EL SERVIDOR\e[0m"
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                echo -e "    ¿Estás seguro de que deseas reiniciar el sistema ahora mismo?\n"
                echo -e "    \e[1;33m[1]\e[0m \e[1;37mSí, reiniciar ahora\e[0m"
                echo -e "    \e[1;32m[0]\e[0m \e[1;37mCancelar y volver al Centro de Mando\e[0m\n"
            else
                echo -e "   \e[1;37mREBOOT SYSTEM\e[0m"
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                echo -e "    Are you sure you want to reboot the system right now?\n"
                echo -e "    \e[1;33m[1]\e[0m \e[1;37mYes, reboot now\e[0m"
                echo -e "    \e[1;32m[0]\e[0m \e[1;37mCancel and return to Control Center\e[0m\n"
            end
            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
            echo ""
            set -l prompt_reboot (test $is_es -eq 1; and echo "  \e[1;31m> Confirmar [1, 0]: \e[0m"; or echo "  \e[1;31m> Confirm [1, 0]: \e[0m")
            read -l -P (echo -e "$prompt_reboot") r_choice
            if test "$r_choice" = "1"
                clear
                if test $is_es -eq 1
                    echo -e "\e[1;33mReiniciando el sistema...\e[0m"
                else
                    echo -e "\e[1;33mRebooting the system...\e[0m"
                end
                sudo systemctl reboot
                break
            end
        case 0 'a' 'A'
            clear
            echo ""
            echo ""
            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
            if test $is_es -eq 1
                echo -e "   \e[1;37mAPAGAR EL SERVIDOR\e[0m"
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                echo -e "    ¿Estás seguro de que deseas apagar este equipo por completo?\n"
                echo -e "    \e[1;31m[1]\e[0m \e[1;37mSí, apagar ahora\e[0m"
                echo -e "    \e[1;32m[0]\e[0m \e[1;37mCancelar y volver al Centro de Mando\e[0m\n"
            else
                echo -e "   \e[1;37mSHUT DOWN SYSTEM\e[0m"
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                echo -e "    Are you sure you want to completely power off this machine?\n"
                echo -e "    \e[1;31m[1]\e[0m \e[1;37mYes, shut down now\e[0m"
                echo -e "    \e[1;32m[0]\e[0m \e[1;37mCancel and return to Control Center\e[0m\n"
            end
            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
            echo ""
            set -l prompt_poweroff (test $is_es -eq 1; and echo "  \e[1;31m> Confirmar [1, 0]: \e[0m"; or echo "  \e[1;31m> Confirm [1, 0]: \e[0m")
            read -l -P (echo -e "$prompt_poweroff") a_choice
            if test "$a_choice" = "1"
                clear
                if test $is_es -eq 1
                    echo -e "\e[1;31mApagando el servidor...\e[0m"
                else
                    echo -e "\e[1;31mShutting down the server...\e[0m"
                end
                sudo systemctl poweroff
                break
            end
        case 'i' 'I'
            install_desktop_menu
        case 'g' 'G'
            if test $has_desktop -gt 0
                set -l target_vt (get_graphical_vt)
                sudo chvt $target_vt 2>/dev/null
            end
        case 1
            if test $has_desktop -eq 0
                install_desktop_menu
            else
                set -l dm_active (systemctl is-active $desktop_dms[1] 2>/dev/null)
                if test "$dm_active" = "active"
                    set -l target_vt (get_graphical_vt)
                    sudo chvt $target_vt 2>/dev/null
                else
                    clear
                    echo ""
                    echo ""
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                    if test $is_es -eq 1
                        echo -e "   \e[1;37mINICIANDO ENTORNO GRÁFICO OFICIAL\e[0m"
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                        echo -e "    \e[1;32m[*] Entorno:\e[0m  \e[1;37m$desktop_names[1]\e[0m"
                        echo -e "    \e[1;36m[*] Gestor:\e[0m   \e[1;37m$desktop_dms[1]\e[0m (Pantalla de acceso X64 LIOS)\n"
                        echo -e "    \e[0;37mEl sistema iniciará el gestor de pantalla con integración completa de\e[0m"
                        echo -e "    \e[0;37mseguridad PAM, D-Bus de sesión y aceleración gráfica en unos segundos.\e[0m\n"
                        echo -e "    \e[1;33m[Tip]\e[0m \e[0;37mPara volver a este Centro de Mando en cualquier momento:\e[0m"
                        echo -e "          \e[1;37mPresiona Ctrl + Alt + F3\e[0m\n"
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        echo -e -n "\n  \e[1;32mIniciando $desktop_dms[1]...\e[0m\n"
                    else
                        echo -e "   \e[1;37mSTARTING OFFICIAL GRAPHICAL ENVIRONMENT\e[0m"
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                        echo -e "    \e[1;32m[*] Environment:\e[0m  \e[1;37m$desktop_names[1]\e[0m"
                        echo -e "    \e[1;36m[*] Manager:\e[0m      \e[1;37m$desktop_dms[1]\e[0m (X64 LIOS Login Screen)\n"
                        echo -e "    \e[0;37mThe system will start the display manager with full PAM security,\e[0m"
                        echo -e "    \e[0;37msession D-Bus and hardware acceleration in a few seconds.\e[0m\n"
                        echo -e "    \e[1;33m[Tip]\e[0m \e[0;37mTo return to this Control Center at any time:\e[0m"
                        echo -e "          \e[1;37mPress Ctrl + Alt + F3\e[0m\n"
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        echo -e -n "\n  \e[1;32mStarting $desktop_dms[1]...\e[0m\n"
                    end
                    sudo systemctl start $desktop_dms[1]
                    sleep 2
                end
            end
        case 'd' 'D'
            if test $has_desktop -gt 0
                set -l dm_active (systemctl is-active $desktop_dms[1] 2>/dev/null)
                if test "$dm_active" = "active"
                    clear
                    echo ""
                    echo ""
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                    if test $is_es -eq 1
                        echo -e "   \e[1;37mDETENER ENTORNO GRÁFICO ($desktop_names[1])\e[0m"
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                        echo -e "    El entorno gráfico \e[1;32m$desktop_names[1]\e[0m está actualmente en ejecución.\n"
                        echo -e "    \e[1;31m[1]\e[0m Detener entorno gráfico ($desktop_dms[1]) y liberar memoria RAM"
                        echo -e "    \e[1;36m[2]\e[0m Volver a la pantalla del escritorio"
                        echo -e "    \e[1;33m[0]\e[0m Volver al Centro de Mando\n"
                    else
                        echo -e "   \e[1;37mSTOP GRAPHICAL ENVIRONMENT ($desktop_names[1])\e[0m"
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                        echo -e "    The graphical environment \e[1;32m$desktop_names[1]\e[0m is currently running.\n"
                        echo -e "    \e[1;31m[1]\e[0m Stop graphical environment ($desktop_dms[1]) and free RAM"
                        echo -e "    \e[1;36m[2]\e[0m Switch back to graphical screen"
                        echo -e "    \e[1;33m[0]\e[0m Return to Control Center\n"
                    end
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                    echo ""
                    set -l prompt_dm_stop (test $is_es -eq 1; and echo "  \e[1;31m> Opción [1, 2, 0]: \e[0m"; or echo "  \e[1;31m> Option [1, 2, 0]: \e[0m")
                    read -l -P (echo -e "$prompt_dm_stop") dm_stop_choice
                    if test "$dm_stop_choice" = "1"
                        if is_graphical_session
                            if test $is_es -eq 1
                                echo -e "\n  \e[1;31m[BLOQUEO DE SEGURIDAD] Estás ejecutando esta terminal dentro de la sesión gráfica.\e[0m"
                                echo -e "  \e[0;37mPara detener el servicio gráfico sin cerrar tu ventana, cambia a una TTY con \e[1;36mCtrl+Alt+F3\e[0m.\e[0m"
                            else
                                echo -e "\n  \e[1;31m[SAFETY LOCK] You are running this terminal inside the graphical session.\e[0m"
                                echo -e "  \e[0;37mTo safely stop the graphical service without aborting, switch to a TTY with \e[1;36mCtrl+Alt+F3\e[0m.\e[0m"
                            end
                            sleep 2
                        else
                            if test $is_es -eq 1
                                echo -e "\n  \e[1;33mDeteniendo $desktop_names[1] ($desktop_dms[1])...\e[0m"
                                sudo systemctl stop $desktop_dms[1]
                                echo -e "  \e[1;32m[OK] Servicio detenido y memoria liberada.\e[0m"
                            else
                                echo -e "\n  \e[1;33mStopping $desktop_names[1] ($desktop_dms[1])...\e[0m"
                                sudo systemctl stop $desktop_dms[1]
                                echo -e "  \e[1;32m[OK] Service stopped and RAM released.\e[0m"
                            end
                            sleep 1
                        end
                    else if test "$dm_stop_choice" = "2"
                        set -l target_vt (get_graphical_vt)
                        sudo chvt $target_vt 2>/dev/null
                    end
                else
                    if test $is_es -eq 1
                        echo -e "\n  \e[1;33m[!] El entorno gráfico no está en ejecución actualmente.\e[0m"
                    else
                        echo -e "\n  \e[1;33m[!] The graphical environment is not currently running.\e[0m"
                    end
                    sleep 1
                end
            end
        case 2 'm' 'M'
            if type -q btop
                btop
            else
                top
            end
        case 3 's' 'S'
            while true
                clear
                echo ""
                echo ""
                set -l cur_ssh (systemctl is-active sshd 2>/dev/null)
                set -l cur_ufw (systemctl is-active ufw 2>/dev/null)
                set -l my_ip (ip route get 1.1.1.1 2>/dev/null | awk '{print $7}')
                test -z "$my_ip"; and set my_ip (ip -4 addr show | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '127.0.0.1' | head -n 1)
                if test -z "$my_ip"
                    set my_ip (test $is_es -eq 1; and echo "Sin conexión de red"; or echo "No network connection")
                end

                set -l ssh_tag (test "$cur_ssh" = "active"; and echo "\e[1;32m[ ACTIVO ]\e[0m"; or echo "\e[1;30m[ INACTIVO ]\e[0m")
                set -l ufw_tag (test "$cur_ufw" = "active"; and echo "\e[1;32m[ ACTIVO ]\e[0m"; or echo "\e[1;30m[ INACTIVO ]\e[0m")

                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                if test $is_es -eq 1
                    echo -e "   \e[1;37mESTADO DEL ACCESO REMOTO (SSH & FIREWALL)\e[0m"
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                    echo -e "    Estado servicio SSH:      $ssh_tag"
                    echo -e "    Estado Firewall (UFW):    $ufw_tag"
                    echo -e "    Dirección IP local:       \e[1;33m$my_ip\e[0m\n"
                    if test "$cur_ssh" = "active"
                        echo -e "    \e[0;37m(Para entrar desde otra PC de tu red: \e[1;36mssh $USER@$my_ip\e[0m\e[0;37m)\e[0m\n"
                        echo -e "    \e[1;33m[1]\e[0m \e[1;37mDesactivar SSH\e[0m \e[0;37m(Apagar acceso remoto por red)\e[0m"
                    else
                        echo -e "    \e[1;32m[1]\e[0m \e[1;37mActivar SSH\e[0m \e[0;37m(Encender acceso remoto y permitir puerto 22)\e[0m"
                    end
                    if test "$cur_ufw" = "active"
                        echo -e "    \e[1;31m[2]\e[0m \e[1;37mDesactivar Firewall UFW\e[0m \e[0;37m(Desproteger puertos locales)\e[0m"
                    else
                        echo -e "    \e[1;32m[2]\e[0m \e[1;37mActivar Firewall UFW\e[0m \e[0;37m(Proteger sistema y bloquear accesos no deseados)\e[0m"
                    end
                    echo -e "    \e[1;36m[3]\e[0m \e[1;37mVer reglas detalladas del Firewall (ufw status verbose)\e[0m"
                    echo -e "    \e[1;33m[0]\e[0m \e[1;37mVolver al Centro de Mando\e[0m\n"
                else
                    echo -e "   \e[1;37mREMOTE ACCESS STATUS (SSH & FIREWALL)\e[0m"
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                    echo -e "    SSH service status:       $ssh_tag"
                    echo -e "    Firewall (UFW) status:    $ufw_tag"
                    echo -e "    Local IP address:         \e[1;33m$my_ip\e[0m\n"
                    if test "$cur_ssh" = "active"
                        echo -e "    \e[0;37m(To connect from another computer: \e[1;36mssh $USER@$my_ip\e[0m\e[0;37m)\e[0m\n"
                        echo -e "    \e[1;33m[1]\e[0m \e[1;37mDisable SSH\e[0m \e[0;37m(Turn off remote network access)\e[0m"
                    else
                        echo -e "    \e[1;32m[1]\e[0m \e[1;37mEnable SSH\e[0m \e[0;37m(Turn on remote access and allow port 22)\e[0m"
                    end
                    if test "$cur_ufw" = "active"
                        echo -e "    \e[1;31m[2]\e[0m \e[1;37mDisable UFW Firewall\e[0m \e[0;37m(Unprotect local ports)\e[0m"
                    else
                        echo -e "    \e[1;32m[2]\e[0m \e[1;37mEnable UFW Firewall\e[0m \e[0;37m(Protect system and block unwanted traffic)\e[0m"
                    end
                    echo -e "    \e[1;36m[3]\e[0m \e[1;37mView detailed Firewall rules (ufw status verbose)\e[0m"
                    echo -e "    \e[1;33m[0]\e[0m \e[1;37mReturn to Control Center\e[0m\n"
                end
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                echo ""
                set -l prompt_ssh_act (test $is_es -eq 1; and echo "  \e[1;31m> Selecciona una opción [1-3, 0]: \e[0m"; or echo "  \e[1;31m> Select an option [1-3, 0]: \e[0m")
                read -l -P (echo -e "$prompt_ssh_act") ssh_action
                test $status -ne 0; and break

                switch "$ssh_action"
                    case 1
                        if test "$cur_ssh" = "active"
                            sudo systemctl disable --now sshd
                            if test $is_es -eq 1
                                echo -e "\n  \e[1;31m[OK] Servicio SSH desactivado con éxito.\e[0m"
                            else
                                echo -e "\n  \e[1;31m[OK] SSH service disabled successfully.\e[0m"
                            end
                        else
                            sudo systemctl enable --now sshd
                            if test (systemctl is-active ufw 2>/dev/null) = "active"
                                sudo ufw allow 22/tcp >/dev/null 2>&1
                                sudo ufw reload >/dev/null 2>&1
                            end
                            if test $is_es -eq 1
                                echo -e "\n  \e[1;32m[OK] ¡Servicio SSH activado con éxito!\e[0m"
                                echo -e "  Tu IP local es: \e[1;33m$my_ip\e[0m"
                            else
                                echo -e "\n  \e[1;32m[OK] SSH service enabled successfully!\e[0m"
                                echo -e "  Your local IP is: \e[1;33m$my_ip\e[0m"
                            end
                        end
                        sleep 1
                    case 2
                        if test "$cur_ufw" = "active"
                            sudo ufw disable
                            sudo systemctl disable --now ufw 2>/dev/null
                            if test $is_es -eq 1
                                echo -e "\n  \e[1;31m[OK] Firewall UFW desactivado.\e[0m"
                            else
                                echo -e "\n  \e[1;31m[OK] UFW Firewall disabled.\e[0m"
                            end
                        else
                            sudo systemctl enable --now ufw 2>/dev/null
                            sudo ufw --force enable
                            if test "$cur_ssh" = "active"
                                sudo ufw allow 22/tcp >/dev/null 2>&1
                            end
                            if test $is_es -eq 1
                                echo -e "\n  \e[1;32m[OK] ¡Firewall UFW activado y protegiendo el sistema!\e[0m"
                            else
                                echo -e "\n  \e[1;32m[OK] UFW Firewall enabled and protecting the system!\e[0m"
                            end
                        end
                        sleep 1
                    case 3
                        clear
                        echo ""
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        if test $is_es -eq 1
                            echo -e "   \e[1;37mREGLAS DEL FIREWALL (UFW STATUS VERBOSE)\e[0m"
                        else
                            echo -e "   \e[1;37mFIREWALL RULES (UFW STATUS VERBOSE)\e[0m"
                        end
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                        sudo ufw status verbose | sed 's/^/    /'
                        echo -e "\n  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        set -l prompt_ufw_back (test $is_es -eq 1; and echo "  Presiona Enter para volver..."; or echo "  Press Enter to return...")
                        read -l -P "$prompt_ufw_back" dummy
                    case 0 'q' 'Q' ''
                        break
                    case '*'
                        continue
                end
            end
        case 4 'u' 'U'
            clear
            echo ""
            echo ""
            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
            if test $is_es -eq 1
                echo -e "   \e[1;37mX64 LIOS - ACTUALIZACIÓN DEL SISTEMA\e[0m"
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                echo -e "    Esta herramienta sincronizará los repositorios oficiales de X64 LIOS"
                echo -e "    y actualizará todos los paquetes creando un snapshot previo con Snapper.\n"
                echo -e "    \e[1;32m[1]\e[0m \e[1;37mIniciar actualización completa del sistema\e[0m"
                echo -e "    \e[1;33m[0]\e[0m \e[1;37mVolver al Centro de Mando\e[0m\n"
            else
                echo -e "   \e[1;37mX64 LIOS - SYSTEM UPDATE\e[0m"
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                echo -e "    This tool will synchronize official X64 LIOS repositories"
                echo -e "    and update all packages with an automatic Snapper safety snapshot.\n"
                echo -e "    \e[1;32m[1]\e[0m \e[1;37mStart full system update\e[0m"
                echo -e "    \e[1;33m[0]\e[0m \e[1;37mReturn to Control Center\e[0m\n"
            end
            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
            echo ""
            set -l prompt_upd (test $is_es -eq 1; and echo "  \e[1;31m> Selecciona una opción [1, 0]: \e[0m"; or echo "  \e[1;31m> Select an option [1, 0]: \e[0m")
            read -l -P (echo -e "$prompt_upd") u_choice
            if test "$u_choice" = "1"
                if test $is_es -eq 1
                    echo -e "\n    \e[1;36mConectando con repositorios y actualizando paquetes...\e[0m\n"
                else
                    echo -e "\n    \e[1;36mConnecting to repositories and updating packages...\e[0m\n"
                end
                if type -q x64-update
                    x64-update
                else
                    sudo pacman -Syu
                end
                if test -d /usr/share/omarchy/.git
                    if test $is_es -eq 1
                        echo -e "\n    \e[1;36mActualizando shell X64 LIOS + Omarchy desde el repositorio oficial...\e[0m"
                    else
                        echo -e "\n    \e[1;36mUpdating X64 LIOS + Omarchy shell from official repository...\e[0m"
                    end
                    sudo git config --system --add safe.directory /usr/share/omarchy 2>/dev/null
                    sudo git -C /usr/share/omarchy pull origin main
                    sudo python3 /usr/share/omarchy/bin/x64-omarchy-setup.py --user $USER --skip-packages 2>/dev/null
                end
                if test $is_es -eq 1
                    echo -e "\n    \e[1;32m¡Actualización completada con éxito!\e[0m"
                    read -l -P "  Presiona Enter para volver..." dummy
                else
                    echo -e "\n    \e[1;32mSystem update completed successfully!\e[0m"
                    read -l -P "  Press Enter to return..." dummy
                end
                exec x64-dashboard
            end
        case 5 'n' 'N'
            while true
                clear
                echo ""
                echo ""
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                if test $is_es -eq 1
                    echo -e "   \e[1;37mDIAGNÓSTICO Y CONFIGURACIÓN DE RED\e[0m"
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                    echo -e "    \e[1;33mInterfaces y direcciones IP activas:\e[0m"
                    ip -br addr | sed 's/^/      /'
                    echo ""
                    echo -e "    \e[1;36m[1]\e[0m \e[1;37mProbar conectividad a Internet (Ping a 1.1.1.1)\e[0m"
                    echo -e "    \e[1;32m[2]\e[0m \e[1;37mConectar a Red Wi-Fi o Cableada (Asistente Visual nmtui)\e[0m"
                    echo -e "    \e[1;33m[3]\e[0m \e[1;37mReiniciar servicio de red (NetworkManager)\e[0m"
                    echo -e "    \e[1;31m[0]\e[0m \e[1;37mVolver al Centro de Mando\e[0m\n"
                else
                    echo -e "   \e[1;37mNETWORK DIAGNOSTICS & CONFIGURATION\e[0m"
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                    echo -e "    \e[1;33mActive interfaces and IP addresses:\e[0m"
                    ip -br addr | sed 's/^/      /'
                    echo ""
                    echo -e "    \e[1;36m[1]\e[0m \e[1;37mTest Internet connectivity (Ping 1.1.1.1)\e[0m"
                    echo -e "    \e[1;32m[2]\e[0m \e[1;37mConnect to Wi-Fi or Wired Network (Visual Wizard nmtui)\e[0m"
                    echo -e "    \e[1;33m[3]\e[0m \e[1;37mRestart network service (NetworkManager)\e[0m"
                    echo -e "    \e[1;31m[0]\e[0m \e[1;37mReturn to Control Center\e[0m\n"
                end
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                echo ""
                set -l prompt_net (test $is_es -eq 1; and echo "  \e[1;31m> Selecciona una opción [1-3, 0]: \e[0m"; or echo "  \e[1;31m> Select an option [1-3, 0]: \e[0m")
                read -l -P (echo -e "$prompt_net") net_choice
                test $status -ne 0; and break

                switch "$net_choice"
                    case 1
                        clear
                        echo ""
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        if test $is_es -eq 1
                            echo -e "   \e[1;37mPRUEBA DE CONECTIVIDAD A INTERNET\e[0m"
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                            echo -e "    Enviando 3 paquetes ICMP a Cloudflare DNS (1.1.1.1)...\n"
                        else
                            echo -e "   \e[1;37mINTERNET CONNECTIVITY TEST\e[0m"
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                            echo -e "    Sending 3 ICMP packets to Cloudflare DNS (1.1.1.1)...\n"
                        end
                        ping -c 3 1.1.1.1 | sed 's/^/    /'
                        echo -e "\n  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        set -l prompt_ping_back (test $is_es -eq 1; and echo "  Presiona Enter para continuar..."; or echo "  Press Enter to continue...")
                        read -l -P "$prompt_ping_back" dummy
                    case 2
                        if type -q nmtui
                            nmtui
                        else
                            if test $is_es -eq 1
                                echo -e "\n  \e[1;31m[!] NetworkManager TUI (nmtui) no está disponible en este sistema.\e[0m"
                            else
                                echo -e "\n  \e[1;31m[!] NetworkManager TUI (nmtui) is not available on this system.\e[0m"
                            end
                            sleep 2
                        end
                    case 3
                        if test $is_es -eq 1
                            echo -e "\n  \e[1;33m[*] Reiniciando NetworkManager...\e[0m"
                        else
                            echo -e "\n  \e[1;33m[*] Restarting NetworkManager...\e[0m"
                        end
                        sudo systemctl restart NetworkManager
                        sleep 2
                        if test $is_es -eq 1
                            echo -e "  \e[1;32m[OK] Servicio de red reiniciado con éxito.\e[0m"
                        else
                            echo -e "  \e[1;32m[OK] Network service restarted successfully.\e[0m"
                        end
                        sleep 1
                    case 0 'q' 'Q' ''
                        break
                    case '*'
                        continue
                end
            end
        case 6 'l' 'L'
            while true
                clear
                echo ""
                echo ""
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"

                set -l pkg_cache_size (du -sh /var/cache/pacman/pkg 2>/dev/null | cut -f1)
                test -z "$pkg_cache_size"; and set pkg_cache_size "0B"

                set -l journal_size (journalctl --disk-usage 2>/dev/null | grep -o '[0-9.]\+[KMGTPiB]\+' | head -n 1)
                test -z "$journal_size"; and set journal_size "0B"

                set -l orphans (pacman -Qtdq 2>/dev/null)
                set -l orphan_count (count $orphans)

                if test $is_es -eq 1
                    echo -e "   \e[1;37mMANTENIMIENTO Y LIMPIEZA DEL SISTEMA\e[0m"
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                    echo -e "    \e[1;33mTelemetría de Almacenamiento y Paquetes:\e[0m"
                    echo -e "      • Caché de paquetes Pacman:    \e[1;37m$pkg_cache_size\e[0m"
                    echo -e "      • Registros de Journalctl:     \e[1;37m$journal_size\e[0m"
                    if test $orphan_count -eq 0
                        echo -e "      • Paquetes huérfanos:          \e[1;32m0 (Sistema limpio)\e[0m\n"
                    else
                        echo -e "      • Paquetes huérfanos:          \e[1;31m$orphan_count detectados\e[0m\n"
                    end
                    echo -e "    \e[1;33m[1]\e[0m \e[1;37mLimpieza profunda completa (Caché + Huérfanos + Registros)\e[0m"
                    echo -e "    \e[1;33m[2]\e[0m \e[1;37mDetectar y purgar paquetes huérfanos (pacman -Qtdq)\e[0m"
                    echo -e "    \e[1;33m[3]\e[0m \e[1;37mOptimizar y vaciar caché de Pacman (pacman -Sc)\e[0m"
                    echo -e "    \e[1;33m[4]\e[0m \e[1;37mCompactar registros del sistema Journalctl (últimos 7 días)\e[0m"
                    echo -e "    \e[1;31m[0]\e[0m \e[1;37mVolver al Centro de Mando\e[0m\n"
                else
                    echo -e "   \e[1;37mSYSTEM MAINTENANCE & CLEANUP\e[0m"
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                    echo -e "    \e[1;33mStorage & Package Telemetry:\e[0m"
                    echo -e "      • Pacman package cache:        \e[1;37m$pkg_cache_size\e[0m"
                    echo -e "      • Journalctl system logs:      \e[1;37m$journal_size\e[0m"
                    if test $orphan_count -eq 0
                        echo -e "      • Orphan packages:             \e[1;32m0 (System clean)\e[0m\n"
                    else
                        echo -e "      • Orphan packages:             \e[1;31m$orphan_count detected\e[0m\n"
                    end
                    echo -e "    \e[1;33m[1]\e[0m \e[1;37mFull deep system cleanup (Cache + Orphans + Logs)\e[0m"
                    echo -e "    \e[1;33m[2]\e[0m \e[1;37mDetect and purge orphaned packages (pacman -Qtdq)\e[0m"
                    echo -e "    \e[1;33m[3]\e[0m \e[1;37mOptimize and clean Pacman package cache (pacman -Sc)\e[0m"
                    echo -e "    \e[1;33m[4]\e[0m \e[1;37mVacuum Journalctl system logs (retain last 7 days)\e[0m"
                    echo -e "    \e[1;31m[0]\e[0m \e[1;37mReturn to Control Center\e[0m\n"
                end
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                echo ""
                set -l prompt_clean (test $is_es -eq 1; and echo "  \e[1;31m> Selecciona una opción [1-4, 0]: \e[0m"; or echo "  \e[1;31m> Select an option [1-4, 0]: \e[0m")
                read -l -P (echo -e "$prompt_clean") l_choice
                test $status -ne 0; and break

                switch "$l_choice"
                    case 1
                        clear
                        echo ""
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        if test $is_es -eq 1
                            echo -e "   \e[1;37mLIMPIEZA PROFUNDA COMPLETA DEL SISTEMA\e[0m"
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                            echo -e "    \e[1;36m1. Limpiando descargas parciales e incompletas...\e[0m"
                            sudo sh -c 'rm -f /var/cache/pacman/pkg/*.part /var/cache/pacman/pkg/*.download 2>/dev/null'
                            echo -e "       \e[1;32m[OK] Paquetes temporales limpios.\e[0m\n"

                            echo -e "    \e[1;36m2. Analizando paquetes huérfanos sin dependencias...\e[0m"
                            set -l cur_orphans (pacman -Qtdq 2>/dev/null)
                            set -l num_orphans (count $cur_orphans)
                            if test $num_orphans -gt 0
                                echo -e "       Purgando $num_orphans paquetes huérfanos..."
                                sudo pacman -Rns --noconfirm $cur_orphans | sed 's/^/       /'
                                echo -e "       \e[1;32m[OK] Paquetes huérfanos eliminados.\e[0m\n"
                            else
                                echo -e "       \e[1;32m[OK] Sin paquetes huérfanos en el sistema.\e[0m\n"
                            end

                            echo -e "    \e[1;36m3. Purgando caché de paquetes descargados antiguos...\e[0m"
                            sudo pacman -Sc --noconfirm | sed 's/^/       /'
                            echo ""

                            echo -e "    \e[1;36m4. Compactando registros del sistema (journalctl)...\e[0m"
                            sudo journalctl --vacuum-time=1w | sed 's/^/       /'

                            echo -e "\n    \e[1;32m¡Limpieza profunda finalizada con éxito!\e[0m\n"
                        else
                            echo -e "   \e[1;37mFULL DEEP SYSTEM CLEANUP\e[0m"
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                            echo -e "    \e[1;36m1. Purging partial and incomplete downloads...\e[0m"
                            sudo sh -c 'rm -f /var/cache/pacman/pkg/*.part /var/cache/pacman/pkg/*.download 2>/dev/null'
                            echo -e "       \e[1;32m[OK] Temporary files cleared.\e[0m\n"

                            echo -e "    \e[1;36m2. Checking orphaned packages without dependencies...\e[0m"
                            set -l cur_orphans (pacman -Qtdq 2>/dev/null)
                            set -l num_orphans (count $cur_orphans)
                            if test $num_orphans -gt 0
                                echo -e "       Purging $num_orphans orphan packages..."
                                sudo pacman -Rns --noconfirm $cur_orphans | sed 's/^/       /'
                                echo -e "       \e[1;32m[OK] Orphan packages removed.\e[0m\n"
                            else
                                echo -e "       \e[1;32m[OK] No orphan packages found.\e[0m\n"
                            end

                            echo -e "    \e[1;36m3. Cleaning old downloaded package cache...\e[0m"
                            sudo pacman -Sc --noconfirm | sed 's/^/       /'
                            echo ""

                            echo -e "    \e[1;36m4. Vacuuming system logs (journalctl)...\e[0m"
                            sudo journalctl --vacuum-time=1w | sed 's/^/       /'

                            echo -e "\n    \e[1;32mDeep cleanup finished successfully!\e[0m\n"
                        end
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        set -l prompt_clean_back (test $is_es -eq 1; and echo "  Presiona Enter para continuar..."; or echo "  Press Enter to continue...")
                        read -l -P "$prompt_clean_back" dummy
                    case 2
                        set -l cur_orphans (pacman -Qtdq 2>/dev/null)
                        set -l num_orphans (count $cur_orphans)
                        if test $num_orphans -eq 0
                            if test $is_es -eq 1
                                echo -e "\n  \e[1;32m[OK] No se detectaron paquetes huérfanos. Tu sistema está 100% limpio.\e[0m"
                            else
                                echo -e "\n  \e[1;32m[OK] No orphan packages detected. Your system is 100% clean.\e[0m"
                            end
                            sleep 2
                        else
                            clear
                            echo ""
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                            if test $is_es -eq 1
                                echo -e "   \e[1;37mPAQUETES HUÉRFANOS DETECTADOS\e[0m"
                                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                                echo -e "    Los siguientes paquetes ya no son requeridos por ningún software instalado:\n"
                                for p in $cur_orphans
                                    echo -e "      \e[1;33m•\e[0m \e[1;37m$p\e[0m"
                                end
                                echo ""
                                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                                read -l -P "  ¿Deseas desinstalar estos paquetes huérfanos y sus dependencias? [s/N]: " confirm_orphan
                                if test "$confirm_orphan" = "s" -o "$confirm_orphan" = "S" -o "$confirm_orphan" = "y" -o "$confirm_orphan" = "Y"
                                    echo -e "\n  \e[1;36m[*] Desinstalando paquetes huérfanos...\e[0m\n"
                                    sudo pacman -Rns --noconfirm $cur_orphans | sed 's/^/    /'
                                    echo -e "\n  \e[1;32m[OK] Paquetes huérfanos purgados con éxito.\e[0m"
                                else
                                    echo -e "\n  \e[1;33mOperación cancelada por el usuario.\e[0m"
                                end
                            else
                                echo -e "   \e[1;37mORPHAN PACKAGES DETECTED\e[0m"
                                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                                echo -e "    The following packages are no longer required by any installed software:\n"
                                for p in $cur_orphans
                                    echo -e "      \e[1;33m•\e[0m \e[1;37m$p\e[0m"
                                end
                                echo ""
                                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                                read -l -P "  Do you want to purge these orphan packages and their unused deps? [y/N]: " confirm_orphan
                                if test "$confirm_orphan" = "y" -o "$confirm_orphan" = "Y" -o "$confirm_orphan" = "s" -o "$confirm_orphan" = "S"
                                    echo -e "\n  \e[1;36m[*] Purging orphan packages...\e[0m\n"
                                    sudo pacman -Rns --noconfirm $cur_orphans | sed 's/^/    /'
                                    echo -e "\n  \e[1;32m[OK] Orphan packages purged successfully.\e[0m"
                                else
                                    echo -e "\n  \e[1;33mOperation cancelled by user.\e[0m"
                                end
                            end
                            set -l prompt_back (test $is_es -eq 1; and echo "  Presiona Enter para continuar..."; or echo "  Press Enter to continue...")
                            read -l -P "$prompt_back" dummy
                        end
                    case 3
                        clear
                        echo ""
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        if test $is_es -eq 1
                            echo -e "   \e[1;37mLIMPIEZA DE CACHÉ DE PACMAN\e[0m"
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                            echo -e "    Purgando paquetes parciales corruptos y paquetes desinstalados de la caché...\n"
                            sudo sh -c 'rm -f /var/cache/pacman/pkg/*.part /var/cache/pacman/pkg/*.download 2>/dev/null'
                            sudo pacman -Sc --noconfirm | sed 's/^/    /'
                            echo -e "\n  \e[1;32m[OK] Caché de paquetes optimizada.\e[0m"
                        else
                            echo -e "   \e[1;37mPACMAN PACKAGE CACHE CLEANUP\e[0m"
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                            echo -e "    Purging partial downloads and outdated cached packages...\n"
                            sudo sh -c 'rm -f /var/cache/pacman/pkg/*.part /var/cache/pacman/pkg/*.download 2>/dev/null'
                            sudo pacman -Sc --noconfirm | sed 's/^/    /'
                            echo -e "\n  \e[1;32m[OK] Package cache optimized.\e[0m"
                        end
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        set -l prompt_back (test $is_es -eq 1; and echo "  Presiona Enter para continuar..."; or echo "  Press Enter to continue...")
                        read -l -P "$prompt_back" dummy
                    case 4
                        clear
                        echo ""
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        if test $is_es -eq 1
                            echo -e "   \e[1;37mCOMPACTACIÓN DE REGISTROS JOURNALCTL\e[0m"
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                            echo -e "    Purgando registros de eventos anteriores a 7 días...\n"
                            sudo journalctl --vacuum-time=1w | sed 's/^/    /'
                            echo -e "\n  \e[1;32m[OK] Registros de journalctl compactados con éxito.\e[0m"
                        else
                            echo -e "   \e[1;37mVACUUM JOURNALCTL LOGS\e[0m"
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                            echo -e "    Purging log events older than 7 days...\n"
                            sudo journalctl --vacuum-time=1w | sed 's/^/    /'
                            echo -e "\n  \e[1;32m[OK] Journalctl logs vacuumed successfully.\e[0m"
                        end
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        set -l prompt_back (test $is_es -eq 1; and echo "  Presiona Enter para continuar..."; or echo "  Press Enter to continue...")
                        read -l -P "$prompt_back" dummy
                    case 0 'q' 'Q' ''
                        break
                    case '*'
                        continue
                end
            end
        case 7 'e' 'E'
            while true
                clear
                echo ""
                echo ""
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"

                set -l failed_units (systemctl --failed --no-legend 2>/dev/null | awk '{print $2}')
                set -l failed_count (count $failed_units)

                set -l crit_count (journalctl -p 3 -b -q --no-pager 2>/dev/null | count)

                if test $is_es -eq 1
                    echo -e "   \e[1;37mDIAGNÓSTICO DE ERRORES Y SALUD DEL SISTEMA\e[0m"
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                    echo -e "    \e[1;33mTelemetría de Salud del Sistema:\e[0m"
                    if test $failed_count -eq 0
                        echo -e "      • Servicios caídos (systemd):  \e[1;32m0 fallos (Sistema 100% saludable)\e[0m"
                    else
                        echo -e "      • Servicios caídos (systemd):  \e[1;31m$failed_count fallos detectados\e[0m"
                    end
                    if test $crit_count -eq 0
                        echo -e "      • Alertas y errores del boot:  \e[1;32m0 eventos (Arranque limpio)\e[0m\n"
                    else
                        echo -e "      • Alertas y errores del boot:  \e[1;33m$crit_count eventos registrados\e[0m\n"
                    end

                    echo -e "    \e[1;33m[1]\e[0m \e[1;37mVisor de errores críticos del arranque (journalctl -p 3 -xb)\e[0m"
                    echo -e "    \e[1;33m[2]\e[0m \e[1;37mInspeccionar servicios caídos de systemd (systemctl --failed)\e[0m"
                    echo -e "    \e[1;33m[3]\e[0m \e[1;37mRegistro completo del arranque actual (journalctl -b)\e[0m"
                    echo -e "    \e[1;33m[4]\e[0m \e[1;37mRegistro del arranque previo o crash (journalctl -b -1)\e[0m"
                    echo -e "    \e[1;31m[0]\e[0m \e[1;37mVolver al Centro de Mando\e[0m\n"
                else
                    echo -e "   \e[1;37mSYSTEM HEALTH & ERROR DIAGNOSTICS\e[0m"
                    echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                    echo -e "    \e[1;33mSystem Health Telemetry:\e[0m"
                    if test $failed_count -eq 0
                        echo -e "      • Failed services (systemd):   \e[1;32m0 failures (100% healthy)\e[0m"
                    else
                        echo -e "      • Failed services (systemd):   \e[1;31m$failed_count failures detected\e[0m"
                    end
                    if test $crit_count -eq 0
                        echo -e "      • Boot warnings and errors:    \e[1;32m0 events (Clean boot)\e[0m\n"
                    else
                        echo -e "      • Boot warnings and errors:    \e[1;33m$crit_count events recorded\e[0m\n"
                    end

                    echo -e "    \e[1;33m[1]\e[0m \e[1;37mCritical boot errors viewer (journalctl -p 3 -xb)\e[0m"
                    echo -e "    \e[1;33m[2]\e[0m \e[1;37mInspect failed systemd services (systemctl --failed)\e[0m"
                    echo -e "    \e[1;33m[3]\e[0m \e[1;37mFull current boot log (journalctl -b)\e[0m"
                    echo -e "    \e[1;33m[4]\e[0m \e[1;37mPrevious boot / crash log (journalctl -b -1)\e[0m"
                    echo -e "    \e[1;31m[0]\e[0m \e[1;37mReturn to Control Center\e[0m\n"
                end
                echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                echo ""
                set -l prompt_diag (test $is_es -eq 1; and echo "  \e[1;31m> Selecciona una opción [1-4, 0]: \e[0m"; or echo "  \e[1;31m> Select an option [1-4, 0]: \e[0m")
                read -l -P (echo -e "$prompt_diag") d_choice
                test $status -ne 0; and break

                switch "$d_choice"
                    case 1
                        x64_log_viewer errors
                    case 2
                        clear
                        echo ""
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                        if test $is_es -eq 1
                            echo -e "   \e[1;37mINSPECCIÓN DE SERVICIOS CAÍDOS (SYSTEMCTL --FAILED)\e[0m"
                        else
                            echo -e "   \e[1;37mFAILED SERVICES INSPECTION (SYSTEMCTL --FAILED)\e[0m"
                        end
                        echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m\n"
                        set -l cur_failed (systemctl --failed --no-legend 2>/dev/null)
                        if test (count $cur_failed) -eq 0
                            if test $is_es -eq 1
                                echo -e "    \e[1;32m[OK] No hay ningún servicio en estado fallido.\e[0m"
                                echo -e "    Todos los servicios de systemd se están ejecutando correctamente.\n"
                            else
                                echo -e "    \e[1;32m[OK] No services are currently in a failed state.\e[0m"
                                echo -e "    All systemd units are running properly.\n"
                            end
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                            set -l prompt_back (test $is_es -eq 1; and echo "  Presiona Enter para continuar..."; or echo "  Press Enter to continue...")
                            read -l -P "$prompt_back" dummy
                        else
                            systemctl --failed -l --no-pager | sed 's/^/    /'
                            echo ""
                            echo -e "  \e[1;31m─────────────────────────────────────────────────────────────────────────────\e[0m"
                            set -l prompt_reset (test $is_es -eq 1; and echo "  ¿Deseas resetear el estado de fallos (systemctl reset-failed)? [s/N]: "; or echo "  Do you want to reset failed status (systemctl reset-failed)? [y/N]: ")
                            read -l -P "$prompt_reset" do_reset
                            if test "$do_reset" = "s" -o "$do_reset" = "S" -o "$do_reset" = "y" -o "$do_reset" = "Y"
                                sudo systemctl reset-failed
                                if test $is_es -eq 1
                                    echo -e "  \e[1;32m[OK] Contador de fallos de systemd reseteado.\e[0m"
                                else
                                    echo -e "  \e[1;32m[OK] Systemd failed units counter reset.\e[0m"
                                end
                                sleep 1.5
                            end
                        end
                    case 3
                        x64_log_viewer current
                    case 4
                        x64_log_viewer previous
                    case 0 'q' 'Q' ''
                        break
                    case '*'
                        continue
                end
            end
        case '*'
            continue
    end
end
