#!/bin/bash
# DeckZap by NerdZap - SteamOS Web App Generator
# youtube.com/nerdzap - nerdzap.com
#
# MIT License
# Copyright (c) 2026 NerdZap
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# ==========================================
# --- COLOURS ---
# ==========================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

# ==========================================
# --- STATE MANAGEMENT ---
# ==========================================
STATE_DIR="$HOME/.local/share/deckzap"
STATE_FILE="$STATE_DIR/state.log"
mkdir -p "$STATE_DIR"

# ==========================================
# --- ROUTER (Engine Core) ---
# ==========================================
APP_MODES=()
CUSTOM_NAMES=()
CUSTOM_URLS=()
RESET_MODE=false
FORCE_RESET_MODE=false
VERBOSE_MODE=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    --xbox|--xcloud) APP_MODES+=("xcloud"); shift ;;
    --geforcenow) APP_MODES+=("geforcenow"); shift ;;
    --netflix) APP_MODES+=("netflix"); shift ;;
    --youtube) APP_MODES+=("youtube"); shift ;;
    --disneyplus) APP_MODES+=("disneyplus"); shift ;;
    --primevideo) APP_MODES+=("primevideo"); shift ;;
    --twitch) APP_MODES+=("twitch"); shift ;;
    --plex) APP_MODES+=("plex"); shift ;;
    --hulu) APP_MODES+=("hulu"); shift ;;
    --crunchyroll) APP_MODES+=("crunchyroll"); shift ;;
    --appletvplus) APP_MODES+=("appletvplus"); shift ;;
    --boosteroid) APP_MODES+=("boosteroid"); shift ;;
    --betterxcloud) APP_MODES+=("betterxcloud"); shift ;;
    --amazonluna) APP_MODES+=("amazonluna"); shift ;;
    --custom-name) CUSTOM_NAMES+=("$2"); shift 2 ;;
    --custom-url) CUSTOM_URLS+=("$2"); shift 2 ;;
    --reset) RESET_MODE=true; shift ;;
    --force-reset) FORCE_RESET_MODE=true; shift ;;
    --verbose) VERBOSE_MODE=true; shift ;;
    *) shift ;;
  esac
done

for i in "${!CUSTOM_NAMES[@]}"; do
  if [ -n "${CUSTOM_NAMES[$i]}" ] && [ -n "${CUSTOM_URLS[$i]}" ]; then
    APP_MODES+=("custom_$i")
  fi
done

# ==========================================
# --- CONFLICT MITIGATION ---
# (Removed to prevent false positive locks with Decky plugins)
# ==========================================

