#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
x64-update: Gestor Oficial y Notificador de Actualizaciones de X64 LIOS.
Desarrollado para X64 Studios.
Interfaz Gráfica Nativa 100% Integrada (PyQt6) con Consola Embebida en Vivo y Soporte CLI / Headless.
"""

import sys
import os
import shutil
import subprocess
import time
import argparse
import tempfile
import threading
import pty
import re
import fcntl
import termios
import struct

STATE_DIR = os.path.expanduser("~/.local/state/x64-update")
COUNT_FILE = os.path.join(STATE_DIR, "count")
PACKAGES_FILE = os.path.join(STATE_DIR, "packages.txt")
LAST_CHECK_FILE = os.path.join(STATE_DIR, "last_check")

# ANSI Color Codes for CLI fallback
C_RESET   = "\033[0m"
C_BOLD    = "\033[1m"
C_DIM     = "\033[2m"
C_RED     = "\033[1;31m"
C_GREEN   = "\033[1;32m"
C_YELLOW  = "\033[1;33m"
C_BLUE    = "\033[1;34m"
C_MAGENTA = "\033[1;35m"
C_CYAN    = "\033[1;36m"
C_WHITE   = "\033[1;37m"
C_LIGHT   = "\033[37m"
C_GRAY    = "\033[1;30m"

BANNER = rf"""{C_RED}
  ██╗  ██╗ ██████╗ ██╗  ██╗     ██╗   ██╗██████╗ ██████╗  █████╗ ████████╗███████╗
  ╚██╗██╔╝██╔════╝ ██║  ██║     ██║   ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝
   ╚███╔╝ ███████╗ ███████║     ██║   ██║██████╔╝██║  ██║███████║   ██║   █████╗  
   ██╔██╗ ██╔═══██╗╚════██║     ██║   ██║██╔═══╝ ██║  ██║██╔══██║   ██║   ██╔══╝  
  ██╔╝ ██╗╚██████╔╝     ██║     ╚██████╔╝██║     ██████╔╝██║  ██║   ██║   ███████╗
  ╚═╝  ╚═╝ ╚═════╝      ╚═╝      ╚═════╝ ╚═╝     ╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚══════╝{C_RESET}
{C_GRAY}  {'─' * 82}{C_RESET}
{C_WHITE}{C_BOLD}{'CENTRO DE ACTUALIZACIONES OFICIAL X64 LIOS':^86}{C_RESET}
{C_GRAY}  {'─' * 82}{C_RESET}"""

def ensure_state_dir():
    os.makedirs(STATE_DIR, exist_ok=True)

def wait_for_user(msg="Presione [Enter] para cerrar esta ventana..."):
    print()
    try:
        input(f"  {C_CYAN}▶{C_RESET} {C_WHITE}{msg}{C_RESET} ")
    except (KeyboardInterrupt, EOFError):
        pass

def get_telemetry():
    kernel = "Linux Desconocido"
    try:
        raw_k = subprocess.check_output(["uname", "-r"], text=True).strip()
        raw_k = raw_k.replace("-cachyos", "").replace("cachyos", "")
        kernel = raw_k
    except Exception:
        pass

    arch = "x86_64"
    try:
        arch = subprocess.check_output(["uname", "-m"], text=True).strip()
    except Exception:
        pass

    uptime_str = "Desconocido"
    try:
        with open("/proc/uptime", "r") as f:
            secs = float(f.readline().split()[0])
            h = int(secs // 3600)
            m = int((secs % 3600) // 60)
            uptime_str = f"{h}h {m}m" if h > 0 else f"{m}m"
    except Exception:
        pass

    hostname = "x64-pc"
    try:
        hostname = subprocess.check_output(["uname", "-n"], text=True).strip()
    except Exception:
        pass

    return {
        "kernel": kernel,
        "arch": arch,
        "uptime": uptime_str,
        "hostname": hostname
    }

def is_x64_package(name):
    lower = name.lower()
    return lower.startswith("x64-") or lower.startswith("falcond") or lower == "calamares"

def is_critical_package(name):
    if is_x64_package(name):
        return False
    lower = name.lower()
    critical_stems = [
        "linux", "kernel", "nvidia", "mesa", "vulkan", "systemd",
        "glibc", "pipewire", "wayland", "dracut", "mkinitcpio",
        "grub", "limine", "refind", "btrfs", "zfs", "scx"
    ]
    for stem in critical_stems:
        if stem in lower:
            return True
    return False

def parse_pkg_line(line):
    line_clean = line.replace("(AUR)", "").replace("(Flatpak)", "").strip()
    parts = line_clean.split()
    if len(parts) >= 4 and parts[2] == "->":
        pkg = parts[0]
        old_v = parts[1]
        new_v = parts[3]
        return pkg, old_v, new_v
    elif len(parts) >= 2:
        return parts[0], parts[1], ""
    return line_clean, "", ""

def check_official_repos():
    repo_pkgs = []
    if not shutil.which("checkupdates"):
        return repo_pkgs

    tmp_db = tempfile.mkdtemp(prefix="x64-checkupdates-")
    env = os.environ.copy()
    env["CHECKUPDATES_DB"] = tmp_db
    try:
        res = subprocess.run(
            ["checkupdates"],
            env=env,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=50
        )
        for line in res.stdout.strip().splitlines():
            line = line.strip()
            if line:
                repo_pkgs.append(line)

        # Capturar reemplazos (replaces) y dependencias que checkupdates (pacman -Qu) omite
        db_to_use = tmp_db if os.path.isdir(os.path.join(tmp_db, "sync")) else None
        sup_cmd = ["pacman", "-Sup", "--print-format", "%n %v"]
        if db_to_use:
            sup_cmd.extend(["--dbpath", db_to_use])

        res_sup = subprocess.run(
            sup_cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=25
        )
        if res_sup.returncode == 0:
            existing_names = {line.split()[0] for line in repo_pkgs if line.split()}
            for sup_line in res_sup.stdout.strip().splitlines():
                parts = sup_line.strip().split()
                if len(parts) >= 2:
                    p_name, p_ver = parts[0], parts[1]
                    if p_name not in existing_names:
                        old_pkg = None
                        old_ver = ""
                        si_cmd = ["pacman", "-Si", p_name]
                        if db_to_use:
                            si_cmd.extend(["--dbpath", db_to_use])
                        si_res = subprocess.run(si_cmd, stdout=subprocess.PIPE, text=True, timeout=5)
                        for si_line in si_res.stdout.splitlines():
                            if si_line.startswith("Remplaza a") or si_line.startswith("Replaces"):
                                rep_val = si_line.split(":", 1)[1].strip()
                                if rep_val and rep_val not in ("Nada", "None"):
                                    old_pkg = rep_val.split()[0]
                                    break
                        if old_pkg:
                            q_res = subprocess.run(["pacman", "-Q", old_pkg], stdout=subprocess.PIPE, text=True, timeout=5)
                            if q_res.returncode == 0:
                                old_ver = q_res.stdout.strip().split()[1]
                                repo_pkgs.append(f"{p_name} {old_ver} -> {p_ver}")
                            else:
                                repo_pkgs.append(f"{p_name} [reemplazo] -> {p_ver}")
                        else:
                            repo_pkgs.append(f"{p_name} [nuevo] -> {p_ver}")
                        existing_names.add(p_name)
    except Exception:
        pass
    finally:
        shutil.rmtree(tmp_db, ignore_errors=True)

    return repo_pkgs

def check_aur_packages():
    aur_pkgs = []
    aur_helper = None
    if shutil.which("paru"):
        aur_helper = "paru"
    elif shutil.which("yay"):
        aur_helper = "yay"

    if not aur_helper:
        return aur_pkgs

    try:
        res = subprocess.run(
            [aur_helper, "-Qua"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=45
        )
        for line in res.stdout.strip().splitlines():
            line = line.strip()
            if line and not line.endswith("[ignored]"):
                aur_pkgs.append(line)
    except Exception:
        pass

    return aur_pkgs

def check_flatpak_packages():
    flatpak_pkgs = []
    if not shutil.which("flatpak"):
        return flatpak_pkgs

    try:
        res = subprocess.run(
            ["flatpak", "remote-ls", "--updates", "--columns=name,application,version"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=30
        )
        for line in res.stdout.strip().splitlines():
            parts = line.strip().split("\t")
            if parts and parts[0]:
                name = parts[0]
                ver = parts[2] if len(parts) > 2 else ""
                flatpak_pkgs.append(f"{name} {ver}".strip())
    except Exception:
        pass

    return flatpak_pkgs

def check_omarchy_git():
    """Comprueba si el repositorio X64 LIOS + Omarchy (/usr/share/omarchy) tiene commits pendientes en Git."""
    omarchy_git = "/usr/share/omarchy/.git"
    if not os.path.isdir(omarchy_git):
        return None
    try:
        local_cmd = ["git", "-C", "/usr/share/omarchy", "rev-parse", "HEAD"]
        local_hash = subprocess.check_output(local_cmd, text=True, stderr=subprocess.DEVNULL, timeout=5).strip()

        remote_cmd = ["git", "-C", "/usr/share/omarchy", "ls-remote", "-h", "origin", "refs/heads/main"]
        env = dict(os.environ, GIT_TERMINAL_PROMPT="0")
        remote_out = subprocess.check_output(remote_cmd, env=env, text=True, stderr=subprocess.DEVNULL, timeout=10).strip()
        if not remote_out:
            return None
        remote_hash = remote_out.split()[0].strip()
        if local_hash and remote_hash and local_hash != remote_hash:
            return f"x64-lios-omarchy {local_hash[:7]} -> {remote_hash[:7]}"
    except Exception:
        pass
    return None

def save_check_results(repo_pkgs, aur_pkgs, flatpak_pkgs):
    ensure_state_dir()
    all_pkgs = []
    for p in repo_pkgs:
        all_pkgs.append(p)
    for p in aur_pkgs:
        all_pkgs.append(f"{p} (AUR)")
    for p in flatpak_pkgs:
        all_pkgs.append(f"{p} (Flatpak)")

    total_count = len(all_pkgs)

    try:
        with open(COUNT_FILE, "w", encoding="utf-8") as f:
            f.write(f"{total_count}\n")
        with open(PACKAGES_FILE, "w", encoding="utf-8") as f:
            for p in all_pkgs:
                f.write(f"{p}\n")
        with open(LAST_CHECK_FILE, "w", encoding="utf-8") as f:
            f.write(f"{time.time()}\n")
    except Exception:
        pass

    return {
        "repo": repo_pkgs,
        "aur": aur_pkgs,
        "flatpak": flatpak_pkgs,
        "all": all_pkgs,
        "count": total_count
    }

def run_background_check_and_save():
    repo_pkgs = check_official_repos()
    omarchy_pkg = check_omarchy_git()
    if omarchy_pkg:
        repo_pkgs.insert(0, omarchy_pkg)
    aur_pkgs = check_aur_packages()
    flatpak_pkgs = check_flatpak_packages()
    return save_check_results(repo_pkgs, aur_pkgs, flatpak_pkgs)

ANSI_MAP = {
    '30': '#52525b', '31': '#ef4444', '32': '#22c55e', '33': '#facc15',
    '34': '#3b82f6', '35': '#d946ef', '36': '#06b6d4', '37': '#e4e4e7',
    '90': '#71717a', '91': '#f87171', '92': '#4ade80', '93': '#fde047',
    '94': '#60a5fa', '95': '#e879f9', '96': '#22d3ee', '97': '#ffffff',
}

# Bold + standard ANSI 30-37 maps to bright palette in modern terminals (like Kitty)
ANSI_BOLD_MAP = {
    '30': '#71717a', '31': '#f87171', '32': '#4ade80', '33': '#fde047',
    '34': '#60a5fa', '35': '#e879f9', '36': '#22d3ee', '37': '#ffffff',
}

def _xterm_256_to_hex(n):
    if n < 0 or n > 255:
        return '#d4d4d8'
    if n < 8:
        return ANSI_MAP.get(str(30 + n), '#d4d4d8')
    if n < 16:
        return ANSI_MAP.get(str(90 + (n - 8)), '#ffffff')
    if n < 232:
        n -= 16
        r_idx = n // 36
        g_idx = (n % 36) // 6
        b_idx = n % 6
        r = 0 if r_idx == 0 else 55 + r_idx * 40
        g = 0 if g_idx == 0 else 55 + g_idx * 40
        b = 0 if b_idx == 0 else 55 + b_idx * 40
        return f'#{r:02x}{g:02x}{b:02x}'
    # Grayscale ramp 232..255 (slightly lifted for dark background legibility, e.g. pacman 243)
    level = min(255, 18 + (n - 232) * 10)
    return f'#{level:02x}{level:02x}{min(255, level + 8):02x}'


class Vt100Screen:
    """True 2D VT100/ANSI Virtual Terminal Buffer for pixel-accurate pacman/paru/flatpak rendering."""

    def __init__(self, header_html=""):
        self.header_html = header_html
        self.lines = [[]]
        self.row = 0
        self.col = 0
        self.fg = None
        self.bold = False
        self.dim = False
        self.pending = ""
        self.cr_overwrite = False

    def feed(self, text):
        data = self.pending + text
        self.pending = ""

        # Hold back incomplete trailing CSI or OSC sequence across PTY read chunks
        m = re.search(r"(\x1b(?:\[[0-9;?]*|\][^\x07\x1b]{0,512}(?:\x1b)?)?)$", data, flags=re.DOTALL)
        if m:
            self.pending = m.group(1)
            data = data[:-len(self.pending)]

        if not data:
            return

        # 1. Strip complete OSC sequences (e.g. \x1b]3008;...\x1b\ or \x1b]0;...\x07)
        data = re.sub(r"\x1b\].*?(?:\x07|\x1b\\)", "", data, flags=re.DOTALL)
        # 2. Strip leftover literal shell notifications like []3008;end=...
        data = re.sub(r"\[\]\d+;[^\r\n]*", "", data)
        # 3. Strip DCS/PM/APC sequences
        data = re.sub(r"\x1b[PX^_].*?\x1b\\", "", data, flags=re.DOTALL)

        i = 0
        n = len(data)
        while i < n:
            ch = data[i]
            if ch == "\x1b":
                m_csi = re.match(r"\x1b\[([0-9;?]*)([A-Za-z@`])", data[i:])
                if m_csi:
                    self._handle_csi(m_csi.group(1), m_csi.group(2))
                    i += m_csi.end()
                    continue
                m_esc = re.match(r"\x1b(?:[\(\)][0-9A-Za-z]|[0-9A-Za-z=><\\])", data[i:])
                if m_esc:
                    i += m_esc.end()
                    continue
                i += 1
            elif ch == "\r":
                self.col = 0
                self.cr_overwrite = True
                i += 1
            elif ch == "\n":
                self.row += 1
                self.col = 0
                self.cr_overwrite = False
                while len(self.lines) <= self.row:
                    self.lines.append([])
                i += 1
            elif ch == "\b":
                self.col = max(0, self.col - 1)
                self.cr_overwrite = False
                i += 1
            elif ch == "\t":
                spaces = 8 - (self.col % 8)
                for _ in range(spaces):
                    self._put_char(" ")
                i += 1
            elif ord(ch) >= 32:
                self._put_char(ch)
                i += 1
            else:
                i += 1

    def _resolve_color(self):
        if self.fg is None:
            if self.bold:
                return "#ffffff"
            if self.dim:
                return "#71717a"
            return None
        if self.bold and self.fg in ANSI_BOLD_MAP:
            return ANSI_BOLD_MAP[self.fg]
        if self.fg in ANSI_MAP:
            return ANSI_MAP[self.fg]
        if self.fg.startswith("#"):
            return self.fg
        return None

    def _put_char(self, ch):
        while len(self.lines) <= self.row:
            self.lines.append([])
        line = self.lines[self.row]
        if self.cr_overwrite:
            line.clear()
            self.cr_overwrite = False
        while len(line) <= self.col:
            line.append((" ", None, False))
        line[self.col] = (ch, self._resolve_color(), self.bold)
        self.col += 1

    def _handle_csi(self, params, cmd):
        arg = params.lstrip("?")
        first_num = arg.split(";")[0] if arg else ""
        count = int(first_num) if first_num.isdigit() and int(first_num) > 0 else 1

        if cmd == "A":  # Cursor Up
            self.row = max(0, self.row - count)
            self.cr_overwrite = (self.col == 0)
        elif cmd == "B":  # Cursor Down
            self.row += count
            while len(self.lines) <= self.row:
                self.lines.append([])
            self.cr_overwrite = (self.col == 0)
        elif cmd == "C":  # Cursor Forward
            self.col += count
            self.cr_overwrite = False
        elif cmd == "D":  # Cursor Back
            self.col = max(0, self.col - count)
            self.cr_overwrite = False
        elif cmd == "E":  # Cursor Next Line (col 0)
            self.row += count
            self.col = 0
            self.cr_overwrite = True
            while len(self.lines) <= self.row:
                self.lines.append([])
        elif cmd == "F":  # Cursor Preceding Line (col 0)
            self.row = max(0, self.row - count)
            self.col = 0
            self.cr_overwrite = True
        elif cmd in ("G", "`"):  # Cursor Horizontal Absolute (1-based)
            self.col = max(0, count - 1)
            self.cr_overwrite = (self.col == 0)
        elif cmd == "K":  # Erase in Line
            while len(self.lines) <= self.row:
                self.lines.append([])
            line = self.lines[self.row]
            mode = int(first_num) if first_num.isdigit() else 0
            if mode == 0:
                if self.cr_overwrite and self.col == 0:
                    line.clear()
                    self.cr_overwrite = False
                else:
                    del line[self.col:]
            elif mode == 1:
                for c_idx in range(min(self.col + 1, len(line))):
                    line[c_idx] = (" ", None, False)
            elif mode == 2:
                line.clear()
                self.cr_overwrite = False
        elif cmd == "J":  # Erase in Display
            mode = int(first_num) if first_num.isdigit() else 0
            if mode in (2, 3):
                self.lines = [[]]
                self.row = 0
                self.col = 0
                self.cr_overwrite = False
        elif cmd == "m":  # SGR (Select Graphic Rendition)
            self._handle_sgr(params)

    def _handle_sgr(self, params):
        if not params or params == "0":
            self.fg = None
            self.bold = False
            self.dim = False
            return
        parts = params.split(";")
        idx = 0
        while idx < len(parts):
            p = parts[idx]
            if p in ("", "0"):
                self.fg = None
                self.bold = False
                self.dim = False
            elif p == "1":
                self.bold = True
            elif p == "2":
                self.dim = True
            elif p == "22":
                self.bold = False
                self.dim = False
            elif p == "39":
                self.fg = None
            elif p == "38" and idx + 2 < len(parts) and parts[idx + 1] == "5":
                if parts[idx + 2].isdigit():
                    self.fg = _xterm_256_to_hex(int(parts[idx + 2]))
                idx += 2
            elif p == "38" and idx + 4 < len(parts) and parts[idx + 1] == "2":
                try:
                    r = max(0, min(255, int(parts[idx + 2])))
                    g = max(0, min(255, int(parts[idx + 3])))
                    b = max(0, min(255, int(parts[idx + 4])))
                    self.fg = f"#{r:02x}{g:02x}{b:02x}"
                except ValueError:
                    pass
                idx += 4
            elif p in ANSI_MAP:
                self.fg = p
            idx += 1

    def to_html(self):
        out_lines = []
        for line in self.lines:
            if not line:
                out_lines.append("")
                continue
            row_parts = []
            cur_fg = None
            cur_bold = False
            buf = []

            def flush_run():
                if not buf:
                    return
                txt = "".join(buf).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
                if cur_fg or cur_bold:
                    styles = []
                    if cur_fg:
                        styles.append(f"color:{cur_fg}")
                    if cur_bold:
                        styles.append("font-weight:bold")
                    row_parts.append(f'<span style="{";".join(styles)}">{txt}</span>')
                else:
                    row_parts.append(txt)

            for ch, fg, bold in line:
                if fg != cur_fg or bold != cur_bold:
                    flush_run()
                    buf = [ch]
                    cur_fg = fg
                    cur_bold = bold
                else:
                    buf.append(ch)
            flush_run()
            out_lines.append("".join(row_parts))

        body = "\n".join(out_lines)
        return (
            f"{self.header_html}"
            f'<pre style="margin: 0; font-family: \'JetBrainsMono Nerd Font\', \'Noto Sans Mono\', monospace; '
            f'font-size: 12px; line-height: 1.38; color: #d4d4d8; white-space: pre;">{body}</pre>'
        )


def ansi_to_html(text):
    vt = Vt100Screen()
    vt.feed(text)
    return vt.to_html()


# ==============================================================================
# MOTOR DE TEMAS DINÁMICOS (OMARCHY & X64 LIOS)
# ==============================================================================

def hex_to_rgb(h):
    h = h.lstrip("#")
    if len(h) == 3:
        h = "".join(c * 2 for c in h)
    return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))

def rgb_to_hex(rgb):
    return f"#{int(max(0, min(255, rgb[0]))):02x}{int(max(0, min(255, rgb[1]))):02x}{int(max(0, min(255, rgb[2]))):02x}"

def blend_colors(c1, c2, factor=0.5):
    try:
        r1, g1, b1 = hex_to_rgb(c1)
        r2, g2, b2 = hex_to_rgb(c2)
        return rgb_to_hex((
            r1 + (r2 - r1) * factor,
            g1 + (g2 - g1) * factor,
            b1 + (b2 - b1) * factor,
        ))
    except Exception:
        return c1

DEFAULT_PALETTE = {
    "mode": "dark",
    "accent": "#dc2626",
    "accent_hover": "#ef4444",
    "accent_subtle": "#991b1b",
    "background": "#09090d",
    "dark_background": "#0b0b10",
    "darker_background": "#07070b",
    "lighter_background": "#13131d",
    "card_bg": "#12121c",
    "card_border": "#232334",
    "table_bg": "#0d0d14",
    "table_alt_bg": "#11111a",
    "table_border": "#222232",
    "selection": "#1f1218",
    "foreground": "#f4f4f6",
    "muted": "#7c7c90",
    "sub_text": "#a1a1b5",
    "laser_stop0": "#dc2626",
    "laser_stop1": "#ef4444",
    "green": "#22c55e",
    "green_bg": "#0b291a",
    "green_border": "#165636",
    "green_text": "#4ade80",
    "yellow": "#f59e0b",
    "yellow_text": "#fbbf24",
    "blue": "#38bdf8",
    "cyan": "#00ccff",
    "magenta": "#e879f9",
}

def load_theme_palette():
    palette = dict(DEFAULT_PALETTE)
    theme_file = os.path.expanduser("~/.local/state/omarchy/current/theme/colors.toml")
    if not os.path.isfile(theme_file):
        return palette

    raw = {}
    try:
        import tomllib
        with open(theme_file, "rb") as f:
            raw = tomllib.load(f)
    except Exception:
        try:
            with open(theme_file, "r", encoding="utf-8") as f:
                for line in f:
                    line = line.strip()
                    if "=" in line and not line.startswith("#"):
                        k, v = line.split("=", 1)
                        raw[k.strip()] = v.strip().strip('"').strip("'")
        except Exception:
            return palette

    mode = str(raw.get("mode", "dark")).lower()
    palette["mode"] = mode

    accent = raw.get("accent") or raw.get("red") or raw.get("color1") or "#dc2626"
    palette["accent"] = accent

    if mode == "light":
        palette["accent_hover"] = blend_colors(accent, "#000000", 0.15)
        palette["accent_subtle"] = blend_colors(accent, "#000000", 0.30)
    else:
        palette["accent_hover"] = raw.get("bright_accent") or raw.get("bright_red") or blend_colors(accent, "#ffffff", 0.18)
        palette["accent_subtle"] = blend_colors(accent, "#000000", 0.35)

    bg = raw.get("background") or raw.get("bg") or raw.get("color0") or ("#ffffff" if mode == "light" else "#09090d")
    palette["background"] = bg

    dark_bg = raw.get("dark_background") or (blend_colors(bg, "#000000", 0.04) if mode == "light" else blend_colors(bg, "#000000", 0.25))
    palette["dark_background"] = dark_bg
    palette["darker_background"] = raw.get("darker_background") or dark_bg

    lighter_bg = raw.get("lighter_background") or raw.get("lighter_bg") or (blend_colors(bg, "#000000", 0.05) if mode == "light" else blend_colors(bg, "#ffffff", 0.08))
    palette["lighter_background"] = lighter_bg
    palette["card_bg"] = lighter_bg

    selection = raw.get("selection") or (blend_colors(bg, "#000000", 0.12) if mode == "light" else blend_colors(bg, "#ffffff", 0.15))
    palette["selection"] = selection

    border = raw.get("border") or raw.get("selection") or (blend_colors(bg, "#000000", 0.16) if mode == "light" else blend_colors(bg, "#ffffff", 0.14))
    palette["card_border"] = border
    palette["table_border"] = border

    palette["table_bg"] = bg
    palette["table_alt_bg"] = lighter_bg

    fg = raw.get("foreground") or raw.get("fg") or raw.get("color7") or ("#18181b" if mode == "light" else "#f4f4f6")
    palette["foreground"] = fg

    muted = raw.get("muted") or raw.get("dark_foreground") or raw.get("color8") or blend_colors(fg, bg, 0.45)
    palette["muted"] = muted
    palette["sub_text"] = blend_colors(fg, bg, 0.30)

    palette["laser_stop0"] = accent
    palette["laser_stop1"] = raw.get("bright_accent") or raw.get("bright_yellow") or raw.get("cyan") or palette["accent_hover"]

    if "green" in raw:
        palette["green"] = raw["green"]
        palette["green_text"] = raw.get("bright_green", raw["green"])
        if mode == "light":
            palette["green_bg"] = blend_colors(raw["green"], "#ffffff", 0.85)
            palette["green_border"] = blend_colors(raw["green"], "#ffffff", 0.50)
        else:
            palette["green_bg"] = blend_colors(raw["green"], "#000000", 0.82)
            palette["green_border"] = blend_colors(raw["green"], "#000000", 0.65)

    if "yellow" in raw:
        palette["yellow"] = raw["yellow"]
        palette["yellow_text"] = raw.get("bright_yellow", raw["yellow"])

    if "blue" in raw:
        palette["blue"] = raw["blue"]
    if "cyan" in raw:
        palette["cyan"] = raw["cyan"]
    if "magenta" in raw:
        palette["magenta"] = raw["magenta"]

    return palette


# ==============================================================================
# PIPELINE DE ACTUALIZACIÓN INTEGRAL (PARIDAD 100% OMARCHY & SEGURIDAD X64 LIOS)
# ==============================================================================

def build_update_pipeline(sudo_cmd="sudo", aur_helper=None, choice="1", has_repo=True, has_aur=False, has_fp=False, password=None):
    """
    Construye la lista ordenada de comandos shell para ejecutar la transacción completa con:
    1. Inhibición de suspensión y reposo (Stay-Awake).
    2. Comprobación preventiva de espacio libre en disco (/).
    3. Poda preventiva de caché de paquetes (antes de snapshots BTRFS).
    4. Instantánea de recuperación Snapper / BTRFS.
    5. Sincronización Git robusta con safe.directory y autostash.
    6. Actualización previa de llaveros PGP (archlinux-keyring, cachyos-keyring, omarchy-keyring).
    7. Actualización de repositorios oficiales (Pacman -Syu).
    8. Migraciones de configuración y dotfiles (omarchy-migrate).
    9. Purgado de paquetes huérfanos.
    10. Actualización de paquetes de usuario AUR (yay/paru).
    11. Actualización de aplicaciones y runtimes Flatpak.
    12. Recarga en caliente de plugins QML y servicios (omarchy-update-restart).
    13. Ganchos de usuario post-actualización (omarchy-hook post-update).
    14. Actualización de herramientas y agentes IA (omarchy-update-mise).
    15. Verificación de la cadena de arranque (omarchy-update-boot).
    16. Limpieza de notificación/badge en Quickshell (omarchy-shell clear).
    17. Reinicio selectivo de daemons actualizados (checkservices).
    18. Liberación limpia del inhibidor de suspensión.
    """
    commands = []
    display_cmds = []

    has_omarchy = os.path.isdir("/usr/share/omarchy/.git")
    sudo_flags = "--sudoflags -A " if password else ""

    # 1. Inhibidor de suspensión y reposo del sistema (Stay-Awake)
    if has_omarchy and os.path.isfile("/usr/share/omarchy/bin/omarchy-update-stay-awake"):
        commands.append(
            "{ if [ -x /usr/share/omarchy/bin/omarchy-update-stay-awake ]; then "
            "/usr/share/omarchy/bin/omarchy-update-stay-awake start 2>/dev/null || true; fi; }"
        )

    # 2. Verificación de espacio libre mínimo en disco (al menos 2 GB en /)
    space_cmd = (
        "{ if [ -x /usr/share/omarchy/bin/omarchy-update-requires-free-space ]; then "
        "/usr/share/omarchy/bin/omarchy-update-requires-free-space || exit 1; "
        "else "
        "free_kb=$(df -k / 2>/dev/null | awk 'NR==2 {print $4}'); "
        "if [ -n \"$free_kb\" ] && [ \"$free_kb\" -lt 2097152 ]; then "
        "printf '\\033[1;31mError: Espacio insuficiente en disco. Se requieren al menos 2 GB libres en / para actualizar con seguridad.\\033[0m\\n' >&2; "
        "exit 1; fi; fi; }"
    )
    commands.append(space_cmd)
    display_cmds.append("comprobar-espacio")

    # 3. Poda preventiva de caché de paquetes (ANTES del snapshot para no inflar BTRFS)
    prune_cmd = (
        "{ if [ -x /usr/share/omarchy/bin/omarchy-update-pkg-prune ]; then "
        f"{sudo_cmd} /usr/share/omarchy/bin/omarchy-update-pkg-prune || true; "
        "elif which paccache >/dev/null 2>&1; then "
        "printf '\\033[1;34m::\\033[0;1m Optimizando caché de paquetes previa al snapshot...\\033[0m\\n'; "
        f"{sudo_cmd} paccache -rk2 -q && {sudo_cmd} paccache -ruk0 -q || true; fi; }}"
    )
    commands.append(prune_cmd)

    # 4. Instantánea de seguridad BTRFS / Snapper (omarchy-snapshot create)
    if has_omarchy and os.path.isfile("/usr/share/omarchy/bin/omarchy-snapshot"):
        snap_cmd = (
            "{ if [ -x /usr/share/omarchy/bin/omarchy-snapshot ]; then "
            f"{sudo_cmd} /usr/share/omarchy/bin/omarchy-snapshot create || true; fi; }}"
        )
        commands.append(snap_cmd)
        display_cmds.append("omarchy-snapshot")

    # 5. Sincronización Git de la Capa Omarchy (con safe.directory y autostash)
    if has_omarchy:
        git_cmd = (
            "{ if [ -x /usr/share/omarchy/bin/omarchy-update-dev ]; then "
            "/usr/share/omarchy/bin/omarchy-update-dev || true; "
            "elif [ -d /usr/share/omarchy/.git ]; then "
            "printf '\\033[1;36m[+]\\033[0;1m Sincronizando Capa X64 LIOS + Omarchy desde Git...\\033[0m\\n'; "
            "git config --global --add safe.directory /usr/share/omarchy 2>/dev/null || true; "
            f"{sudo_cmd} git config --global --add safe.directory /usr/share/omarchy 2>/dev/null || true; "
            f"{sudo_cmd} git -C /usr/share/omarchy pull --rebase --autostash origin main || true; fi; }}"
        )
        commands.append(git_cmd)
        display_cmds.append("git-pull-omarchy")

    # 6. Actualización previa de Llaveros / Keyrings PGP (archlinux, cachyos, omarchy)
    keyring_cmd = (
        "{ if [ -x /usr/share/omarchy/bin/omarchy-update-keyring ]; then "
        f"{sudo_cmd} /usr/share/omarchy/bin/omarchy-update-keyring || true; "
        "else "
        "printf '\\033[1;34m::\\033[0;1m Verificando depósitos de firmas PGP (keyrings)...\\033[0m\\n'; "
        f"{sudo_cmd} pacman -Sy --needed --noconfirm archlinux-keyring cachyos-keyring 2>/dev/null || true; fi; }}"
    )
    commands.append(keyring_cmd)
    display_cmds.append("actualizar-keyrings")

    # 7. Actualización de paquetes oficiales (Pacman -Syu)
    if has_repo or (not has_aur and not has_fp):
        commands.append(f"{sudo_cmd} pacman -Syu --noconfirm")
        display_cmds.append("sudo pacman -Syu --noconfirm")

    # 8. Migraciones de configuración y dotfiles (omarchy-migrate)
    if has_omarchy:
        migrate_cmd = (
            "{ if [ -x /usr/share/omarchy/bin/omarchy-migrate ]; then "
            "printf '\\033[1;36m[+]\\033[0;1m Comprobando y aplicando migraciones de configuración (Omarchy Migrations)...\\033[0m\\n'; "
            "if /usr/share/omarchy/bin/omarchy-migrate --pending >/dev/null 2>&1; then "
            "if [ -x /usr/share/omarchy/bin/omarchy-restart-shell ]; then "
            "/usr/share/omarchy/bin/omarchy-restart-shell || true; fi; fi; "
            "/usr/share/omarchy/bin/omarchy-migrate || true; fi; }"
        )
        commands.append(migrate_cmd)
        display_cmds.append("omarchy-migrate")

    # 9. Limpieza de paquetes huérfanos residuales
    orphan_cmd = (
        "{ if [ -x /usr/share/omarchy/bin/omarchy-update-orphan-pkgs ]; then "
        f"{sudo_cmd} /usr/share/omarchy/bin/omarchy-update-orphan-pkgs -y || true; "
        "else "
        "orphans=$(pacman -Qtdq 2>/dev/null || true); "
        "if [ -n \"$orphans\" ]; then "
        "printf '\\033[1;34m::\\033[0;1m Eliminando paquetes huérfanos...\\033[0m\\n'; "
        f"{sudo_cmd} pacman -Rns --noconfirm $orphans || true; fi; fi; }}"
    )
    commands.append(orphan_cmd)

    # 10. Actualización de paquetes AUR (yay/paru)
    if has_aur and aur_helper:
        commands.append(f"{aur_helper} -Sua --noconfirm {sudo_flags}".strip())
        display_cmds.append(f"{aur_helper} -Sua --noconfirm")

    # 11. Actualización de aplicaciones Flatpak
    if has_fp and shutil.which("flatpak"):
        commands.append("{ flatpak update -y && flatpak uninstall --unused -y; }")
        display_cmds.append("flatpak update -y && flatpak uninstall --unused -y")

    # 12. Purgado adicional si se solicitó opción 3 en CLI
    if choice == "3":
        commands.append(f"{sudo_cmd} pacman -Sc --noconfirm")

    # 13. Recarga en caliente de plugins QML y servicios de escritorio
    if has_omarchy:
        restart_cmd = (
            "{ if [ -x /usr/share/omarchy/bin/omarchy-update-restart ]; then "
            "printf '\\033[1;36m[+]\\033[0;1m Recargando plugins y entorno de escritorio X64 LIOS + Omarchy...\\033[0m\\n'; "
            "/usr/share/omarchy/bin/omarchy-update-restart --services-only 2>/dev/null || /usr/share/omarchy/bin/omarchy-update-restart || true; fi; }"
        )
        commands.append(restart_cmd)
        display_cmds.append("omarchy-update-restart")

    # 14. Ganchos post-actualización del usuario
    if has_omarchy:
        hook_cmd = (
            "{ if [ -x /usr/share/omarchy/bin/omarchy-hook ]; then "
            "/usr/share/omarchy/bin/omarchy-hook post-update || true; fi; }"
        )
        commands.append(hook_cmd)

    # 15. Actualización de herramientas y agentes IA (Mise)
    if has_omarchy:
        mise_cmd = (
            "{ if [ -x /usr/share/omarchy/bin/omarchy-update-mise ]; then "
            "printf '\\033[1;36m[+]\\033[0;1m Actualizando herramientas y agentes IA (Mise)...\\033[0m\\n'; "
            "/usr/share/omarchy/bin/omarchy-update-mise || true; fi; }"
        )
        commands.append(mise_cmd)
        display_cmds.append("omarchy-update-mise")

    # 16. Verificación de la cadena de arranque (omarchy-update-boot)
    if has_omarchy:
        boot_cmd = (
            "{ if [ -x /usr/share/omarchy/bin/omarchy-update-boot ]; then "
            f"{sudo_cmd} /usr/share/omarchy/bin/omarchy-update-boot || true; fi; }}"
        )
        commands.append(boot_cmd)

    # 17. Limpieza de notificación/badge en la barra de Quickshell (Shell IPC)
    if has_omarchy:
        shell_clear_cmd = (
            "{ if [ -x /usr/share/omarchy/bin/omarchy-shell ]; then "
            "/usr/share/omarchy/bin/omarchy-shell -q omarchy.system-update clear 2>/dev/null || true; fi; }"
        )
        commands.append(shell_clear_cmd)

    # 18. Reinicio de servicios de segundo plano actualizados (checkservices)
    if shutil.which("checkservices"):
        cs_cmd = (
            f"{{ svcs=$({sudo_cmd} checkservices -F -P -R "
            "-i gdm.service -i plasmalogin.service -i sddm.service -i lightdm.service "
            "-i lxdm.service -i slim.service -i xdm.service -i greetd.service "
            "-i nodm.service -i ly.service -i lemurs.service -i dbus.service "
            "-i systemd-logind.service -i NetworkManager.service 2>/dev/null "
            "| grep '.service' | cut -f2 -d \"'\" || true); "
            "if [ -n \"$svcs\" ]; then "
            "printf '\\033[1;34m::\\033[0;1m Reiniciando servicios de segundo plano actualizados...\\033[0m\\n'; "
            f"{sudo_cmd} systemctl restart $svcs || true; fi; }}"
        )
        commands.append(cs_cmd)

    # 19. Liberación del inhibidor de suspensión (Stay-Awake stop)
    if has_omarchy and os.path.isfile("/usr/share/omarchy/bin/omarchy-update-stay-awake"):
        commands.append(
            "{ if [ -x /usr/share/omarchy/bin/omarchy-update-stay-awake ]; then "
            "/usr/share/omarchy/bin/omarchy-update-stay-awake stop 2>/dev/null || true; fi; }"
        )

    return commands, display_cmds


# ==============================================================================
# GUI NATIVA (PyQt6) 100% INTEGRADA
# ==============================================================================

def run_gui():
    from PyQt6.QtWidgets import (
        QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
        QLabel, QPushButton, QLineEdit, QTableWidget, QTableWidgetItem,
        QHeaderView, QCheckBox, QFrame, QButtonGroup, QAbstractItemView,
        QProgressBar, QTextEdit, QStackedWidget, QDialog, QStyledItemDelegate, QStyle, QSizePolicy
    )
    from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer, QSize, QRectF, QFileSystemWatcher
    from PyQt6.QtGui import QColor, QFont, QIcon, QPixmap, QTextCursor, QPainter, QPen, QBrush, QPalette

    class CheckWorker(QThread):
        finished = pyqtSignal(dict)
        status = pyqtSignal(str)

        def run(self):
            self.status.emit("Comprobando repositorios oficiales...")
            repo_pkgs = check_official_repos()
            if os.path.isdir("/usr/share/omarchy/.git"):
                self.status.emit("Comprobando Capa X64 LIOS + Omarchy...")
                omarchy_pkg = check_omarchy_git()
                if omarchy_pkg:
                    repo_pkgs.insert(0, omarchy_pkg)
            self.status.emit("Inspeccionando catálogo AUR...")
            aur_pkgs = check_aur_packages()
            self.status.emit("Verificando paquetes Flatpak...")
            flatpak_pkgs = check_flatpak_packages()

            data = save_check_results(repo_pkgs, aur_pkgs, flatpak_pkgs)
            self.finished.emit({
                "repo": repo_pkgs,
                "aur": aur_pkgs,
                "flatpak": flatpak_pkgs,
                "count": data["count"]
            })

    class TransactionWorker(QThread):
        output_received = pyqtSignal(str)
        stage_changed = pyqtSignal(str, int) # (stage_text, percent)
        transaction_done = pyqtSignal(bool, int, bool) # (success, exit_code, kernel_updated)

        def __init__(self, commands, password=None):
            super().__init__()
            self.commands = commands
            self.password = password
            self.master_fd = None
            self.proc = None
            self.kernel_updated = False

        def run(self):
            askpass_path = None
            if self.password:
                try:
                    askpass_path = f"/tmp/.x64-askpass-{os.getuid()}-{os.getpid()}"
                    with open(askpass_path, "w", encoding="utf-8") as af:
                        af.write("#!/bin/sh\nprintf '%s\\n' \"$X64_SUDO_SECRET\"\n")
                    os.chmod(askpass_path, 0o700)
                except Exception:
                    askpass_path = None

            master, slave = pty.openpty()
            self.master_fd = master

            # Set PTY window size (32 rows, 104 columns) so pacman/ncurses format progress bars cleanly inside log_view
            try:
                winsize = struct.pack("HHHH", 32, 104, 0, 0)
                fcntl.ioctl(slave, termios.TIOCSWINSZ, winsize)
            except Exception:
                pass

            env = os.environ.copy()
            env["TERM"] = "xterm-256color"
            env["COLUMNS"] = "104"
            env["LINES"] = "32"
            env["LC_ALL"] = "C.UTF-8"
            if askpass_path and self.password:
                env["SUDO_ASKPASS"] = askpass_path
                env["X64_SUDO_SECRET"] = self.password

            sudo_bin = "sudo -A" if (askpass_path and self.password) else "sudo"

            # 1. Pre-stamp PTY sudo ticket + auto-unlock stale /var/lib/pacman/db.lck inside the PTY session
            preamble = (
                f"if [ -n \"${{SUDO_ASKPASS:-}}\" ]; then {sudo_bin} -v >/dev/null 2>&1; fi; "
                f"if [ -e /var/lib/pacman/db.lck ] && ! pgrep -x pacman >/dev/null 2>&1; then "
                f"printf '\\033[1;33m::\\033[0;1m Detectado candado huérfano /var/lib/pacman/db.lck (sin procesos activos). Desbloqueando...\\033[0m\\r\\n'; "
                f"{sudo_bin} rm -f /var/lib/pacman/db.lck; "
                f"fi"
            )
            cmd_str = f"set -e; {preamble}; " + " && ".join(self.commands) + "; sync"

            def _setup_pty_session():
                os.setsid()
                try:
                    fcntl.ioctl(0, termios.TIOCSCTTY, 0)
                except Exception:
                    pass

            self.stage_changed.emit("Iniciando transacción de paquetes...", 10)

            try:
                self.proc = subprocess.Popen(
                    ["bash", "-e", "-c", cmd_str],
                    stdin=slave,
                    stdout=slave,
                    stderr=slave,
                    env=env,
                    preexec_fn=_setup_pty_session,
                    close_fds=True
                )
                os.close(slave)

                while True:
                    try:
                        data = os.read(master, 1024)
                        if not data:
                            break
                        text = data.decode("utf-8", errors="replace")
                        self.output_received.emit(text)

                        # Detect critical kernel / driver replacements
                        low = text.lower()
                        if "vmlinuz" in low or "initramfs" in low or "linux-cachyos" in low or "nvidia" in low:
                            self.kernel_updated = True

                        if "optimizando caché" in low or "paccache" in low:
                            self.stage_changed.emit("Optimizando caché y preparando snapshot...", 20)
                        elif "instantánea" in low or "snapshot" in low:
                            self.stage_changed.emit("Creando instantánea Snapper / BTRFS...", 25)
                        elif "sincronizando capa" in low or "git update" in low or "stepgit" in low:
                            self.stage_changed.emit("Sincronizando capa Git de Omarchy...", 30)
                        elif "retrieving" in low or "recuperando" in low or "downloading" in low or "descargando" in low:
                            self.stage_changed.emit("Descargando paquetes de repositorios...", 40)
                        elif "checking keyring" in low or "comprobando el depósito" in low or "verificando depósitos" in low:
                            self.stage_changed.emit("Verificando claves y firmas de seguridad (Keyrings)...", 50)
                        elif "checking package integrity" in low or "verificando la integridad" in low:
                            self.stage_changed.emit("Verificando integridad de archivos...", 60)
                        elif "upgrading" in low or "actualizando" in low or "installing" in low or "instalando" in low:
                            self.stage_changed.emit("Instalando y descomprimiendo paquetes...", 70)
                        elif "running post-transaction hooks" in low or "ejecutando" in low or "hooks" in low:
                            self.stage_changed.emit("Ejecutando ganchos del sistema (initramfs, kernel)...", 80)
                        elif "migraciones de configuración" in low or "running migration" in low:
                            self.stage_changed.emit("Aplicando migraciones de configuración (Omarchy Migrations)...", 88)
                        elif "eliminando paquetes huérfanos" in low or "removing orphan" in low:
                            self.stage_changed.emit("Limpiando paquetes huérfanos residuales...", 92)
                        elif "recargando plugins" in low or "reloading shell" in low:
                            self.stage_changed.emit("Sincronizando plugins y entorno de escritorio...", 95)
                        elif "actualizando herramientas" in low or "mise" in low:
                            self.stage_changed.emit("Actualizando herramientas y agentes IA (Mise)...", 97)

                    except OSError:
                        break

                os.close(master)
                ret = self.proc.wait() if self.proc else 1
            except Exception as e:
                self.output_received.emit(f"\nError interno ejecutando transacción: {e}\n")
                ret = 1
            finally:
                if askpass_path and os.path.exists(askpass_path):
                    try:
                        os.remove(askpass_path)
                    except Exception:
                        pass

            # 7. Exact CachyOS kernel reboot check: verify if running kernel's vmlinuz was replaced
            try:
                running_kernel_vmlinuz = f"/usr/lib/modules/{os.uname().release}/vmlinuz"
                if not os.path.isfile(running_kernel_vmlinuz):
                    self.kernel_updated = True
            except Exception:
                pass

            success = (ret == 0)
            if success:
                # Immediately clear state files so tray icon updates to "up to date" without delay
                try:
                    ensure_state_dir()
                    with open(COUNT_FILE, "w", encoding="utf-8") as f:
                        f.write("0\n")
                    with open(PACKAGES_FILE, "w", encoding="utf-8") as f:
                        f.write("")
                except Exception:
                    pass
                self.stage_changed.emit("¡Transacción finalizada con éxito!", 100)
                run_background_check_and_save()
            else:
                self.stage_changed.emit(f"Transacción abortada con código: {ret}", 100)

            self.transaction_done.emit(success, ret, self.kernel_updated)

    class ConfirmDialog(QDialog):
        def __init__(self, items_count, crit_count, cached_sudo, parent=None, breakdown=None, palette=None):
            super().__init__(parent)
            self.palette = palette or (parent.palette if hasattr(parent, "palette") else load_theme_palette())
            p = self.palette
            self.setWindowTitle("Autorización del Sistema")
            self.setFixedWidth(520)
            self.setModal(True)
            self.cached_sudo = cached_sudo
            self.breakdown = breakdown or {}
            self.setStyleSheet(f"""
                QDialog {{
                    background-color: {p['dark_background']};
                }}
                QLabel {{
                    border: none;
                    background: transparent;
                }}
            """)

            vbox = QVBoxLayout(self)
            vbox.setContentsMargins(24, 22, 24, 22)
            vbox.setSpacing(16)

            # Header Row (Official Icon + Title & Subtitle)
            hdr = QHBoxLayout()
            hdr.setSpacing(14)

            icon_box = QFrame()
            icon_box.setObjectName("iconBox")
            icon_box.setFixedSize(44, 44)
            icon_box.setStyleSheet(f"""
                QFrame#iconBox {{
                    background-color: {p['lighter_background']};
                    border: 1px solid {p['card_border']};
                    border-radius: 10px;
                }}
            """)
            ib_layout = QVBoxLayout(icon_box)
            ib_layout.setContentsMargins(0, 0, 0, 0)
            ib_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
            lbl_icon = QLabel()
            for icon_path in [
                "/usr/share/pixmaps/x64-update.png",
                "/usr/share/icons/hicolor/128x128/apps/x64-update.png",
                os.path.expanduser("~/Proyectos/X64-LIOS-Packages/x64-update/icons/128x128/apps/x64-update.png")
            ]:
                if os.path.exists(icon_path):
                    pix = QPixmap(icon_path).scaled(
                        30, 30,
                        Qt.AspectRatioMode.KeepAspectRatio,
                        Qt.TransformationMode.SmoothTransformation
                    )
                    lbl_icon.setPixmap(pix)
                    break
            ib_layout.addWidget(lbl_icon)
            hdr.addWidget(icon_box)

            title_col = QVBoxLayout()
            title_col.setSpacing(2)
            lbl_title = QLabel("Autorización de Actualización")
            lbl_title.setStyleSheet(f"color: {p['foreground']}; font-size: 15px; font-weight: 800;")
            lbl_sub = QLabel("Confirma la operación para iniciar la transacción del sistema")
            lbl_sub.setStyleSheet(f"color: {p['muted']}; font-size: 12px;")
            title_col.addWidget(lbl_title)
            title_col.addWidget(lbl_sub)
            hdr.addLayout(title_col)
            hdr.addStretch()
            vbox.addLayout(hdr)

            # Flat Summary Card (strictly scoped by #summaryCard so QLabels never inherit borders)
            summary_frame = QFrame()
            summary_frame.setObjectName("summaryCard")
            summary_frame.setStyleSheet(f"""
                QFrame#summaryCard {{
                    background-color: {p['table_alt_bg']};
                    border: 1px solid {p['card_border']};
                    border-radius: 9px;
                }}
            """)
            sbox = QVBoxLayout(summary_frame)
            sbox.setContentsMargins(14, 12, 14, 12)
            sbox.setSpacing(8)

            pkg_word = "paquete listo" if items_count == 1 else "paquetes listos"
            lbl_pkgs = QLabel(f"{items_count} {pkg_word} para actualizar")
            lbl_pkgs.setStyleSheet(f"color: {p['foreground']}; font-size: 13px; font-weight: 700;")
            sbox.addWidget(lbl_pkgs)

            # Breakdown pills in their own dedicated row so neither title nor pills ever get clipped
            pills_row = QHBoxLayout()
            pills_row.setSpacing(6)
            x64_n = self.breakdown.get("x64", 0)
            repo_n = self.breakdown.get("repo", 0)
            aur_n = self.breakdown.get("aur", 0)
            fp_n = self.breakdown.get("fp", 0)

            def make_pill(text, fg, bg, border):
                pill = QLabel(text)
                pill.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
                pill.setStyleSheet(
                    f"background-color: {bg}; color: {fg}; border: 1px solid {border}; "
                    f"border-radius: 5px; padding: 3px 9px; font-size: 11px; font-weight: 700;"
                )
                return pill

            if x64_n > 0:
                pills_row.addWidget(make_pill(f"X64 LIOS: {x64_n}", "#ff4d4d", "#2a0a0e", "#5c161e"))
            if repo_n > 0:
                pills_row.addWidget(make_pill(f"Sistema: {repo_n}", "#38bdf8", "#092030", "#123b56"))
            if aur_n > 0:
                pills_row.addWidget(make_pill(f"AUR: {aur_n}", "#e879f9", "#26092e", "#481456"))
            if fp_n > 0:
                pills_row.addWidget(make_pill(f"Flatpak: {fp_n}", "#818cf8", "#101036", "#232368"))
            if crit_count > 0:
                pills_row.addWidget(make_pill(f"Críticos: {crit_count}", "#fbbf24", "#2b1d06", "#573b0c"))
            pills_row.addStretch()

            sbox.addLayout(pills_row)

            if crit_count > 0:
                crit_word = "componente crítico" if crit_count == 1 else "componentes críticos"
                lbl_note = QLabel(f"Incluye {crit_count} {crit_word} del sistema (Kernel / Controladores).")
                lbl_note.setStyleSheet(f"color: {p['yellow_text']}; font-size: 11px; font-weight: 600;")
            else:
                lbl_note = QLabel("Los paquetes se descargarán e instalarán mediante verificación criptográfica.")
                lbl_note.setStyleSheet(f"color: {p['muted']}; font-size: 11px;")
            sbox.addWidget(lbl_note)

            vbox.addWidget(summary_frame)

            # Authentication Section
            if not self.cached_sudo:
                auth_col = QVBoxLayout()
                auth_col.setSpacing(6)

                lbl_auth = QLabel("Contraseña de administrador")
                lbl_auth.setStyleSheet(f"color: {p['sub_text']}; font-size: 12px; font-weight: 600;")
                auth_col.addWidget(lbl_auth)

                self.pwd_input = QLineEdit()
                self.pwd_input.setEchoMode(QLineEdit.EchoMode.Password)
                self.pwd_input.setPlaceholderText("Ingresa tu contraseña de sudo...")
                self.pwd_input.setStyleSheet(f"""
                    QLineEdit {{
                        background-color: {p['lighter_background']};
                        color: {p['foreground']};
                        border: 1px solid {p['card_border']};
                        border-radius: 8px;
                        padding: 9px 12px;
                        font-size: 13px;
                    }}
                    QLineEdit:focus {{
                        border: 1px solid {p['accent']};
                        background-color: {p['selection']};
                    }}
                """)
                auth_col.addWidget(self.pwd_input)

                self.lbl_error = QLabel("")
                self.lbl_error.setStyleSheet(f"color: {p['accent']}; font-size: 11px; font-weight: 600;")
                self.lbl_error.setVisible(False)
                auth_col.addWidget(self.lbl_error)

                vbox.addLayout(auth_col)
                self.pwd_input.returnPressed.connect(self.verify_and_confirm)
                self.pwd_input.setFocus()
            else:
                self.pwd_input = None
                auth_ok_frame = QFrame()
                auth_ok_frame.setObjectName("authOkFrame")
                auth_ok_frame.setStyleSheet(f"""
                    QFrame#authOkFrame {{
                        background-color: {p['green_bg']};
                        border: 1px solid {p['green_border']};
                        border-radius: 8px;
                    }}
                """)
                ok_box = QHBoxLayout(auth_ok_frame)
                ok_box.setContentsMargins(12, 8, 12, 8)
                lbl_auth_ok = QLabel("Sesión de administrador activa — no se requiere contraseña adicional.")
                lbl_auth_ok.setStyleSheet(f"color: {p['green_text']}; font-size: 11px; font-weight: 600;")
                ok_box.addWidget(lbl_auth_ok)
                vbox.addWidget(auth_ok_frame)

            vbox.addSpacing(2)

            # Action Buttons
            btn_row = QHBoxLayout()
            btn_row.setSpacing(10)

            btn_cancel = QPushButton("Cancelar")
            btn_cancel.setCursor(Qt.CursorShape.PointingHandCursor)
            btn_cancel.setStyleSheet(f"""
                QPushButton {{
                    background-color: {p['table_bg']};
                    color: {p['sub_text']};
                    border: 1px solid {p['card_border']};
                    border-radius: 8px;
                    padding: 9px 18px;
                    font-weight: 600;
                    font-size: 12px;
                }}
                QPushButton:hover {{
                    background-color: {p['selection']};
                    color: {p['foreground']};
                    border: 1px solid {p['accent']};
                }}
            """)
            btn_cancel.clicked.connect(self.reject)

            btn_confirm = QPushButton("Autorizar y Actualizar")
            btn_confirm.setCursor(Qt.CursorShape.PointingHandCursor)
            btn_confirm.setStyleSheet(f"""
                QPushButton {{
                    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 {p['accent']}, stop:1 {p['accent_subtle']});
                    color: #ffffff;
                    border: 1px solid {p['accent_hover']};
                    border-radius: 8px;
                    padding: 9px 22px;
                    font-weight: 700;
                    font-size: 12px;
                }}
                QPushButton:hover {{
                    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 {p['accent_hover']}, stop:1 {p['accent']});
                }}
            """)
            btn_confirm.clicked.connect(self.verify_and_confirm)

            btn_row.addStretch()
            btn_row.addWidget(btn_cancel)
            btn_row.addWidget(btn_confirm)
            vbox.addLayout(btn_row)
            self.adjustSize()
            self.setFixedSize(520, self.sizeHint().height())

        def verify_and_confirm(self):
            if not self.cached_sudo:
                pwd = self.pwd_input.text()
                if not pwd:
                    self.lbl_error.setText("Por favor, ingresa tu contraseña.")
                    self.lbl_error.setVisible(True)
                    return

                p = subprocess.run(
                    ["sudo", "-S", "-v"],
                    input=f"{pwd}\n".encode(),
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL
                )
                if p.returncode == 0:
                    self.accept()
                else:
                    self.lbl_error.setText("✕ Contraseña incorrecta. Inténtalo de nuevo.")
                    self.lbl_error.setVisible(True)
                    self.pwd_input.selectAll()
                    self.pwd_input.setFocus()
            else:
                self.accept()

        def get_password(self):
            return self.pwd_input.text() if self.pwd_input else None

    class BadgeDelegate(QStyledItemDelegate):
        """Renders rounded pill badges inside Column 0 without breaking QTableWidget sorting."""
        def __init__(self, parent=None, palette=None):
            super().__init__(parent)
            self.palette = palette or {}

        def update_palette(self, palette):
            self.palette = palette

        def paint(self, painter, option, index):
            painter.save()
            painter.setRenderHint(QPainter.RenderHint.Antialiasing)

            sel_bg = self.palette.get("selection", "#1f1218")
            hover_bg = self.palette.get("lighter_background", "#161622")
            bdr_line = self.palette.get("card_border", "#171723")

            # Draw row selection/hover background if active
            if option.state & QStyle.StateFlag.State_Selected:
                painter.fillRect(option.rect, QColor(sel_bg))
            elif option.state & QStyle.StateFlag.State_MouseOver:
                painter.fillRect(option.rect, QColor(hover_bg))

            # Draw subtle horizontal bottom row separator to match columns 1..3
            painter.setPen(QPen(QColor(bdr_line), 1.0))
            painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())

            meta = index.data(Qt.ItemDataRole.UserRole)
            if isinstance(meta, dict):
                label = meta.get("label", "")
                fg = QColor(meta.get("fg", "#38bdf8"))
                bg = QColor(meta.get("bg", "#092030"))
                border = QColor(meta.get("border", "#123b56"))

                font = QFont(option.font)
                font.setPixelSize(11)
                font.setBold(True)
                painter.setFont(font)

                pill_w = 86
                pill_h = 24
                x = option.rect.x() + (option.rect.width() - pill_w) / 2.0
                y = option.rect.y() + (option.rect.height() - pill_h) / 2.0
                pill_rect = QRectF(x, y, pill_w, pill_h)

                painter.setBrush(QBrush(bg))
                painter.setPen(QPen(border, 1.0))
                painter.drawRoundedRect(pill_rect, 6.0, 6.0)

                painter.setPen(fg)
                painter.drawText(pill_rect, Qt.AlignmentFlag.AlignCenter, label)

            painter.restore()

    class X64UpdateWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.palette = load_theme_palette()
            self.setWindowTitle("X64 LIOS Update")
            self.resize(1020, 680)
            self.setMinimumSize(850, 520)

            for icon_path in [
                "/usr/share/pixmaps/x64-update.png",
                "/usr/share/icons/hicolor/128x128/apps/x64-update.png",
                os.path.expanduser("~/Proyectos/X64-LIOS-Packages/x64-update/icons/128x128/apps/x64-update.png")
            ]:
                if os.path.exists(icon_path):
                    self.setWindowIcon(QIcon(icon_path))
                    break

            self.all_items = []
            self.active_filter = "all"
            self.check_worker = None
            self.tx_worker = None
            self.tx_start_time = 0
            self.timer_elapsed = QTimer(self)
            self.timer_elapsed.timeout.connect(self.update_elapsed_time)

            self.init_ui()
            self.setup_theme_watcher()
            self.apply_theme()
            self.load_cached_state()
            self.trigger_refresh()

        def mousePressEvent(self, event):
            if event.button() == Qt.MouseButton.LeftButton:
                if event.pos().y() <= 80:
                    wh = self.window().windowHandle()
                    if wh:
                        wh.startSystemMove()
                        event.accept()
                        return
            super().mousePressEvent(event)

        def setup_theme_watcher(self):
            self.theme_watcher = QFileSystemWatcher(self)
            self._last_theme_mtime = 0
            self._arm_theme_watcher()
            self.theme_watcher.fileChanged.connect(self.on_theme_changed)
            self.theme_watcher.directoryChanged.connect(self.on_theme_changed)

            # Timer de sondeo ultra-ligero (1s) para garantizar hot-reload incluso ante reemplazos atómicos (rm/mv)
            self.theme_poll_timer = QTimer(self)
            self.theme_poll_timer.timeout.connect(self.check_theme_poll)
            self.theme_poll_timer.start(1000)

        def _arm_theme_watcher(self):
            theme_file = os.path.expanduser("~/.local/state/omarchy/current/theme/colors.toml")
            theme_name_file = os.path.expanduser("~/.local/state/omarchy/current/theme.name")
            current_dir = os.path.expanduser("~/.local/state/omarchy/current")
            theme_dir = os.path.expanduser("~/.local/state/omarchy/current/theme")
            for p in [current_dir, theme_dir, theme_name_file, theme_file]:
                if os.path.exists(p):
                    if os.path.isdir(p) and p not in self.theme_watcher.directories():
                        self.theme_watcher.addPath(p)
                    elif os.path.isfile(p) and p not in self.theme_watcher.files():
                        self.theme_watcher.addPath(p)

        def check_theme_poll(self):
            theme_file = os.path.expanduser("~/.local/state/omarchy/current/theme/colors.toml")
            if os.path.isfile(theme_file):
                try:
                    mtime = os.path.getmtime(theme_file)
                    if mtime != self._last_theme_mtime:
                        self._last_theme_mtime = mtime
                        self.on_theme_changed()
                except Exception:
                    pass

        def on_theme_changed(self, path=None):
            new_pal = load_theme_palette()
            # Si no ha cambiado la paleta visual real, no redibujar innecesariamente
            if getattr(self, "palette", None) and self.palette.get("accent") == new_pal.get("accent") and self.palette.get("background") == new_pal.get("background"):
                self._arm_theme_watcher()
                return

            self.palette = new_pal
            if hasattr(self, "badge_delegate"):
                self.badge_delegate.update_palette(self.palette)
            self.apply_theme()
            c_all = int(self.f_all.text().split("(")[1].split(")")[0]) if "(" in self.f_all.text() else 0
            c_crit = int(self.f_crit.text().split("(")[1].split(")")[0]) if "(" in self.f_crit.text() else 0
            c_repo = int(self.f_repo.text().split("(")[1].split(")")[0]) if "(" in self.f_repo.text() else 0
            c_aur = int(self.f_aur.text().split("(")[1].split(")")[0]) if "(" in self.f_aur.text() else 0
            c_fp = int(self.f_fp.text().split("(")[1].split(")")[0]) if "(" in self.f_fp.text() else 0
            self._update_chip_styles(c_all, c_crit, c_repo, c_aur, c_fp)
            self.apply_filter()
            self._arm_theme_watcher()

        def apply_theme(self):
            p = self.palette
            self.setStyleSheet(f"""
                QMainWindow {{
                    background-color: {p['background']};
                }}
            """)

            if hasattr(self, "hdr_icon_box"):
                self.hdr_icon_box.setStyleSheet(f"""
                    QFrame#hdrIconBox {{
                        background-color: {p['lighter_background']};
                        border: 1px solid {p['card_border']};
                        border-radius: 10px;
                    }}
                """)
            if hasattr(self, "lbl_badge"):
                self.lbl_badge.setStyleSheet(f"background-color: {p['accent']}; color: #ffffff; font-weight: 900; font-size: 12px; padding: 2px 7px; border-radius: 4px;")
            if hasattr(self, "lbl_title"):
                self.lbl_title.setStyleSheet(f"color: {p['foreground']}; font-weight: 800; font-size: 19px; letter-spacing: 0.8px;")
            if hasattr(self, "lbl_sub"):
                self.lbl_sub.setStyleSheet(f"color: {p['muted']}; font-size: 12px;")
            if hasattr(self, "lbl_kernel"):
                self.lbl_kernel.setStyleSheet(f"background-color: {p['lighter_background']}; color: {p['sub_text']}; border: 1px solid {p['card_border']}; border-radius: 7px; padding: 0px 13px; font-size: 11px; font-weight: 700;")
            if hasattr(self, "lbl_uptime"):
                self.lbl_uptime.setStyleSheet(f"background-color: {p['lighter_background']}; color: {p['sub_text']}; border: 1px solid {p['card_border']}; border-radius: 7px; padding: 0px 13px; font-size: 11px; font-weight: 700;")
            if hasattr(self, "btn_refresh"):
                self.btn_refresh.setStyleSheet(f"""
                    QPushButton {{
                        background-color: {p['lighter_background']};
                        color: {p['foreground']};
                        border: 1px solid {p['card_border']};
                        border-radius: 7px;
                        padding: 0px 16px;
                        font-weight: 700;
                        font-size: 12px;
                    }}
                    QPushButton:hover {{
                        background-color: {p['selection']};
                        border: 1px solid {p['accent']};
                    }}
                    QPushButton:disabled {{
                        background-color: {p['dark_background']};
                        color: {p['muted']};
                        border: 1px solid {p['card_border']};
                    }}
                """)

            if hasattr(self, "search_input"):
                self.search_input.setStyleSheet(f"""
                    QLineEdit {{
                        background-color: {p['lighter_background']};
                        color: {p['foreground']};
                        border: 1px solid {p['card_border']};
                        border-radius: 8px;
                        padding: 0px 14px;
                        font-size: 13px;
                    }}
                    QLineEdit:focus {{
                        border: 1px solid {p['accent']};
                        background-color: {p['selection']};
                    }}
                """)

            if hasattr(self, "prog_bar"):
                self.prog_bar.setStyleSheet(f"""
                    QProgressBar {{
                        background: {p['dark_background']};
                        border: none;
                    }}
                    QProgressBar::chunk {{
                        background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 {p['laser_stop0']}, stop:1 {p['laser_stop1']});
                    }}
                """)

            if hasattr(self, "table"):
                self.table.setStyleSheet(f"""
                    QTableWidget {{
                        background-color: {p['table_bg']};
                        alternate-background-color: {p['table_alt_bg']};
                        color: {p['foreground']};
                        border: 1px solid {p['table_border']};
                        border-radius: 10px;
                        selection-background-color: {p['selection']};
                        selection-color: {p['foreground']};
                        font-size: 13px;
                    }}
                    QTableWidget::item {{
                        padding: 0px 14px;
                        border-bottom: 1px solid {p['card_border']};
                    }}
                    QHeaderView::section {{
                        background-color: {p['lighter_background']};
                        color: {p['muted']};
                        padding: 10px 14px;
                        border: none;
                        border-bottom: 2px solid {p['accent']};
                        font-weight: 800;
                        font-size: 11px;
                        letter-spacing: 0.6px;
                    }}
                    QHeaderView::section:hover {{
                        background-color: {p['selection']};
                        color: {p['foreground']};
                    }}
                    QScrollBar:vertical {{
                        background: {p['table_bg']};
                        width: 10px;
                        margin: 0px;
                        border-radius: 5px;
                    }}
                    QScrollBar::handle:vertical {{
                        background: {p['card_border']};
                        min-height: 35px;
                        border-radius: 5px;
                    }}
                    QScrollBar::handle:vertical:hover {{
                        background: {p['accent']};
                    }}
                    QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{
                        height: 0px;
                    }}
                """)

            if hasattr(self, "zero_card"):
                self.zero_card.setStyleSheet(f"""
                    QFrame#zero_card {{
                        background-color: {p['table_alt_bg']};
                        border: 1px solid {p['card_border']};
                        border-radius: 12px;
                    }}
                    QFrame#zero_card QLabel {{
                        border: none;
                        background: transparent;
                    }}
                """)
            if hasattr(self, "lbl_zero_icon"):
                self.lbl_zero_icon.setStyleSheet(f"""
                    background-color: {p['green_bg']};
                    color: {p['green_text']};
                    border: 1px solid {p['green_border']};
                    border-radius: 30px;
                    font-size: 28px;
                    font-weight: 900;
                """)
            if hasattr(self, "lbl_zero_title"):
                self.lbl_zero_title.setStyleSheet(f"color: {p['green_text']}; font-size: 17px; font-weight: 800;")
            if hasattr(self, "lbl_zero_desc"):
                self.lbl_zero_desc.setStyleSheet(f"color: {p['muted']}; font-size: 13px;")

            if hasattr(self, "footer_frame"):
                self.footer_frame.setStyleSheet(f"""
                    QFrame#footerFrame {{
                        background-color: {p['lighter_background']};
                        border: 1px solid {p['card_border']};
                        border-radius: 10px;
                    }}
                    QFrame#footerFrame QLabel {{
                        border: none;
                        background: transparent;
                    }}
                """)
            if hasattr(self, "lbl_summary"):
                self.lbl_summary.setStyleSheet(f"color: {p['foreground']}; font-weight: 700; font-size: 13px;")
            if hasattr(self, "lbl_sub_summary"):
                self.lbl_sub_summary.setStyleSheet(f"color: {p['muted']}; font-size: 11px;")
            if hasattr(self, "btn_close"):
                self.btn_close.setStyleSheet(f"""
                    QPushButton {{
                        background-color: {p['table_bg']};
                        color: {p['sub_text']};
                        border: 1px solid {p['card_border']};
                        border-radius: 8px;
                        padding: 0px 20px;
                        font-weight: 600;
                        font-size: 13px;
                    }}
                    QPushButton:hover {{
                        background-color: {p['selection']};
                        color: {p['foreground']};
                        border: 1px solid {p['accent']};
                    }}
                """)
            if hasattr(self, "btn_update"):
                self.btn_update.setStyleSheet(f"""
                    QPushButton {{
                        background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 {p['accent']}, stop:1 {p['accent_subtle']});
                        color: #ffffff;
                        border: 1px solid {p['accent_hover']};
                        border-radius: 8px;
                        padding: 0px 26px;
                        font-weight: 700;
                        font-size: 13px;
                    }}
                    QPushButton:hover {{
                        background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 {p['accent_hover']}, stop:1 {p['accent']});
                    }}
                    QPushButton:disabled {{
                        background-color: {p['dark_background']};
                        color: {p['muted']};
                        border: 1px solid {p['card_border']};
                    }}
                """)

            if hasattr(self, "lbl_live"):
                self.lbl_live.setStyleSheet(f"background-color: {p['accent']}; color: #ffffff; font-weight: 900; font-size: 12px; padding: 2px 8px; border-radius: 4px;")
            if hasattr(self, "lbl_tx_title"):
                self.lbl_tx_title.setStyleSheet(f"color: {p['foreground']}; font-weight: 800; font-size: 18px; letter-spacing: 0.5px;")
            if hasattr(self, "lbl_elapsed"):
                self.lbl_elapsed.setStyleSheet(f"background: {p['lighter_background']}; color: {p['sub_text']}; border: 1px solid {p['card_border']}; border-radius: 6px; padding: 6px 14px; font-size: 12px; font-weight: bold;")
            if hasattr(self, "log_view"):
                self.log_view.setStyleSheet(f"""
                    QTextEdit {{
                        background-color: {p['darker_background']};
                        color: {p['foreground']};
                        border: 1px solid {p['card_border']};
                        border-radius: 8px;
                        padding: 12px;
                        font-family: 'JetBrainsMono Nerd Font', 'Noto Sans Mono', monospace;
                        font-size: 12px;
                        line-height: 1.4;
                    }}
                    QScrollBar:vertical {{
                        background: {p['darker_background']};
                        width: 10px;
                        margin: 0px;
                        border-radius: 5px;
                    }}
                    QScrollBar::handle:vertical {{
                        background: {p['card_border']};
                        min-height: 35px;
                        border-radius: 5px;
                    }}
                    QScrollBar::handle:vertical:hover {{
                        background: {p['accent']};
                    }}
                    QScrollBar::horizontal {{
                        background: {p['darker_background']};
                        height: 10px;
                        margin: 0px;
                        border-radius: 5px;
                    }}
                    QScrollBar::handle:horizontal {{
                        background: {p['card_border']};
                        min-width: 35px;
                        border-radius: 5px;
                    }}
                    QScrollBar::handle:horizontal:hover {{
                        background: {p['accent']};
                    }}
                """)
            if hasattr(self, "tx_footer"):
                self.tx_footer.setStyleSheet(f"""
                    QFrame#tx_footer {{
                        background-color: {p['lighter_background']};
                        border: 1px solid {p['card_border']};
                        border-radius: 10px;
                        padding: 8px 16px;
                    }}
                """)
            if hasattr(self, "lbl_tx_status"):
                self.lbl_tx_status.setStyleSheet(f"color: {p['foreground']}; font-weight: bold; font-size: 13px;")

        def init_ui(self):
            self.stacked_widget = QStackedWidget()
            self.setCentralWidget(self.stacked_widget)

            # PAGE 0: Packages List View
            self.page_packages = QWidget()
            self.init_packages_page(self.page_packages)
            self.stacked_widget.addWidget(self.page_packages)

            # PAGE 1: In-App Live Transaction View
            self.page_transaction = QWidget()
            self.init_transaction_page(self.page_transaction)
            self.stacked_widget.addWidget(self.page_transaction)

        def init_packages_page(self, parent):
            layout = QVBoxLayout(parent)
            layout.setContentsMargins(24, 20, 24, 20)
            layout.setSpacing(16)

            # Header Hero
            header_layout = QHBoxLayout()
            header_layout.setSpacing(14)

            self.hdr_icon_box = QFrame()
            self.hdr_icon_box.setObjectName("hdrIconBox")
            self.hdr_icon_box.setFixedSize(44, 44)

            hib_layout = QVBoxLayout(self.hdr_icon_box)
            hib_layout.setContentsMargins(0, 0, 0, 0)
            hib_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
            lbl_hdr_icon = QLabel()
            lbl_hdr_icon.setStyleSheet("border: none; background: transparent;")
            for icon_path in [
                "/usr/share/pixmaps/x64-update.png",
                "/usr/share/icons/hicolor/128x128/apps/x64-update.png",
                os.path.expanduser("~/Proyectos/X64-LIOS-Packages/x64-update/icons/128x128/apps/x64-update.png")
            ]:
                if os.path.exists(icon_path):
                    pix = QPixmap(icon_path).scaled(
                        30, 30,
                        Qt.AspectRatioMode.KeepAspectRatio,
                        Qt.TransformationMode.SmoothTransformation
                    )
                    lbl_hdr_icon.setPixmap(pix)
                    break
            hib_layout.addWidget(lbl_hdr_icon)
            self.hdr_icon_box.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
            header_layout.addWidget(self.hdr_icon_box)

            title_vbox = QVBoxLayout()
            title_vbox.setSpacing(2)

            title_row = QHBoxLayout()
            title_row.setSpacing(8)
            self.lbl_badge = QLabel("X64")
            self.lbl_badge.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
            self.lbl_title = QLabel("LIOS UPDATE")
            self.lbl_title.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
            title_row.addWidget(self.lbl_badge)
            title_row.addWidget(self.lbl_title)
            title_row.addStretch()

            self.lbl_sub = QLabel("Centro de Actualizaciones y Mantenimiento del Sistema")
            self.lbl_sub.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)

            title_vbox.addLayout(title_row)
            title_vbox.addWidget(self.lbl_sub)
            header_layout.addLayout(title_vbox)

            header_layout.addStretch()

            t = get_telemetry()
            self.lbl_kernel = QLabel(f"Kernel: {t['kernel']}")
            self.lbl_kernel.setFixedHeight(34)
            self.lbl_kernel.setAlignment(Qt.AlignmentFlag.AlignCenter)

            self.lbl_uptime = QLabel(f"Activo: {t['uptime']}")
            self.lbl_uptime.setFixedHeight(34)
            self.lbl_uptime.setAlignment(Qt.AlignmentFlag.AlignCenter)

            self.btn_refresh = QPushButton("⟳ Comprobar")
            self.btn_refresh.setFixedHeight(34)
            self.btn_refresh.setCursor(Qt.CursorShape.PointingHandCursor)
            self.btn_refresh.clicked.connect(self.trigger_refresh)

            self.btn_close = QPushButton("✕")
            self.btn_close.setFixedSize(30, 30)
            self.btn_close.setCursor(Qt.CursorShape.PointingHandCursor)
            self.btn_close.setToolTip("Cerrar")
            self.btn_close.setStyleSheet("""
                QPushButton {
                    background-color: rgba(255, 255, 255, 0.05);
                    color: #a1a1aa;
                    border: 1px solid rgba(255, 255, 255, 0.08);
                    border-radius: 15px;
                    font-size: 13px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #ef4444;
                    color: #ffffff;
                    border: 1px solid #ef4444;
                }
                QPushButton:pressed {
                    background-color: #dc2626;
                    color: #ffffff;
                    border: 1px solid #dc2626;
                }
            """)
            self.btn_close.clicked.connect(self.close)

            header_layout.addWidget(self.lbl_kernel)
            header_layout.addWidget(self.lbl_uptime)
            header_layout.addWidget(self.btn_refresh)
            header_layout.addSpacing(6)
            header_layout.addWidget(self.btn_close)
            desktop_name = (os.environ.get("XDG_CURRENT_DESKTOP") or "").lower()
            session_name = (os.environ.get("DESKTOP_SESSION") or "").lower()
            is_tiling = any(k in desktop_name or k in session_name for k in ["hyprland", "niri", "sway", "i3", "river", "bspwm", "qtile", "dwm"])
            self.btn_close.setVisible(is_tiling)
            layout.addLayout(header_layout)

            # Search & Filter Chips Bar
            filter_layout = QHBoxLayout()
            filter_layout.setSpacing(10)

            self.search_input = QLineEdit()
            self.search_input.setFixedHeight(36)
            self.search_input.setPlaceholderText("Filtrar paquetes por nombre o versión...")
            self.search_input.textChanged.connect(self.apply_filter)
            filter_layout.addWidget(self.search_input, stretch=2)

            self.btn_group = QButtonGroup(self)
            self.btn_group.setExclusive(True)

            self.f_all = QPushButton("Todos (0)")
            self.f_all.setCheckable(True)
            self.f_all.setChecked(True)
            self.f_all.setProperty("filter", "all")

            self.f_crit = QPushButton("Críticos (0)")
            self.f_crit.setCheckable(True)
            self.f_crit.setProperty("filter", "crit")

            self.f_repo = QPushButton("Sistema (0)")
            self.f_repo.setCheckable(True)
            self.f_repo.setProperty("filter", "repo")

            self.f_aur = QPushButton("AUR (0)")
            self.f_aur.setCheckable(True)
            self.f_aur.setProperty("filter", "aur")

            self.f_fp = QPushButton("Flatpak (0)")
            self.f_fp.setCheckable(True)
            self.f_fp.setProperty("filter", "fp")

            for btn in [self.f_all, self.f_crit, self.f_repo, self.f_aur, self.f_fp]:
                btn.setFixedHeight(36)
                btn.setCursor(Qt.CursorShape.PointingHandCursor)
                self.btn_group.addButton(btn)
                btn.clicked.connect(self.on_filter_clicked)
                filter_layout.addWidget(btn)

            layout.addLayout(filter_layout)

            # Progress Bar (Thin Laser Line)
            self.prog_bar = QProgressBar()
            self.prog_bar.setFixedHeight(3)
            self.prog_bar.setTextVisible(False)
            self.prog_bar.setRange(0, 0)
            self.prog_bar.setVisible(False)
            layout.addWidget(self.prog_bar)

            # Main Table of Packages
            self.table = QTableWidget()
            self.table.setColumnCount(4)
            self.table.setHorizontalHeaderLabels(["ORIGEN / TIPO", "PAQUETE", "VERSIÓN ACTUAL", "NUEVA VERSIÓN"])
            self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
            self.table.setColumnWidth(0, 145)
            self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
            self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)
            self.table.setColumnWidth(2, 175)
            self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.Fixed)
            self.table.setColumnWidth(3, 185)
            self.table.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.horizontalHeaderItem(1).setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
            self.table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
            self.table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
            self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
            self.table.setFocusPolicy(Qt.FocusPolicy.NoFocus)
            self.table.setShowGrid(False)
            self.table.verticalHeader().setVisible(False)
            self.table.verticalHeader().setDefaultSectionSize(44)
            self.table.setAlternatingRowColors(True)
            self.table.setSortingEnabled(True)
            self.badge_delegate = BadgeDelegate(self.table, self.palette)
            self.table.setItemDelegateForColumn(0, self.badge_delegate)
            layout.addWidget(self.table, stretch=1)

            # Zero Updates Card (Placeholder when system is up to date)
            self.zero_card = QFrame()
            self.zero_card.setObjectName("zero_card")
            zero_vbox = QVBoxLayout(self.zero_card)
            zero_vbox.setContentsMargins(40, 50, 40, 50)
            zero_vbox.setAlignment(Qt.AlignmentFlag.AlignCenter)
            zero_vbox.setSpacing(12)

            self.lbl_zero_icon = QLabel("✓")
            self.lbl_zero_icon.setFixedSize(60, 60)
            self.lbl_zero_icon.setAlignment(Qt.AlignmentFlag.AlignCenter)

            self.lbl_zero_title = QLabel("Tu sistema X64 LIOS está completamente al día")
            self.lbl_zero_title.setAlignment(Qt.AlignmentFlag.AlignCenter)

            self.lbl_zero_desc = QLabel("Todos los paquetes del sistema, módulos X64 LIOS, catálogo AUR y aplicaciones Flatpak están en su última versión.")
            self.lbl_zero_desc.setAlignment(Qt.AlignmentFlag.AlignCenter)

            zero_vbox.addWidget(self.lbl_zero_icon, alignment=Qt.AlignmentFlag.AlignCenter)
            zero_vbox.addWidget(self.lbl_zero_title)
            zero_vbox.addWidget(self.lbl_zero_desc)

            self.zero_card.setVisible(False)
            layout.addWidget(self.zero_card, stretch=1)

            # Footer Action Bar (strictly scoped by #footerFrame so QLabels never inherit borders)
            self.footer_frame = QFrame()
            self.footer_frame.setObjectName("footerFrame")
            footer_layout = QHBoxLayout(self.footer_frame)
            footer_layout.setContentsMargins(18, 12, 18, 12)
            footer_layout.setSpacing(16)

            opts_vbox = QVBoxLayout()
            opts_vbox.setSpacing(3)

            self.lbl_summary = QLabel("Analizando estado de los paquetes...")
            opts_vbox.addWidget(self.lbl_summary)

            self.lbl_sub_summary = QLabel("Limpieza automática de paquetes residuales y caché segura activada")
            opts_vbox.addWidget(self.lbl_sub_summary)

            footer_layout.addLayout(opts_vbox, stretch=2)

            btn_box = QHBoxLayout()
            btn_box.setSpacing(10)

            self.btn_close = QPushButton("Cerrar")
            self.btn_close.setFixedHeight(38)
            self.btn_close.setCursor(Qt.CursorShape.PointingHandCursor)
            self.btn_close.clicked.connect(self.close)

            self.btn_update = QPushButton("Actualizar Sistema")
            self.btn_update.setObjectName("btn-update")
            self.btn_update.setFixedHeight(38)
            self.btn_update.setCursor(Qt.CursorShape.PointingHandCursor)
            self.btn_update.clicked.connect(self.start_inapp_transaction)

            btn_box.addWidget(self.btn_close)
            btn_box.addWidget(self.btn_update)
            footer_layout.addLayout(btn_box)

            layout.addWidget(self.footer_frame)

        def _update_chip_styles(self, tot, crit_cnt, repo_cnt, aur_cnt, fp_cnt):
            p = self.palette
            counts = {
                self.f_all: tot,
                self.f_crit: crit_cnt,
                self.f_repo: repo_cnt,
                self.f_aur: aur_cnt,
                self.f_fp: fp_cnt,
            }
            for btn, cnt in counts.items():
                fg = p['foreground'] if cnt > 0 else p['muted']
                bg = p['lighter_background'] if cnt > 0 else p['dark_background']
                bdr = p['accent_hover'] if cnt > 0 else p['card_border']
                btn.setStyleSheet(f"""
                    QPushButton {{
                        background-color: {bg};
                        color: {fg};
                        border: 1px solid {bdr};
                        border-radius: 8px;
                        padding: 0px 14px;
                        font-weight: 600;
                        font-size: 12px;
                    }}
                    QPushButton:hover {{
                        background-color: {p['selection']};
                        color: {p['foreground']};
                    }}
                    QPushButton:checked {{
                        background-color: {p['accent']};
                        color: #ffffff;
                        border: 1px solid {p['accent_hover']};
                        font-weight: 700;
                    }}
                """)

        def init_transaction_page(self, parent):
            layout = QVBoxLayout(parent)
            layout.setContentsMargins(24, 20, 24, 20)
            layout.setSpacing(14)

            # Hero Header
            hdr_layout = QHBoxLayout()
            vbox = QVBoxLayout()
            vbox.setSpacing(2)

            title_row = QHBoxLayout()
            self.lbl_live = QLabel("EN VIVO")
            self.lbl_tx_title = QLabel("ACTUALIZACIÓN DEL SISTEMA EN PROGRESO")
            title_row.addWidget(self.lbl_live)
            title_row.addWidget(self.lbl_tx_title)
            title_row.addStretch()

            self.lbl_tx_stage = QLabel("Inicializando transacción de paquetes...")
            self.lbl_tx_stage.setStyleSheet("color: #38bdf8; font-size: 13px; font-weight: bold;")

            vbox.addLayout(title_row)
            vbox.addWidget(self.lbl_tx_stage)
            hdr_layout.addLayout(vbox)

            hdr_layout.addStretch()

            self.lbl_elapsed = QLabel("⏱ Tiempo: 00:00")
            hdr_layout.addWidget(self.lbl_elapsed)

            layout.addLayout(hdr_layout)

            # Main Progress Bar
            self.tx_progress = QProgressBar()
            self.tx_progress.setFixedHeight(8)
            self.tx_progress.setTextVisible(False)
            self.tx_progress.setRange(0, 100)
            self.tx_progress.setValue(10)
            layout.addWidget(self.tx_progress)

            # Embedded Console Log View
            self.log_view = QTextEdit()
            self.log_view.setReadOnly(True)
            self.log_view.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap)
            layout.addWidget(self.log_view, stretch=1)

            # Transaction Footer
            self.tx_footer = QFrame()
            self.tx_footer.setObjectName("tx_footer")
            footer_box = QHBoxLayout(self.tx_footer)
            footer_box.setContentsMargins(14, 10, 14, 10)
            footer_box.setSpacing(16)

            self.lbl_tx_status = QLabel("⏳ Ejecutando comandos de actualización...")
            footer_box.addWidget(self.lbl_tx_status, stretch=2)

            self.btn_tx_reboot = QPushButton("⚡ Reiniciar Ahora")
            self.btn_tx_reboot.setCursor(Qt.CursorShape.PointingHandCursor)
            self.btn_tx_reboot.setStyleSheet("""
                QPushButton {
                    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #ef4444, stop:1 #b91c1c);
                    color: #ffffff;
                    border: 1px solid #f87171;
                    border-radius: 8px;
                    padding: 10px 24px;
                    font-weight: 800;
                    font-size: 13px;
                }
                QPushButton:hover {
                    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #f87171, stop:1 #dc2626);
                    border: 1px solid #fca5a5;
                }
                QPushButton:pressed {
                    background: #991b1b;
                    border: 1px solid #b91c1c;
                }
            """)
            self.btn_tx_reboot.setVisible(False)
            self.btn_tx_reboot.clicked.connect(lambda: os.system("systemctl reboot 2>/dev/null || sudo systemctl reboot"))
            footer_box.addWidget(self.btn_tx_reboot)

            self.btn_tx_done = QPushButton("Procesando...")
            self.btn_tx_done.setCursor(Qt.CursorShape.PointingHandCursor)
            self.btn_tx_done.setEnabled(False) # Enabled only on finish
            self.btn_tx_done.clicked.connect(self.on_tx_close_clicked)
            footer_box.addWidget(self.btn_tx_done)

            layout.addWidget(self.tx_footer)

        def update_elapsed_time(self):
            elapsed = int(time.time() - self.tx_start_time)
            mins = elapsed // 60
            secs = elapsed % 60
            self.lbl_elapsed.setText(f"⏱ Tiempo: {mins:02d}:{secs:02d}")

        def load_cached_state(self):
            if not os.path.exists(PACKAGES_FILE):
                return
            try:
                lines = []
                with open(PACKAGES_FILE, "r", encoding="utf-8") as f:
                    lines = [l.strip() for l in f if l.strip()]
                
                repo_l = [l for l in lines if not l.endswith("(AUR)") and not l.endswith("(Flatpak)")]
                aur_l  = [l.replace(" (AUR)", "") for l in lines if l.endswith("(AUR)")]
                fp_l   = [l.replace(" (Flatpak)", "") for l in lines if l.endswith("(Flatpak)")]

                self.populate_items(repo_l, aur_l, fp_l)
            except Exception:
                pass

        def trigger_refresh(self):
            if self.check_worker and self.check_worker.isRunning():
                return
            self.prog_bar.setVisible(True)
            self.btn_refresh.setEnabled(False)
            self.btn_refresh.setText("Analizando...")

            self.check_worker = CheckWorker()
            self.check_worker.finished.connect(self.on_check_finished)
            self.check_worker.start()

        def on_check_finished(self, data):
            self.prog_bar.setVisible(False)
            self.btn_refresh.setEnabled(True)
            self.btn_refresh.setText("⟳ Comprobar")

            self.populate_items(data["repo"], data["aur"], data["flatpak"])

        def populate_items(self, repo_pkgs, aur_pkgs, flatpak_pkgs):
            self.all_items = []
            
            for line in repo_pkgs:
                p, old_v, new_v = parse_pkg_line(line)
                is_crit = is_critical_package(p)
                is_x64 = is_x64_package(p)
                self.all_items.append({
                    "pkg": p,
                    "old_v": old_v,
                    "new_v": new_v,
                    "type": "Sistema",
                    "x64": is_x64,
                    "crit": is_crit
                })

            for line in aur_pkgs:
                p, old_v, new_v = parse_pkg_line(line)
                is_crit = is_critical_package(p)
                is_x64 = is_x64_package(p)
                self.all_items.append({
                    "pkg": p,
                    "old_v": old_v,
                    "new_v": new_v,
                    "type": "AUR",
                    "x64": is_x64,
                    "crit": is_crit
                })

            for line in flatpak_pkgs:
                p, old_v, new_v = parse_pkg_line(line)
                self.all_items.append({
                    "pkg": p,
                    "old_v": old_v,
                    "new_v": new_v,
                    "type": "Flatpak",
                    "x64": False,
                    "crit": False
                })

            self.all_items.sort(key=lambda x: (0 if x["crit"] else (1 if x["x64"] else 2), x["pkg"]))

            tot = len(self.all_items)
            crit_cnt = sum(1 for x in self.all_items if x["crit"])
            repo_cnt = sum(1 for x in self.all_items if x["type"] == "Sistema")
            aur_cnt  = sum(1 for x in self.all_items if x["type"] == "AUR")
            fp_cnt   = sum(1 for x in self.all_items if x["type"] == "Flatpak")

            self.f_all.setText(f"Todos ({tot})")
            self.f_crit.setText(f"Críticos ({crit_cnt})")
            self.f_repo.setText(f"Sistema ({repo_cnt})")
            self.f_aur.setText(f"AUR ({aur_cnt})")
            self.f_fp.setText(f"Flatpak ({fp_cnt})")
            self._update_chip_styles(tot, crit_cnt, repo_cnt, aur_cnt, fp_cnt)

            if tot == 0:
                self.lbl_summary.setText("No hay actualizaciones pendientes.")
                self.btn_update.setEnabled(False)
                self.btn_update.setText("Sistema al Día")
                self.table.setVisible(False)
                self.zero_card.setVisible(True)
            else:
                pkg_txt = "1 paquete pendiente de actualización" if tot == 1 else f"<b>{tot}</b> paquetes pendientes de actualización"
                if crit_cnt > 0:
                    c_txt = "1 componente crítico" if crit_cnt == 1 else f"{crit_cnt} componentes críticos"
                    crit_msg = f" &nbsp;•&nbsp; <span style='color: #fbbf24;'>{c_txt}</span>"
                else:
                    crit_msg = ""
                self.lbl_summary.setText(f"{pkg_txt}{crit_msg}")
                self.btn_update.setEnabled(True)
                self.btn_update.setText(f"Actualizar Sistema ({tot})")
                self.table.setVisible(True)
                self.zero_card.setVisible(False)

            self.apply_filter()

        def on_filter_clicked(self):
            sender = self.sender()
            if sender:
                self.active_filter = sender.property("filter")
                self.apply_filter()

        def apply_filter(self):
            query = self.search_input.text().strip().lower()

            self.table.setSortingEnabled(False)
            self.table.setRowCount(0)

            mono_font = QFont("JetBrainsMono Nerd Font")
            mono_font.setPointSize(10)
            mono_bold = QFont("JetBrainsMono Nerd Font")
            mono_bold.setPointSize(10)
            mono_bold.setBold(True)

            for item in self.all_items:
                if self.active_filter == "crit" and not item["crit"]:
                    continue
                if self.active_filter == "repo" and item["type"] != "Sistema":
                    continue
                if self.active_filter == "aur" and item["type"] != "AUR":
                    continue
                if self.active_filter == "fp" and item["type"] != "Flatpak":
                    continue

                if query:
                    if query not in item["pkg"].lower() and query not in item["new_v"].lower():
                        continue

                row = self.table.rowCount()
                self.table.insertRow(row)

                # Col 0: Rounded Pill Badge via BadgeDelegate
                if item["crit"]:
                    sort_key = "1_Crítico"
                    meta = {"label": "Crítico", "fg": "#fbbf24", "bg": "#2b1d06", "border": "#573b0c"}
                elif item.get("x64"):
                    sort_key = "2_X64 LIOS"
                    meta = {"label": "X64 LIOS", "fg": "#ff4d4d", "bg": "#2a0a0e", "border": "#5c161e"}
                elif item["type"] == "Sistema":
                    sort_key = "3_Sistema"
                    meta = {"label": "Sistema", "fg": "#38bdf8", "bg": "#092030", "border": "#123b56"}
                elif item["type"] == "AUR":
                    sort_key = "4_AUR"
                    meta = {"label": "AUR", "fg": "#e879f9", "bg": "#26092e", "border": "#481456"}
                else:
                    sort_key = "5_Flatpak"
                    meta = {"label": "Flatpak", "fg": "#818cf8", "bg": "#101036", "border": "#232368"}

                tag_item = QTableWidgetItem(sort_key)
                tag_item.setData(Qt.ItemDataRole.UserRole, meta)
                self.table.setItem(row, 0, tag_item)

                # Col 1: Package Name
                p_item = QTableWidgetItem(item["pkg"])
                p_font = QFont()
                p_font.setBold(True)
                p_item.setFont(p_font)
                p_item.setForeground(QColor(self.palette["foreground"]))
                self.table.setItem(row, 1, p_item)

                # Col 2: Current Version
                old_item = QTableWidgetItem(item["old_v"] if item["old_v"] else "—")
                old_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                old_item.setFont(mono_font)
                old_item.setForeground(QColor(self.palette["sub_text"]))
                self.table.setItem(row, 2, old_item)

                # Col 3: New Version
                new_str = f"➔  {item['new_v']}" if item["new_v"] else "disponible"
                new_item = QTableWidgetItem(new_str)
                new_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                new_item.setFont(mono_bold)
                new_item.setForeground(QColor(self.palette["green_text"]) if not item["crit"] else QColor(self.palette["yellow_text"]))
                self.table.setItem(row, 3, new_item)

            self.table.setSortingEnabled(True)

        def start_inapp_transaction(self):
            # Check if passwordless sudo (NOPASSWD) or a session-verified password is already available for a new PTY
            nopasswd_sudo = (
                subprocess.run(
                    ["setsid", "sudo", "-n", "-v"],
                    stdin=subprocess.DEVNULL,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL
                ).returncode == 0
            )
            cached_sudo = nopasswd_sudo or bool(getattr(self, "_session_sudo_pwd", None))

            # Count total items and breakdown by category
            items_count = len(self.all_items)
            crit_count = sum(1 for item in self.all_items if item.get("crit", False))
            breakdown = {
                "x64": sum(1 for item in self.all_items if item.get("x64", False)),
                "repo": sum(1 for item in self.all_items if item.get("type") == "Sistema" and not item.get("x64", False)),
                "aur": sum(1 for item in self.all_items if item.get("type") == "AUR" and not item.get("x64", False)),
                "fp": sum(1 for item in self.all_items if item.get("type") == "Flatpak"),
            }

            dlg = ConfirmDialog(items_count, crit_count, cached_sudo, self, breakdown=breakdown, palette=self.palette)
            if dlg.exec() != QDialog.DialogCode.Accepted:
                return # User canceled
            if dlg.get_password():
                self._session_sudo_pwd = dlg.get_password()
            password = getattr(self, "_session_sudo_pwd", None)
            sudo_cmd = "sudo -A" if password else "sudo"

            # Assemble transaction commands (100% full parity with omarchy-update & CachyOS/X64 pipeline)
            aur_helper = "paru" if shutil.which("paru") else ("yay" if shutil.which("yay") else None)
            has_repo_updates = any(item.get("type") == "Sistema" for item in self.all_items)
            has_aur_updates = any(item.get("type") == "AUR" for item in self.all_items)
            has_fp_updates = any(item.get("type") == "Flatpak" for item in self.all_items)

            commands, display_cmds = build_update_pipeline(
                sudo_cmd=sudo_cmd,
                aur_helper=aur_helper,
                choice="1",
                has_repo=has_repo_updates or (not has_aur_updates and not has_fp_updates),
                has_aur=has_aur_updates,
                has_fp=has_fp_updates,
                password=password
            )

            # Switch to In-App Transaction View
            self.stacked_widget.setCurrentIndex(1)
            cmd_display = " && ".join(display_cmds).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
            header_html = (
                f"<div style=\"color: #ef4444; font-weight: bold; font-family: 'JetBrainsMono Nerd Font', 'Noto Sans Mono', monospace; font-size: 12px;\">"
                f"[X64 LIOS UPDATE] INICIANDO TRANSACCIÓN DE ACTUALIZACIÓN DEL SISTEMA...</div>"
                f"<div style=\"color: #71717a; font-family: 'JetBrainsMono Nerd Font', 'Noto Sans Mono', monospace; font-size: 12px;\">"
                f"Comandos: {cmd_display}</div>"
                f"<div style=\"color: #222230; font-family: 'JetBrainsMono Nerd Font', 'Noto Sans Mono', monospace; font-size: 12px; margin-bottom: 6px;\">"
                f"{'─' * 104}</div>"
            )
            self.vt_screen = Vt100Screen(header_html=header_html)
            self.vt_last_render = 0.0
            if not hasattr(self, "vt_render_timer"):
                self.vt_render_timer = QTimer(self)
                self.vt_render_timer.setSingleShot(True)
                self.vt_render_timer.timeout.connect(self.flush_vt_render)
            self.log_view.setHtml(self.vt_screen.to_html())

            # Reset header and transaction state
            self.lbl_live.setText("EN VIVO")
            self.lbl_live.setStyleSheet("background-color: #ef4444; color: #ffffff; font-weight: 900; font-size: 12px; padding: 2px 8px; border-radius: 4px;")
            self.lbl_tx_title.setText("ACTUALIZACIÓN DEL SISTEMA EN PROGRESO")
            self.lbl_tx_stage.setText("Inicializando transacción de paquetes...")
            self.lbl_tx_stage.setStyleSheet("color: #38bdf8; font-size: 13px; font-weight: bold;")
            self.lbl_tx_status.setText("⏳ Ejecutando comandos de actualización...")
            self.lbl_tx_status.setStyleSheet("color: #ffffff; font-weight: bold; font-size: 13px;")

            self.btn_tx_done.setEnabled(False)
            self.btn_tx_done.setText("Procesando...")
            self.btn_tx_done.setStyleSheet("""
                QPushButton {
                    background: #181822;
                    color: #555566;
                    border: 1px solid #222230;
                    border-radius: 8px;
                    padding: 10px 24px;
                    font-weight: bold;
                    font-size: 13px;
                }
            """)
            self.btn_tx_reboot.setVisible(False)
            self.tx_progress.setValue(10)
            self.tx_progress.setStyleSheet("""
                QProgressBar {
                    background-color: #14141e;
                    border: 1px solid #252536;
                    border-radius: 4px;
                }
                QProgressBar::chunk {
                    background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #ff1a1a, stop:0.7 #f59e0b, stop:1 #22c55e);
                    border-radius: 4px;
                }
            """)
            self.tx_start_time = time.time()
            self.timer_elapsed.start(1000)

            # Start worker thread
            self.tx_worker = TransactionWorker(commands, password)
            self.tx_worker.output_received.connect(self.on_tx_output)
            self.tx_worker.stage_changed.connect(self.on_tx_stage)
            self.tx_worker.transaction_done.connect(self.on_tx_finished)
            self.tx_worker.start()

        def flush_vt_render(self):
            if not hasattr(self, "vt_screen"):
                return
            self.vt_last_render = time.time()

            # Sticky scroll (terminal-like): only follow new output if the user is already at the bottom.
            # If the user scrolled up to read, keep their exact vertical and horizontal position.
            vbar = self.log_view.verticalScrollBar()
            hbar = self.log_view.horizontalScrollBar()
            prev_v = vbar.value()
            prev_h = hbar.value()
            was_at_bottom = prev_v >= vbar.maximum() - 8

            self.log_view.setHtml(self.vt_screen.to_html())

            if was_at_bottom:
                vbar.setValue(vbar.maximum())
            else:
                vbar.setValue(min(prev_v, vbar.maximum()))
            hbar.setValue(min(prev_h, hbar.maximum()))

        def on_tx_output(self, raw_text):
            if not hasattr(self, "vt_screen"):
                self.vt_screen = Vt100Screen()
            self.vt_screen.feed(raw_text)
            now = time.time()
            if now - getattr(self, "vt_last_render", 0.0) >= 0.025:
                if hasattr(self, "vt_render_timer") and self.vt_render_timer.isActive():
                    self.vt_render_timer.stop()
                self.flush_vt_render()
            else:
                if hasattr(self, "vt_render_timer") and not self.vt_render_timer.isActive():
                    self.vt_render_timer.start(25)

        def on_tx_stage(self, stage_text, percent):
            self.lbl_tx_stage.setText(stage_text)
            self.tx_progress.setValue(percent)

        def on_tx_finished(self, success, exit_code, kernel_updated):
            if hasattr(self, "vt_render_timer") and self.vt_render_timer.isActive():
                self.vt_render_timer.stop()
            self.flush_vt_render()
            self.timer_elapsed.stop()
            self.btn_tx_done.setEnabled(True)

            if success:
                self.lbl_live.setText("COMPLETADO")
                self.lbl_live.setStyleSheet("background-color: #22c55e; color: #ffffff; font-weight: 900; font-size: 12px; padding: 2px 8px; border-radius: 4px;")
                self.lbl_tx_title.setText("ACTUALIZACIÓN DEL SISTEMA FINALIZADA")
                self.lbl_tx_stage.setText("✓ ¡Todos los paquetes se han instalado y verificado con éxito!")
                self.lbl_tx_stage.setStyleSheet("color: #22c55e; font-size: 13px; font-weight: bold;")
                self.lbl_tx_status.setText("🛡️ Sistema X64 LIOS actualizado, sincronizado y seguro.")
                self.lbl_tx_status.setStyleSheet("color: #4ade80; font-weight: bold; font-size: 13px;")
                self.tx_progress.setValue(100)
                self.tx_progress.setStyleSheet("""
                    QProgressBar {
                        background-color: #14141e;
                        border: 1px solid #14532d;
                        border-radius: 4px;
                    }
                    QProgressBar::chunk {
                        background: #22c55e;
                        border-radius: 4px;
                    }
                """)

                self.btn_tx_done.setText("✓ Cerrar y Salir")
                self.btn_tx_done.setStyleSheet("""
                    QPushButton {
                        background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #22c55e, stop:1 #15803d);
                        color: #ffffff;
                        border: 1px solid #4ade80;
                        border-radius: 8px;
                        padding: 10px 24px;
                        font-weight: 800;
                        font-size: 13px;
                    }
                    QPushButton:hover {
                        background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #4ade80, stop:1 #16a34a);
                        border: 1px solid #86efac;
                    }
                """)

                if kernel_updated:
                    self.lbl_tx_status.setText("⚡ Se actualizó el Kernel o Driver gráfico. Se recomienda reiniciar.")
                    self.lbl_tx_status.setStyleSheet("color: #facc15; font-weight: bold; font-size: 13px;")
                    self.btn_tx_reboot.setVisible(True)
            else:
                self.lbl_live.setText("ERROR")
                self.lbl_live.setStyleSheet("background-color: #dc2626; color: #ffffff; font-weight: 900; font-size: 12px; padding: 2px 8px; border-radius: 4px;")
                self.lbl_tx_title.setText("ERROR EN LA ACTUALIZACIÓN")
                self.lbl_tx_stage.setText(f"✕ La transacción se interrumpió (código de salida: {exit_code})")
                self.lbl_tx_stage.setStyleSheet("color: #ef4444; font-size: 13px; font-weight: bold;")
                self.lbl_tx_status.setText("✕ La actualización no se pudo completar completamente.")
                self.lbl_tx_status.setStyleSheet("color: #f87171; font-weight: bold; font-size: 13px;")
                self.tx_progress.setStyleSheet("""
                    QProgressBar {
                        background-color: #14141e;
                        border: 1px solid #7f1d1d;
                        border-radius: 4px;
                    }
                    QProgressBar::chunk {
                        background: #ef4444;
                        border-radius: 4px;
                    }
                """)
                self.btn_tx_done.setText("← Volver")
                self.btn_tx_done.setStyleSheet("""
                    QPushButton {
                        background: #27273a;
                        color: #ffffff;
                        border: 1px solid #3e3e56;
                        border-radius: 8px;
                        padding: 10px 24px;
                        font-weight: bold;
                        font-size: 13px;
                    }
                    QPushButton:hover {
                        background: #32324a;
                        border: 1px solid #555577;
                    }
                """)

        def on_tx_close_clicked(self):
            if self.btn_tx_done.text().startswith("←") or "Volver" in self.btn_tx_done.text():
                self.stacked_widget.setCurrentIndex(0)
                self.trigger_refresh()
            else:
                self.close()

    # 2. Single-instance lock (prevent opening two concurrent x64-update windows)
    lock_file = open("/tmp/x64-update-gui.lock", "w")
    try:
        fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        sys.exit(0)

    app = QApplication(sys.argv)
    app.setDesktopFileName("x64-update")
    app.setApplicationName("x64-update")
    app.setStyle("Fusion")
    _palette = load_theme_palette()
    _pal = app.palette()
    _pal.setColor(QPalette.ColorRole.Window, QColor(_palette["background"]))
    _pal.setColor(QPalette.ColorRole.WindowText, QColor(_palette["foreground"]))
    _pal.setColor(QPalette.ColorRole.Base, QColor(_palette["table_bg"]))
    _pal.setColor(QPalette.ColorRole.AlternateBase, QColor(_palette["lighter_background"]))
    _pal.setColor(QPalette.ColorRole.Text, QColor(_palette["foreground"]))
    _pal.setColor(QPalette.ColorRole.Button, QColor(_palette["lighter_background"]))
    _pal.setColor(QPalette.ColorRole.ButtonText, QColor(_palette["foreground"]))
    _pal.setColor(QPalette.ColorRole.Highlight, QColor(_palette["accent"]))
    _pal.setColor(QPalette.ColorRole.HighlightedText, QColor("#ffffff"))
    app.setPalette(_pal)
    win = X64UpdateWindow()
    win.show()
    sys.exit(app.exec())


# ==============================================================================
# CLI INTERACTIVO (Fallback para consola/TTY pura)
# ==============================================================================

def run_cli_interactive():
    if sys.stdout.isatty():
        os.system("clear")

    print(BANNER)
    t = get_telemetry()
    box_w = 82
    line_content = f"  {C_CYAN}Equipo:{C_RESET} {C_WHITE}{t['hostname']}{C_RESET}     {C_CYAN}Kernel:{C_RESET} {C_WHITE}{t['kernel']}{C_RESET}     {C_CYAN}Uptime:{C_RESET} {C_WHITE}{t['uptime']}{C_RESET}"
    visible_content = f"  Equipo: {t['hostname']}     Kernel: {t['kernel']}     Uptime: {t['uptime']}"
    pad = max(0, box_w - len(visible_content))

    print(f"{C_GRAY}  ┌{'─' * box_w}┐{C_RESET}")
    print(f"{C_GRAY}  │{C_RESET}{line_content}{' ' * pad}{C_GRAY}│{C_RESET}")
    print(f"{C_GRAY}  └{'─' * box_w}┘{C_RESET}\n")

    print(f"  {C_CYAN}[*]{C_RESET} Comprobando repositorios oficiales...")
    repo_pkgs = check_official_repos()
    omarchy_pkg = check_omarchy_git()
    if omarchy_pkg:
        repo_pkgs.insert(0, omarchy_pkg)
    aur_pkgs = check_aur_packages()
    flatpak_pkgs = check_flatpak_packages()

    total_updates = len(repo_pkgs) + len(aur_pkgs) + len(flatpak_pkgs)
    if total_updates == 0:
        print(f"\n  {C_GREEN}{C_BOLD}✓ ¡Tu sistema X64 LIOS está completamente al día!{C_RESET}\n")
        wait_for_user()
        return 0

    print(f"\n  {C_RED}{C_BOLD}▶ PAQUETES DETECTADOS PARA ACTUALIZACIÓN ({total_updates}):{C_RESET}\n")
    
    col_name_w = 32
    col_trans_w = 36
    col_type_w = 12
    header_top = f"{C_GRAY}  ┌{'─' * col_name_w}┬{'─' * col_trans_w}┬{'─' * col_type_w}┐{C_RESET}"
    header_mid = f"{C_GRAY}  ├{'─' * col_name_w}┼{'─' * col_trans_w}┼{'─' * col_type_w}┤{C_RESET}"
    header_bot = f"{C_GRAY}  └{'─' * col_name_w}┴{'─' * col_trans_w}┴{'─' * col_type_w}┘{C_RESET}"

    print(header_top)
    print(f"{C_GRAY}  │{C_RESET} {C_WHITE}{C_BOLD}{'PAQUETE':<{col_name_w-2}}{C_RESET} "
          f"{C_GRAY}│{C_RESET} {C_WHITE}{C_BOLD}{'TRANSICIÓN DE VERSIÓN':<{col_trans_w-2}}{C_RESET} "
          f"{C_GRAY}│{C_RESET} {C_WHITE}{C_BOLD}{'ORIGEN':<{col_type_w-2}}{C_RESET} {C_GRAY}│{C_RESET}")
    print(header_mid)

    all_list = []
    for line in repo_pkgs:
        p, old_v, new_v = parse_pkg_line(line)
        trans = f"{old_v} ➔ {new_v}" if new_v else old_v
        all_list.append((p, trans, "Oficial", C_CYAN, is_critical_package(p)))
    for line in aur_pkgs:
        p, old_v, new_v = parse_pkg_line(line)
        trans = f"{old_v} ➔ {new_v}" if new_v else old_v
        all_list.append((p, trans, "AUR", C_MAGENTA, is_critical_package(p)))
    for line in flatpak_pkgs:
        p, old_v, new_v = parse_pkg_line(line)
        all_list.append((p, old_v, "Flatpak", C_BLUE, False))

    all_list.sort(key=lambda x: (0 if x[4] else 1, x[0]))

    for p, trans, orig, col, is_crit in all_list:
        tag = f"{C_YELLOW}[!]{C_RESET} " if is_crit else "    "
        max_p_w = col_name_w - 6
        p_str = p if len(p) <= max_p_w else p[:max_p_w-2] + ".."
        pad_name = max(0, max_p_w - len(p_str))
        pkg_display = f"{tag}{col}{p_str}{C_RESET}{' ' * pad_name}"

        max_t_w = col_trans_w - 2
        t_str = trans if len(trans) <= max_t_w else trans[:max_t_w-2] + ".."
        pad_trans = max(0, max_t_w - len(t_str))

        max_o_w = col_type_w - 2
        o_str = orig[:max_o_w]
        pad_orig = max(0, max_o_w - len(o_str))

        print(f"{C_GRAY}  │{C_RESET} {pkg_display} "
              f"{C_GRAY}│{C_RESET} {C_WHITE}{t_str}{C_RESET}{' ' * pad_trans} "
              f"{C_GRAY}│{C_RESET} {col}{o_str}{C_RESET}{' ' * pad_orig} {C_GRAY}│{C_RESET}")

    print(header_bot)
    print()

    print(f"{C_WHITE}{C_BOLD}  OPCIONES DE ACTUALIZACIÓN:{C_RESET}")
    print(f"   {C_RED}[1]{C_RESET} {C_WHITE}Actualizar TODO el sistema ahora (Recomendado: Oficial + AUR + Flatpak){C_RESET}")
    print(f"   {C_RED}[2]{C_RESET} {C_WHITE}Solo repositorios oficiales{C_RESET}")
    print(f"   {C_RED}[3]{C_RESET} {C_WHITE}Actualizar y purgar caché de paquetes (pacman -Sc){C_RESET}")
    print(f"   {C_RED}[4]{C_RESET} {C_LIGHT}Cancelar y salir{C_RESET}\n")

    choice = "1"
    try:
        raw_choice = input(f"  {C_CYAN}Seleccione una opción [1-4] (por defecto 1): {C_RESET}").strip()
        if raw_choice:
            choice = raw_choice
    except (KeyboardInterrupt, EOFError):
        print(f"\n  {C_YELLOW}Operación cancelada.{C_RESET}")
        return 0

    if choice == "4":
        return 0

    aur_helper = "paru" if shutil.which("paru") else ("yay" if shutil.which("yay") else None)
    has_aur = (choice in ["1", "3"] and bool(aur_helper) and len(aur_pkgs) > 0)
    has_fp = (choice == "1" and bool(shutil.which("flatpak")) and len(flatpak_pkgs) > 0)
    has_repo = (len(repo_pkgs) > 0 or (not has_aur and not has_fp))

    cmds, _ = build_update_pipeline(
        sudo_cmd="sudo",
        aur_helper=aur_helper,
        choice=choice,
        has_repo=has_repo,
        has_aur=has_aur,
        has_fp=has_fp
    )

    print(f"\n  {C_RED}{C_BOLD}▶ EJECUTANDO TRANSACCIÓN INTEGRAL DEL SISTEMA...{C_RESET}\n")
    subprocess.run(" && ".join(cmds), shell=True)
    run_background_check_and_save()
    wait_for_user()
    return 0


# ==============================================================================
# MAIN ENTRYPOINT
# ==============================================================================

def main():
    parser = argparse.ArgumentParser(description="x64-update: Gestor Oficial de Actualizaciones de X64 LIOS")
    parser.add_argument("--check", action="store_true", help="Comprueba en segundo plano y actualiza el estado")
    parser.add_argument("--cli", action="store_true", help="Fuerza la ejecución en terminal/CLI interactivo")
    args, unknown = parser.parse_known_args()

    if args.check:
        run_background_check_and_save()
        return 0

    has_display = bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))

    if args.cli or not has_display:
        return run_cli_interactive()

    try:
        run_gui()
    except Exception as e:
        print(f"Error iniciando GUI PyQt6: {e}. Entrando a modo terminal...")
        return run_cli_interactive()

if __name__ == "__main__":
    sys.exit(main() or 0)