# ==========================================
# --- SYNC ENGINE ---
# ==========================================
define_python_atomic_sync() {
cat << 'EOF' > /tmp/deckzap_sync.py
import urllib.request, json, socket, base64, os, sys, time, binascii, shutil

# --- STEAM API CONFIGURATION ---
API_ADD_SHORTCUT = "AddShortcut"
API_SET_SHORTCUT_NAME = "SetShortcutName"
API_SET_SHORTCUT_EXE = "SetShortcutExe"
API_SET_SHORTCUT_START_DIR = "SetShortcutStartDir"
API_SET_APP_LAUNCH_OPTIONS = "SetAppLaunchOptions"
API_SET_SHORTCUT_ICON = "SetShortcutIcon"
API_SET_CUSTOM_ARTWORK = "SetCustomArtworkForApp"
API_REMOVE_SHORTCUT = "RemoveShortcut"

API_GET_COLLECTION_ID = "GetCollectionIDByUserTag"
API_GET_COLLECTION = "GetCollection"
API_NEW_UNSAVED_COLLECTION = "NewUnsavedCollection"
# -------------------------------

def get_appid(exe, name):
    crc = binascii.crc32((exe + name).encode('utf-8')) & 0xFFFFFFFF
    return (crc | 0x80000000) & 0xFFFFFFFF

def wait_for_ui(ports=[8080, 8081], timeout=60):
    start = time.time()
    while time.time() - start < timeout:
        for port in ports:
            try:
                req = urllib.request.Request(f"http://localhost:{port}/json")
                with urllib.request.urlopen(req, timeout=3) as res:
                    if res.status == 200:
                        targets = json.loads(res.read().decode())
                        ws_url = next((t["webSocketDebuggerUrl"] for t in targets if t.get("title") == "SharedJSContext"), None)
                        if ws_url: return ws_url
            except: pass
        time.sleep(1)
    return None

def recv_ws_message(sock):
    while True:
        header = b""
        while len(header) < 2:
            chunk = sock.recv(2 - len(header))
            if not chunk: return ""
            header += chunk
        opcode = header[0] & 0x0F
        payload_len = header[1] & 0x7F
        if payload_len == 126:
            ext = b""
            while len(ext) < 2: ext += sock.recv(2 - len(ext))
            payload_len = int.from_bytes(ext, 'big')
        elif payload_len == 127:
            ext = b""
            while len(ext) < 8: ext += sock.recv(8 - len(ext))
            payload_len = int.from_bytes(ext, 'big')
        data = b""
        while len(data) < payload_len:
            chunk = sock.recv(payload_len - len(data))
            if not chunk: break
            data += chunk
        if opcode == 0x9:
            sock.send(bytearray([0x8A, 0x00]))
            continue
        if opcode == 0x8: return ""
        if opcode == 0x1: return data.decode('utf-8', errors='ignore')
        continue

def execute_atomic_sync(mode, app_name, launch_opts, art_dir, art_banner, art_capsule, art_icon, art_logo):
    ws_url = wait_for_ui()
    if not ws_url: return "FAIL_NO_DEBUGGER_PORT"
    exe_path, start_dir = "/usr/bin/flatpak", "/usr/bin"
    icon_path = os.path.join(art_dir, art_icon)
    safe_app_name = app_name.replace('\\', '\\\\').replace('"', '\\"')
    safe_launch_opts = launch_opts.replace('\\', '\\\\').replace('"', '\\"')
    safe_icon_path = icon_path.replace('\\', '\\\\').replace('"', '\\"')
    
    def get_b64(file_name):
        if not file_name: return ""
        p = os.path.join(art_dir, file_name)
        if os.path.isfile(p):
            with open(p, "rb") as f:
                return base64.b64encode(f.read()).decode('utf-8')
        return ""
        
    b64_banner = get_b64(art_banner)
    b64_capsule = get_b64(art_capsule)
    b64_logo = get_b64(art_logo)
    
    js_payload = f"""
    (async () => {{
        try {{
            let retries = 20;
            const getStore = () => window.g_CollectionStore || window.collectionStore;
            const getAppStore = () => window.g_AppStore || window.appStore;
            const getApps = () => window.SteamClient?.Apps;
            while ((!getStore() || !getAppStore() || !getApps()) && retries > 0) {{
                await new Promise(r => setTimeout(r, 500));
                retries--;
            }}
            const cStore = getStore();
            const aStore = getAppStore();
            const cApps = getApps();
            if (!cStore || !aStore || !cApps) return "FAIL_NO_API_HYDRATION";

            if ("{mode}" === "install") {{
                const appId = await cApps.{API_ADD_SHORTCUT}("{safe_app_name}", "{exe_path}", "{start_dir}", "{safe_launch_opts}");
                await cApps.{API_SET_SHORTCUT_NAME}(appId, "{safe_app_name}");
                await cApps.{API_SET_SHORTCUT_EXE}(appId, "{exe_path}");
                await cApps.{API_SET_SHORTCUT_START_DIR}(appId, "{start_dir}");
                await cApps.{API_SET_APP_LAUNCH_OPTIONS}(appId, "{safe_launch_opts}");
                await cApps.{API_SET_SHORTCUT_ICON}(appId, "{safe_icon_path}");
                
                const b64Banner = "{b64_banner}";
                const b64Capsule = "{b64_capsule}";
                const b64Logo = "{b64_logo}";
                
                if (b64Capsule && typeof cApps.{API_SET_CUSTOM_ARTWORK} === 'function') {{
                    await cApps.{API_SET_CUSTOM_ARTWORK}(appId, b64Capsule, "jpg", 0);
                }}
                if (b64Banner && typeof cApps.{API_SET_CUSTOM_ARTWORK} === 'function') {{
                    await cApps.{API_SET_CUSTOM_ARTWORK}(appId, b64Banner, "jpg", 1);
                    await cApps.{API_SET_CUSTOM_ARTWORK}(appId, b64Banner, "jpg", 3);
                }}
                if (b64Logo && typeof cApps.{API_SET_CUSTOM_ARTWORK} === 'function') {{
                    await cApps.{API_SET_CUSTOM_ARTWORK}(appId, b64Logo, "png", 2);
                }}
                
                const tag = "DeckZap";
                let col = null;
                
                if (typeof cStore.{API_GET_COLLECTION_ID} === 'function') {{
                    const existingId = cStore.{API_GET_COLLECTION_ID}(tag);
                    if (existingId) col = cStore.{API_GET_COLLECTION}(existingId);
                }}
                
                if (!col && typeof cStore.{API_NEW_UNSAVED_COLLECTION} === 'function') {{
                    col = cStore.{API_NEW_UNSAVED_COLLECTION}(tag, undefined, []);
                }}
                
                if (col) {{
                    if (col.Save) await col.Save();
                    if (col.m_setApps && !col.m_setApps.has(appId)) {{
                        col.m_setApps.add(appId);
                        if (col.m_setAddedManually) col.m_setAddedManually.add(appId);
                        if (col.Save) await col.Save();
                    }}
                    return "SUCCESS_INSTALLED";
                }}
                return "FAIL_COLLECTION_FINAL";
            }} else {{
                if ("{safe_app_name}" === "GlobalSweep") {{
                    let removed = false;
                    const tag = "DeckZap";
                    if (typeof cStore.{API_GET_COLLECTION_ID} === 'function') {{
                        const existingId = cStore.{API_GET_COLLECTION_ID}(tag);
                        if (existingId) {{
                            const col = cStore.{API_GET_COLLECTION}(existingId);
                            if (col && col.m_setApps) {{
                                const appIds = Array.from(col.m_setApps);
                                for (const id of appIds) {{
                                    if (typeof cApps.{API_REMOVE_SHORTCUT} === 'function') {{
                                        await cApps.{API_REMOVE_SHORTCUT}(id);
                                        removed = true;
                                    }}
                                }}
                            }}
                        }}
                    }}
                    return removed ? "SUCCESS_REMOVED" : "SUCCESS_NOT_FOUND";
                }} else {{
                    const apps = Array.from(aStore.m_mapApps.values());
                    const target = apps.find(s => (s.m_strName === "{safe_app_name}" || s.display_name === "{safe_app_name}"));
                    if (target) {{
                        const id = target.unAppID || target.appid;
                        if (typeof cApps.{API_REMOVE_SHORTCUT} === 'function') {{
                            await cApps.{API_REMOVE_SHORTCUT}(id);
                        }}
                        return "SUCCESS_REMOVED";
                    }}
                    return "SUCCESS_NOT_FOUND";
                }}
            }}
        }} catch (e) {{ return "ERROR_" + e.message; }}
    }})();
    """
    try:
        from urllib.parse import urlparse
        p = urlparse(ws_url)
        sock = socket.create_connection((p.hostname, p.port), timeout=10)
        key = base64.b64encode(os.urandom(16)).decode()
        handshake = f"GET {p.path} HTTP/1.1\r\nHost: {p.hostname}:{p.port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
        sock.send(handshake.encode())
        resp = b""
        while b"\r\n\r\n" not in resp and len(resp) < 8192: resp += sock.recv(1024)
        sock.settimeout(45)
        
        payload = json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {"expression": js_payload, "awaitPromise": True, "returnByValue": True}})
        msg = payload.encode('utf-8')
        frame = bytearray([0x81])
        msg_len = len(msg)
        
        if msg_len <= 125:
            frame.append(msg_len | 0x80)
        elif msg_len <= 65535:
            frame.append(126 | 0x80)
            frame.extend(msg_len.to_bytes(2, 'big'))
        else:
            frame.append(127 | 0x80)
            frame.extend(msg_len.to_bytes(8, 'big'))
            
        mask = os.urandom(4)
        frame.extend(mask)
        frame.extend(bytearray(b ^ mask[i % 4] for i, b in enumerate(msg)))
        sock.send(frame)
        
        result = recv_ws_message(sock)
        sock.close()
        
        steam_userdata = os.path.expanduser("~/.local/share/Steam/userdata")
        appid_unsigned = get_appid('"' + exe_path + '"', app_name)
        if os.path.exists(steam_userdata):
            for user_id in os.listdir(steam_userdata):
                if user_id in ["0", "anonymous"]: continue
                grid_dir = os.path.join(steam_userdata, user_id, "config", "grid")
                os.makedirs(grid_dir, exist_ok=True)
                for src, dest in [(art_banner, f"{appid_unsigned}_hero.jpg"), (art_capsule, f"{appid_unsigned}p.jpg"), (art_icon, f"{appid_unsigned}_icon.png"), (art_logo, f"{appid_unsigned}_logo.png")]:
                    if not src: continue
                    p = os.path.join(grid_dir, dest)
                    src_path = os.path.join(art_dir, src)
                    if mode == "install" and os.path.isfile(src_path): shutil.copy(src_path, p)
        return result
    except Exception as e: return f"FAIL_SOCKET_ERROR_{e}"

if __name__ == "__main__":
    print(execute_atomic_sync(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7], sys.argv[8]))
EOF
}

# ==========================================
# --- CEF DEBUGGER CHECK ---
# ==========================================
check_cef_debugger() {
  echo -n "-> [CHECKPOINT] Checking Steam CEF Remote Debugger... "

  if timeout 8 curl -s http://localhost:8080/json >/dev/null 2>&1 || \
     timeout 8 curl -s http://localhost:8081/json >/dev/null 2>&1; then
    echo -e "${GREEN}[READY]${NC}"
    return 0
  fi

  echo -e "${RED}[NOT ENABLED]${NC}"

  CEF_FILE="$HOME/.steam/steam/.cef-enable-remote-debugging"

  if [ ! -f "$CEF_FILE" ]; then
    echo -n "-> Adjusting background settings... "
    mkdir -p "$HOME/.steam/steam"
    touch "$CEF_FILE"
    echo -e "${GREEN}[DONE]${NC}"
  else
    echo "-> Background settings are already in place (but Steam isn't responding yet)"
  fi

  echo -e "\n${YELLOW}One-time setup required:${NC}\n"

  if [ "$RESET_MODE" = true ] || [ "$FORCE_RESET_MODE" = true ]; then
    echo -e "DeckZap needs to talk to Steam to remove your apps."
    echo -e "However, the developer connection is currently closed.\n"
  else
    echo -e "DeckZap has updated your background settings, but Steam needs to be restarted to recognise the change.\n"
  fi

  echo -e "${CYAN}Please do this now:${NC}"
  echo -e "1. Restart the Steam Client (Exit from the taskbar icon at the bottom right, then open it again)."
  echo -e "2. Run your DeckZap command again.\n"

  echo -e "${YELLOW}Tip:${NC} If a simple Steam restart doesn't work, a full system reboot usually resolves the issue.\n"
  exit 1
}

# ==========================================
# --- LOGIC EXECUTION ---
# ==========================================
if ! pgrep -x "steam" > /dev/null; then
  echo -e "${RED}[ERROR] Steam is not running. Please open Steam and try again.${NC}"; exit 1
fi
check_cef_debugger
define_python_atomic_sync

# --- LEDGER RESET PHASE (Primary) ---
if [ "$RESET_MODE" = true ]; then
  echo -e "${YELLOW}⚡ Performing Reset...${NC}"
  
  if [ ! -f "$STATE_FILE" ]; then
    echo -e "${RED}[ERROR] Install log not found.${NC}"
    echo "To forcibly delete all apps in the DeckZap collection, please run the script again with the --force-reset flag."
    exit 1
  fi
  
  if grep -q "EDGE_PRE_EXISTED=false" "$STATE_FILE" 2>/dev/null; then
    echo -e "-> ${CYAN}[CLEANUP]${NC} Removing Microsoft Edge (Previously Installed by DeckZap)..."
    flatpak uninstall -y com.microsoft.Edge >/dev/null 2>&1
  fi
  
  # Extract exact app names from the ledger and remove them one by one
  grep "APP_NAME_RECORD=" "$STATE_FILE" | cut -d'"' -f2 | sort -u | while read -r LOGGED_APP_NAME; do
    if [ -n "$LOGGED_APP_NAME" ]; then
      echo -n "-> [CHECKPOINT] Removing '$LOGGED_APP_NAME'... "
      SYNC_RESULT=$(python3 /tmp/deckzap_sync.py "reset" "$LOGGED_APP_NAME" "" "" "" "" "" "")
      [ "$VERBOSE_MODE" = true ] && echo -e "\n${YELLOW}[VERBOSE] Steam Reply: $SYNC_RESULT${NC}"
      
      if [[ "$SYNC_RESULT" == *"\"SUCCESS_REMOVED\""* || "$SYNC_RESULT" == *"\"SUCCESS_NOT_FOUND\""* ]]; then
        echo -e "${GREEN}[OK]${NC}"
      else
        echo -e "${RED}[FAIL]${NC}"
      fi
    fi
  done
  
  if grep -q "CEF_FIX_APPLIED_BY_DECKZAP=true" "$STATE_FILE" 2>/dev/null; then
    echo -n "-> [CLEANUP] Reverting Steam developer settings... "
    rm -f "$HOME/.steam/steam/.cef-enable-remote-debugging"
    echo -e "${GREEN}[OK]${NC}"
  fi
  
  rm -f "$STATE_FILE"
  echo -e "${GREEN}✓ Reset Complete.${NC}"
  exit 0
fi

# ==========================================
# --- GLOBAL SWEEP PHASE ---
# ==========================================
if [ "$FORCE_RESET_MODE" = true ]; then
  echo -e "${YELLOW}⚡ Performing Forced Reset (Global Sweep)...${NC}"
  
  if grep -q "EDGE_PRE_EXISTED=false" "$STATE_FILE" 2>/dev/null; then
    echo -e "-> ${CYAN}[CLEANUP]${NC} Removing Microsoft Edge (Installed by DeckZap)..."
    flatpak uninstall -y com.microsoft.Edge >/dev/null 2>&1
  fi
  
  echo -n "-> [CHECKPOINT] Sweeping and removing all DeckZap shortcuts... "
  SYNC_RESULT=$(python3 /tmp/deckzap_sync.py "reset" "GlobalSweep" "" "" "" "" "" "")
  [ "$VERBOSE_MODE" = true ] && echo -e "\n${YELLOW}[VERBOSE] Steam Reply: $SYNC_RESULT${NC}"
  
  if [[ "$SYNC_RESULT" == *"\"SUCCESS_REMOVED\""* || "$SYNC_RESULT" == *"\"SUCCESS_NOT_FOUND\""* ]]; then
    if grep -q "CEF_FIX_APPLIED_BY_DECKZAP=true" "$STATE_FILE" 2>/dev/null; then
      echo -n "-> [CLEANUP] Reverting Steam developer settings... "
      rm -f "$HOME/.steam/steam/.cef-enable-remote-debugging"
      echo -e "${GREEN}[OK]${NC}"
    fi
    
    rm -rf "$STATE_DIR/artwork" 
    rm -f "$STATE_FILE"
    echo -e "${GREEN}[OK]${NC}"; echo -e "${GREEN}✓ Global Sweep Complete.${NC}"
  else
    echo -e "${RED}[FAIL]${NC}"; [ "$VERBOSE_MODE" = false ] && echo -e "${YELLOW}[DEBUG] Steam Reply: $SYNC_RESULT${NC}"; exit 1
  fi
  exit 0
fi
# ==========================================
#--- INSTALL QUEUE PHASE ---
# ==========================================

if [ ${#APP_MODES[@]} -gt 0 ]; then

  # Ensure Edge is installed before iterating
  if flatpak list | grep -q com.microsoft.Edge; then
    [ ! -f "$STATE_FILE" ] || grep -q "EDGE_PRE_EXISTED" "$STATE_FILE" || echo "EDGE_PRE_EXISTED=true" >> "$STATE_FILE"
  else
    echo -n "-> [CHECKPOINT] Installing Microsoft Edge (Recommended for controller compatibility)... "
    
    # Ensure the user-level repository exists before attempting install
    flatpak --user remote-add --if-not-exists --noninteractive flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1
    
    if ! flatpak install --user -y --noninteractive flathub com.microsoft.Edge >/dev/null; then
      echo -e "\n${RED}[FAIL] Microsoft Edge failed to install.${NC}"
      echo -e "${YELLOW}Your system may be downloading background updates, or you may be offline.${NC}"
      echo -e "Please wait a minute and try again, or manually install Microsoft Edge from the Discover store, then run DeckZap again."
      exit 1
    fi
    echo "EDGE_PRE_EXISTED=false" >> "$STATE_FILE"
    echo -e "${GREEN}[OK]${NC}"
  fi
  flatpak --user override --filesystem=/run/udev:ro com.microsoft.Edge >/dev/null 2>&1

  # Loop through all requested applications
  for APP_MODE in "${APP_MODES[@]}"; do
  
    # Shared Variables
    ART_DIR="$STATE_DIR/artwork/$APP_MODE"
    BASE_URL="https://nerdzap.com/tools/deckzap/artwork/$APP_MODE"
    BASE_LAUNCH_OPTS="run --branch=stable --arch=x86_64 --command=/app/bin/edge --file-forwarding com.microsoft.Edge @@u @@ --window-size=1024,640 --force-device-scale-factor=1.25 --device-scale-factor=1.25 --kiosk"

    # App Definitions
    if [ "$APP_MODE" = "xcloud" ]; then
      APP_NAME="Xbox Cloud Gaming (Beta)"
      APP_URL="https://www.xbox.com/play"
      ART_BANNER="Xbox_Cloud_Gaming_Banner.jpg"
      ART_CAPSULE="Xbox_Cloud_Gaming_Capsule.jpg"
      ART_ICON="Xbox_Cloud_Gaming_Icon.png"
      ART_LOGO="Xbox_Cloud_Gaming_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "geforcenow" ]; then
      APP_NAME="GeForce Now"
      APP_URL="https://play.geforcenow.com"
      ART_BANNER="GeForce_Now_Banner.jpg"
      ART_CAPSULE="GeForce_Now_Capsule.jpg"
      ART_ICON="GeForce_Now_Icon.png"
      ART_LOGO="GeForce_Now_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "netflix" ]; then
      APP_NAME="Netflix"
      APP_URL="https://www.netflix.com"
      ART_BANNER="Netflix_Banner.jpg"
      ART_CAPSULE="Netflix_Capsule.jpg"
      ART_ICON="Netflix_Icon.png"
      ART_LOGO="Netflix_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "youtube" ]; then
      APP_NAME="YouTube"
      APP_URL="https://www.youtube.com/tv"
      ART_BANNER="YouTube_Banner.jpg"
      ART_CAPSULE="YouTube_Capsule.jpg"
      ART_ICON="YouTube_Icon.png"
      ART_LOGO="YouTube_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "disneyplus" ]; then
      APP_NAME="Disney+"
      APP_URL="https://www.disneyplus.com"
      ART_BANNER="Disney_Plus_Banner.jpg"
      ART_CAPSULE="Disney_Plus_Capsule.jpg"
      ART_ICON="Disney_Plus_Icon.png" 
      ART_LOGO="Disney_Plus_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "primevideo" ]; then
      APP_NAME="Prime Video"
      APP_URL="https://www.primevideo.com"
      ART_BANNER="Amazon_Prime_Video_Banner.jpg"
      ART_CAPSULE="Amazon_Prime_Video_Capsule.jpg"
      ART_ICON="Amazon_Prime_Video_Icon.png"
      ART_LOGO="Amazon_Prime_Video_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "twitch" ]; then
      APP_NAME="Twitch"
      APP_URL="https://www.twitch.tv"
      ART_BANNER="Twitch_Banner.jpg"
      ART_CAPSULE="Twitch_Capsule.jpg"
      ART_ICON="Twitch_Icon.png"
      ART_LOGO="Twitch_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "plex" ]; then
      APP_NAME="Plex"
      APP_URL="https://app.plex.tv/desktop"
      ART_BANNER="Plex_Banner.jpg"
      ART_CAPSULE="Plex_Capsule.jpg"
      ART_ICON="Plex_Icon.png"
      ART_LOGO="Plex_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "hulu" ]; then
      APP_NAME="Hulu"
      APP_URL="https://www.hulu.com"
      ART_BANNER="Hulu_Banner.jpg"
      ART_CAPSULE="Hulu_Capsule.jpg"
      ART_ICON="Hulu_Icon.png"
      ART_LOGO="Hulu_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "crunchyroll" ]; then
      APP_NAME="Crunchyroll"
      APP_URL="https://www.crunchyroll.com"
      ART_BANNER="Crunchyroll_Banner.jpg"
      ART_CAPSULE="Crunchyroll_Capsule.jpg"
      ART_ICON="Crunchyroll_Icon.png"
      ART_LOGO="Crunchyroll_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "appletvplus" ]; then
      APP_NAME="Apple TV+"
      APP_URL="https://tv.apple.com"
      ART_BANNER="Apple_TV_Banner.jpg"
      ART_CAPSULE="Apple_TV_Capsule.jpg"
      ART_ICON="Apple_TV_Icon.png" 
      ART_LOGO="Apple_TV_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "boosteroid" ]; then
      APP_NAME="Boosteroid"
      APP_URL="https://cloud.boosteroid.com"
      ART_BANNER="Boosteroid_Banner.jpg"
      ART_CAPSULE="Boosteroid_Capsule.jpg"
      ART_ICON="Boosteroid_Icon.png" 
      ART_LOGO="Boosteroid_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "betterxcloud" ]; then
      APP_NAME="Better xCloud"
      APP_URL="https://better-xcloud.github.io"
      ART_BANNER="Better_xCloud_Banner.jpg"
      ART_CAPSULE="Better_xCloud_Capsule.jpg"
      ART_ICON="Better_xCloud_Icon.png"
      ART_LOGO="Better_xCloud_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
    elif [ "$APP_MODE" = "amazonluna" ]; then
      APP_NAME="Amazon Luna"
      APP_URL="https://luna.amazon.com"
      ART_BANNER="Amazon_Luna_Banner.jpg"
      ART_CAPSULE="Amazon_Luna_Capsule.jpg"
      ART_ICON="Amazon_Luna_Icon.png"
      ART_LOGO="Amazon_Luna_Logo.png"
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS --user-agent=\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36\" --app=\"$APP_URL\""
    elif [[ "$APP_MODE" == custom_* ]]; then
      idx="${APP_MODE#custom_}"
      APP_NAME="${CUSTOM_NAMES[$idx]}"
      APP_URL="${CUSTOM_URLS[$idx]}"
      ART_BANNER=""
      ART_CAPSULE=""
      ART_ICON="Custom_Icon.png"
      ART_LOGO=""
      LAUNCH_OPTS="$BASE_LAUNCH_OPTS \"$APP_URL\""
      # Override BASE_URL for custom icon fetch to prevent 404s on dynamic paths
      BASE_URL="https://nerdzap.com/tools/deckzap/artwork/custom"
    fi

    # ==========================================
    # --- DUPLICATE PREVENTION ---
    # ==========================================
    if [ -f "$STATE_FILE" ] && grep -q "APP_NAME_RECORD=\"$APP_NAME\"" "$STATE_FILE"; then
      echo -e "\n${YELLOW}⚡ Skipping: $APP_NAME (Already present in ledger)${NC}"
      continue
    fi

    echo -e "\n${CYAN}⚡ Starting DeckZap Engine for: $APP_NAME${NC}"
    
    echo -n "-> [CHECKPOINT] Downloading artwork... "
    mkdir -p "$ART_DIR"
    for f in "$ART_BANNER" "$ART_CAPSULE" "$ART_ICON" "$ART_LOGO"; do 
      if [ -n "$f" ]; then
        curl -sL "$BASE_URL/$f" -o "$ART_DIR/$f"
      fi
    done
    echo -e "${GREEN}[OK]${NC}"
    
    echo -n "-> [CHECKPOINT] Injecting Steam payload... "
    SYNC_RESULT=$(python3 /tmp/deckzap_sync.py "install" "$APP_NAME" "$LAUNCH_OPTS" "$ART_DIR" "$ART_BANNER" "$ART_CAPSULE" "$ART_ICON" "$ART_LOGO")
    [ "$VERBOSE_MODE" = true ] && echo -e "\n${YELLOW}[VERBOSE] Steam Reply: $SYNC_RESULT${NC}"
    
    if [[ "$SYNC_RESULT" == *"\"SUCCESS_INSTALLED\""* ]]; then
      echo "APP_INSTALLED_$APP_MODE=true" >> "$STATE_FILE"
      echo "APP_NAME_RECORD=\"$APP_NAME\"" >> "$STATE_FILE"
      echo -e "${GREEN}✓ '$APP_NAME' installed successfully.${NC}"
    else
      echo -e "${RED}[FAIL]${NC}"; [ "$VERBOSE_MODE" = false ] && echo -e "${YELLOW}[DEBUG] Steam Reply: $SYNC_RESULT${NC}";
    fi
  done

  # --- POST-INSTALLATION INSTRUCTIONS ---
  echo -e "\n${CYAN}🎉 DeckZap Queue Complete!${NC}"
  echo -e "${GREEN}DeckZap is free and built in my spare time. If it saved you some hassle, a beer helps keep it updated:${NC}"
  echo -e "${CYAN}https://buymeacoffee.com/nerdzap${NC}\n"
  echo -e "${YELLOW}Important Note on Controllers:${NC}"
  echo -e "The script has enabled hardware access, but you must manually select a controller template in Gaming Mode. I recommend using the 'Gamepad with Mouse Trackpad' (or a custom configuration) for the best experience."
  echo -e ""
  echo -e "${YELLOW}Need to start over?${NC}"
  echo -e "You can cleanly remove all DeckZap apps at any time by running this command:"
  echo -e "${CYAN}curl -sL https://nerdzap.com/tools/deckzap/scripts/deckzap.sh | bash -s -- --reset${NC}\n"
fi