tell me the current API commands in here please

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Ultimate Games & YouTube App Revamped</title>
  
  <!-- CodeMirror CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.12/codemirror.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.12/theme/monokai.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.12/addon/hint/show-hint.min.css" />
  
  <!-- Styles -->
  <style>
    /* Reset & Basic */
    * {
      box-sizing: border-box;
    }
    html, body {
      margin: 0; padding: 0; height: 100%;
      font-family: system-ui, -apple-system, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
      background-color: var(--bg);
      color: var(--fg);
      transition: background-color 0.5s ease, color 0.5s ease;
      overflow-x: hidden;
    }

    :root {
      --bg: #d3d3d3;
      --fg: #222;
      --accent: #555;
      --accent-hover: #777;
      --box-bg: white;
      --box-shadow: rgba(0,0,0,0.2);
      --error-color: #d9534f;
      --success-color: #27ae60;
      --toast-bg: #333;
      --toast-fg: white;

      --button-bg: #444;
      --button-hover-bg: #666;
      --button-fg: white;

      --input-bg: #f0f0f0;
      --input-fg: #333;
      --input-border: #ccc;
    }

    .dark-mode {
      --bg: #171717;
      --fg: #eaeaea;
      --accent: #888;
      --accent-hover: #aaa;
      --box-bg: #2e2e2e;
      --box-shadow: rgba(0,0,0,0.8);
      --error-color: #ff5c5c;
      --success-color: #42f584;
      --toast-bg: #222;
      --toast-fg: #eee;

      --button-bg: #666;
      --button-hover-bg: #888;
      --button-fg: white;

      --input-bg: #252525;
      --input-fg: #ddd;
      --input-border: #555;
    }

    /* Body classes */
    body.locked {
      overflow: hidden;
    }

    /* Particle canvas */
    #particles-js {
      position: fixed;
      top: 0; left: 0;
      width: 100vw; height: 100vh;
      z-index: -1;
      user-select:none;
    }

    /* Toasts */
    #toast-container {
      position: fixed;
      bottom: 90px;
      right: 20px;
      max-width: 320px;
      z-index: 12000;
      font-weight: 700;
      user-select:none;
    }
    .toast {
      background: var(--toast-bg);
      color: var(--toast-fg);
      padding: 14px 22px;
      margin-top: 10px;
      border-radius: 12px;
      box-shadow: 0 0 15px rgba(0,0,0,0.5);
      opacity: 0;
      transform: translateX(100%);
      transition: opacity 0.3s ease, transform 0.3s ease;
      cursor:pointer;
      user-select:none;
    }
    .toast.show {
      opacity: 1;
      transform: translateX(0);
    }

    /* Overlay & Lock Screen */
    #overlay {
      position: fixed;
      top:0; left:0;
      width: 100vw; height: 100vh;
      background: rgba(0,0,0,0.85);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 9999;
      transition: opacity 0.3s ease;
      user-select:none;
    }
    #overlay[aria-hidden='true'] {
      opacity: 0;
      pointer-events:none;
    }

    #passwordModal {
      background: var(--box-bg);
      border-radius: 12px;
      padding: 30px 25px;
      box-shadow: 0 0 40px var(--box-shadow);
      width: 320px;
      max-width: 90vw;
      text-align: center;
      user-select:none;
    }
    #passwordModal h2 {
      font-weight: 900;
      margin-bottom: 20px;
      color: var(--fg);
    }
    #passwordInput {
      font-size: 1.1rem;
      width: 100%;
      padding: 14px 10px;
      border-radius: 10px;
      border: 2px solid var(--input-border);
      background: var(--input-bg);
      color: var(--input-fg);
      user-select:text;
      transition: border-color 0.3s ease;
    }
    #passwordInput:focus {
      border-color: var(--accent);
      outline: none;
      box-shadow: 0 0 20px var(--accent);
    }
    #submitPassword {
      margin-top: 20px;
      padding: 14px 28px;
      font-weight: 700;
      font-size: 1.1rem;
      background: var(--button-bg);
      color: var(--button-fg);
      border:none;
      border-radius: 12px;
      cursor: pointer;
      user-select:none;
      transition: background-color 0.3s ease;
      width: 100%;
    }
    #submitPassword:hover:not(:disabled) {
      background: var(--button-hover-bg);
    }
    #submitPassword:disabled {
      background: #999;
      cursor: not-allowed;
    }
    #errorMessage {
      color: var(--error-color);
      font-weight: 700;
      min-height: 20px;
      margin-top: 14px;
      text-align: center;
    }

    /* Buttons */
    button, .game-link, #settingsBar button {
      background: var(--button-bg);
      border-radius: 10px;
      border: none;
      color: var(--button-fg);
      padding: 10px 20px;
      margin: 5px 8px;
      font-weight: 700;
      cursor: pointer;
      user-select:none;
      transition: background-color 0.3s ease;
      box-shadow: 0 1px 4px rgba(0,0,0,0.1);
      letter-spacing: 0.04em;
    }
    button:hover, .game-link:hover, #settingsBar button:hover {
      background: var(--button-hover-bg);
      box-shadow: 0 2px 15px rgba(0,0,0,0.3);
    }
    button:disabled, .game-link.disabled {
      cursor: not-allowed;
      opacity: 0.5;
      background:#888;
      box-shadow: none;
    }

    /* Layout Container */
    .container {
      max-width: 750px;
      margin: 30px auto 120px auto;
      padding: 28px 32px 36px 32px;
      border-radius: 14px;
      background: var(--box-bg);
      box-shadow: 0 6px 28px var(--box-shadow);
      transition: background-color 0.5s ease, color 0.5s ease;
      user-select:none;
    }
    .container h2 {
      font-weight: 900;
      font-size: 2.15rem;
      margin-bottom: 25px;
      user-select:none;
      color: var(--fg);
    }

    /* Settings Bar */
    #settingsBar {
      position: fixed;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      background: var(--button-bg);
      padding: 14px 22px;
      border-top-left-radius: 24px;
      border-top-right-radius: 24px;
      display: flex;
      gap: 18px;
      box-shadow: 0 -5px 20px var(--box-shadow);
      width: fit-content;
      z-index: 10000;
      user-select:none;
    }
    #settingsBar button {
      padding: 10px 18px;
      font-size: 1rem;
      min-width: 130px;
      user-select:none;
    }
    #settingsBar button:focus {
      outline: 3px solid var(--accent);
      outline-offset: 3px;
    }

    /* Settings UI panel */
    #settingsUI {
      display: none;
      position: fixed;
      bottom: 72px;
      left: 50%;
      transform: translateX(-50%);
      max-width: 720px;
      width: 95vw;
      max-height: 75vh;
      overflow-y: auto;
      padding: 28px 32px 32px 32px;
      border-radius: 18px 18px 0 0;
      background: var(--box-bg);
      box-shadow: 0 -8px 30px var(--box-shadow);
      z-index: 11000;
      color: var(--fg);
      user-select:none;
    }
    #settingsUI.active {
      display: block;
    }
    #settingsUI h3 {
      font-weight: 900;
      font-size: 1.9rem;
      margin-top: 0;
      margin-bottom: 22px;
      user-select:none;
    }
    #settingsUI h4 {
      font-weight: 700;
      font-size: 1.2rem;
      margin: 20px 0 10px 0;
      user-select:none;
    }
    #settingsUI label {
      display: flex;
      align-items: center;
      font-weight: 700;
      font-size: 1rem;
      margin-bottom: 16px;
      gap: 15px;
      cursor: pointer;
      user-select:none;
      flex-wrap: wrap;
    }
    #settingsUI input[type="checkbox"] {
      cursor: pointer;
      height: 22px;
      width: 22px;
      flex-shrink: 0;
    }
    #settingsUI select, #settingsUI input[type="number"] {
      padding: 7px 12px;
      font-size: 1rem;
      border-radius: 9px;
      border: 1.7px solid var(--input-border);
      background: var(--input-bg);
      color: var(--input-fg);
      cursor: pointer;
      min-width: 160px;
      user-select:none;
      transition: border-color 0.3s ease;
    }
    #settingsUI select:focus, #settingsUI input[type="number"]:focus {
      outline: none;
      border-color: var(--accent);
      box-shadow: 0 0 20px var(--accent);
    }

    /* Games list container */
    #glist1, #glist2 {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
      gap: 16px;
      max-height: 360px;
      overflow-y: auto;
      user-select:none;
    }
    /* Single game card */
    .game-link {
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      padding: 18px 14px;
      font-size: 1.12rem;
      font-weight: 700;
      background: var(--button-bg);
      border-radius: 18px;
      color: var(--button-fg);
      user-select:none;
      box-shadow: 0 3px 12px rgba(0,0,0,0.2);
      cursor: pointer;
      transition: box-shadow 0.3s ease, background-color 0.3s ease;
      flex-shrink: 0;
      height: 70px;
      /* For keyboard */
      outline-offset: 4px;
    }
    .game-link:focus {
      outline: 3px solid var(--accent);
      outline-offset: 4px;
      box-shadow: 0 0 14px var(--accent), 0 3px 20px rgba(0,0,0,0.35);
    }
    .game-link:hover {
      background-color: var(--button-hover-bg);
      box-shadow: 0 0 20px var(--accent-hover);
      color: var(--button-fg);
    }

    .game-link.favorite {
      background: gold;
      color: #444;
      font-weight: 900;
      box-shadow: 0 0 16px gold;
      border: 2px solid #daa520;
    }
    .game-link.disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    /* Search Bar For Games */
    input.search-bar {
      width: calc(100% - 32px);
      min-width: 280px;
      max-width: 440px;
      padding: 11px 16px;
      border-radius: 14px;
      border: 1.8px solid var(--input-border);
      font-size: 1.1rem;
      margin-bottom: 24px;
      user-select:text;
      color: var(--input-fg);
      background: var(--input-bg);
      transition: border-color 0.3s ease;
    }
    input.search-bar:focus {
      outline: none;
      border-color: var(--accent);
      box-shadow: 0 0 25px var(--accent);
    }

    .page-button {
      font-weight: 900;
      font-size: 1rem;
      margin: 18px auto 6px auto;
      display: block;
      width: 130px;
      border-radius: 18px;
      box-shadow: 0 4px 14px var(--box-shadow);
      user-select:none;
    }
    .page-button:hover {
      box-shadow: 0 0 24px var(--accent-hover);
    }
    .page-button:focus {
      outline: 3px solid var(--accent);
      outline-offset: 4px;
    }

    /* Confirmation Dialog */
    #confirmationDialog {
      position: fixed;
      top: 50%; left: 50%;
      transform: translate(-50%, -50%);
      background: var(--box-bg);
      color: var(--fg);
      padding: 32px 26px;
      border-radius: 18px;
      box-shadow: 0 0 40px var(--box-shadow);
      width: 350px;
      max-width: 90vw;
      display: none;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
      user-select:none;
      z-index: 12000;
    }
    #confirmationDialog.active {
      display: flex;
    }
    #confirmationDialog p {
      font-weight: 900;
      font-size: 1.4rem;
      margin-bottom: 28px;
    }
    #confirmationDialog button {
      user-select:none;
      border-radius: 14px;
      padding: 14px 24px;
      min-width: 100px;
      margin: 0 12px;
      font-weight: 700;
      font-size: 1.1rem;
      box-shadow: 0 0 25px var(--box-shadow);
    }

    /* Console UI */
    #consoleUI {
      display: none;
      max-width: 780px;
      margin: 28px auto 140px auto;
      padding: 28px 32px;
      border-radius: 24px;
      background: var(--box-bg);
      box-shadow: 0 5px 32px var(--box-shadow);
      font-family: monospace, monospace;
      color: limegreen;
      user-select:text;
      position: relative;
    }
    #consoleUI.active {
      display: block;
    }
    #consoleUI h3 {
      font-weight: 900;
      font-size: 2rem;
      margin-top: 0;
      margin-bottom: 24px;
      color: var(--fg);
    }

    /* Console tab bar */
    .code-tab-bar {
      display: flex;
      gap: 14px;
      margin-bottom: 20px;
      user-select:none;
    }
    .code-tab {
      background: var(--button-bg);
      color: var(--button-fg);
      padding: 8px 18px;
      border-radius: 18px;
      font-weight: 700;
      cursor: pointer;
      user-select:none;
      box-shadow: 0 4px 15px rgba(0,0,0,0.18);
      transition: background-color 0.3s ease;
      user-select:none;
      position: relative;
      outline-offset: 2px;
    }
    .code-tab.active {
      background: var(--button-hover-bg);
      box-shadow: 0 0 30px var(--accent);
      user-select:none;
    }
    .code-tab:focus {
      outline: 3px solid var(--accent);
      outline-offset: 6px;
    }
    .code-tab .close-tab {
      position: absolute;
      top: 6px;
      right: 8px;
      font-weight: 900;
      font-size: 16px;
      cursor: pointer;
      background: #444;
      width: 22px;
      height: 22px;
      border-radius: 50%;
      line-height: 22px;
      text-align: center;
      color: var(--button-fg);
      transition: background-color 0.3s ease;
      user-select:none;
    }
    .code-tab .close-tab:hover {
      background: #666;
    }
    #newCodeButton {
      font-size: 1.7rem;
      width: 42px;
      height: 42px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    /* Console textarea */
    #consoleInput {
      resize: vertical;
      width: 100%;
      min-height: 180px;
      font-family: monospace, monospace;
      font-size: 16px;
      font-weight: 700;
      padding: 16px 18px;
      border-radius: 16px;
      border: 2px solid var(--input-border);
      background: #111;
      color: limegreen;
      box-shadow: inset 2px 2px 12px #0f0;
      user-select:text;
      transition: border-color 0.3s ease;
      white-space: pre-wrap;
      overflow-wrap: break-word;
    }
    #consoleInput:focus {
      outline: none;
      border-color: limegreen;
      box-shadow: 0 0 28px limegreen;
    }

    /* Console control buttons */
    #consoleUI > button {
      margin-top: 16px;
      margin-right: 12px;
      padding: 12px 20px;
      border-radius: 16px;
      font-weight: 900;
      font-size: 1rem;
      border: none;
      cursor: pointer;
      background: var(--button-bg);
      color: var(--button-fg);
      user-select:none;
      transition: background-color 0.3s ease;
    }
    #consoleUI > button:hover {
      background: var(--button-hover-bg);
      box-shadow: 0 0 18px var(--accent);
    }

    /* Console output */
    #console-output {
      margin-top: 20px;
      background: #000;
      color: limegreen;
      border-radius: 16px;
      padding: 22px;
      height: 260px;
      font-family: monospace, monospace;
      white-space: pre-wrap;
      overflow-y: auto;
      box-shadow: inset 0 0 30px #0f0;
      user-select:text;
      border: 2px solid var(--input-border);
    }

    /* YouTube Embed UI */
    #youtubeEmbedUI {
      position: fixed;
      top: 110px;
      left: 50%;
      transform: translateX(-50%);
      max-width: 1400px;
      width: 96vw;
      background: var(--box-bg);
      border-radius: 22px;
      box-shadow: 0 0 50px var(--box-shadow);
      padding: 32px 38px 38px 38px;
      color: var(--fg);
      z-index: 11000;
      display: none;
      user-select:none;
      overflow: visible;
    }
    #youtubeEmbedUI.active {
      display: block;
    }
    #youtubeEmbedUI h3 {
      font-weight: 900;
      font-size: 2.3rem;
      margin-top: 0;
      margin-bottom: 26px;
      user-select:none;
    }
    #youtubeURL {
      font-size: 1.25rem;
      width: 70%;
      padding: 14px 20px;
      border-radius: 16px;
      border: 2.2px solid var(--input-border);
      background: var(--input-bg);
      color: var(--input-fg);
      user-select:text;
      transition: border-color 0.3s ease;
      margin-bottom: 20px;
      user-select:text;
    }
    #youtubeURL:focus {
      outline: none;
      border-color: var(--accent);
      box-shadow: 0 0 30px var(--accent);
    }
    #loadVideoButton, #changeVideoButton {
      margin-left: 18px;
      background: var(--button-bg);
      color: var(--button-fg);
      padding: 14px 28px;
      border-radius: 14px;
      font-weight: 900;
      font-size: 1rem;
      box-shadow: 0 2px 20px rgba(0,0,0,0.35);
      cursor: pointer;
      user-select:none;
      transition: background-color 0.3s ease;
    }
    #loadVideoButton:hover, #changeVideoButton:hover {
      background: var(--button-hover-bg);
    }
    #loadVideoButton:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      box-shadow: none;
    }
    #changeVideoButton {
      display: none;
    }

    /* Video container */
    #video-container {
      width: 100%;
      aspect-ratio: 16 / 9;
      position: relative;
      border-radius: 22px;
      overflow: hidden;
      background: black;
      user-select:none;
      box-shadow: 0 0 30px #000a inset;
    }
    #video-container iframe {
      position: absolute;
      top: 0; left: 0;
      width: 100%;
      height: 100%;
      border-radius: 22px;
      pointer-events: auto;
    }

    /* YouTube Player Controls Bar */
    #ytControlsWrapper {
      margin-top: 26px;
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 16px;
      flex-wrap: nowrap;
      user-select:none;
      position: relative;
    }

    #ytControlsNavBtnPrev, #ytControlsNavBtnNext {
      border: none;
      border-radius: 14px;
      background: var(--button-bg);
      color: var(--button-fg);
      font-size: 2rem;
      cursor: pointer;
      user-select:none;
      padding: 4px 14px;
      font-weight: 900;
      flex-shrink: 0;
      box-shadow: 0 3px 20px rgba(0,0,0,0.3);
      transition: background-color 0.3s ease;
    }
    #ytControlsNavBtnPrev:disabled, #ytControlsNavBtnNext:disabled {
      opacity: 0.35;
      cursor: default;
      box-shadow: none;
    }
    #ytControlsNavBtnPrev:hover:not(:disabled), #ytControlsNavBtnNext:hover:not(:disabled) {
      background: var(--button-hover-bg);
    }
    #ytControlsNavBtnPrev:focus, #ytControlsNavBtnNext:focus {
      outline: 3px solid var(--accent);
      outline-offset: 3px;
    }

    /* Player control buttons container */
    #ytControlButtons {
      display: flex;
      align-items: center;
      gap: 16px;
      overflow-x: auto;
      flex-shrink: 1;
      max-width: 80vw;
      padding-bottom: 4px;
      scroll-behavior: smooth;
      user-select:none;
    }
    #ytControlButtons::-webkit-scrollbar {
      height: 8px;
    }
    #ytControlButtons::-webkit-scrollbar-thumb {
      background: var(--accent);
      border-radius: 14px;
      cursor: pointer;
    }
    #ytControlButtons button, #ytControlButtons select, #ytControlButtons input[type=checkbox] {
      min-width: 50px;
      padding: 8px 12px;
      border-radius: 14px;
      border: none;
      font-weight: 700;
      user-select:none;
      white-space: nowrap;
      color: var(--button-fg);
      background: var(--button-bg);
      cursor: pointer;
      transition: background-color 0.3s ease;
      box-shadow: 0 2px 18px rgba(0,0,0,0.2);
    }
    #ytControlButtons button:hover, #ytControlButtons select:hover {
      background: var(--button-hover-bg);
      box-shadow: 0 2px 28px var(--accent);
    }
    #ytControlButtons select, #ytControlButtons input[type="checkbox"] {
      cursor: pointer;
      color: var(--input-fg);
      background: var(--input-bg);
      font-weight: 700;
      min-width: 85px;
      text-align: center;
      padding-left: 8px;
      border-radius: 14px;
    }
    #ytControlButtons input[type=checkbox] {
      min-width: 20px;
      min-height: 20px;
      padding: 0;
    }
    #ytControlButtons label {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 1rem;
      user-select:none;
    }
    #ytControlButtons label span {
      user-select:none;
      white-space: nowrap;
    }

    /* Collapsible Side Panel for Likes & Playlists */
    #ytSidePanelToggle {
      position: fixed;
      top: 16rem;
      right: 24px;
      background: var(--button-bg);
      color: var(--button-fg);
      border-radius: 22px 0 0 22px;
      font-weight: 900;
      padding: 12px 18px;
      cursor: pointer;
      box-shadow: 0 5px 25px rgba(0,0,0,0.35);
      z-index: 15000;
      user-select:none;
      transition: background-color 0.3s ease;
    }
    #ytSidePanelToggle:hover {
      background: var(--button-hover-bg);
    }
    #ytSidePanelToggle:focus {
      outline: 3px solid var(--accent);
      outline-offset: 4px;
    }

    #ytSidePanel {
      position: fixed;
      top: 6rem;
      right: 0;
      width: 360px;
      height: 70vh;
      background: var(--box-bg);
      box-shadow: -8px 2px 50px var(--box-shadow);
      border-radius: 24px 0 0 24px;
      overflow-y: auto;
      padding: 28px 25px 30px 25px;
      z-index: 15001;
      user-select:none;
      transition: transform 0.35s ease;
      transform: translateX(100%);
      display: flex;
      flex-direction: column;
      gap: 22px;
    }
    #ytSidePanel.open {
      transform: translateX(0);
    }
    #ytSidePanel h4 {
      font-weight: 900;
      font-size: 1.5rem;
      margin: 0 0 10px 0;
      user-select:none;
    }
    #ytSidePanel button.closeSidePanel {
      align-self: flex-end;
      font-size: 1.5rem;
      background: transparent;
      color: var(--fg);
      cursor: pointer;
      border: none;
      font-weight: 900;
      margin-bottom: 16px;
      user-select:none;
    }

    /* Likes List & Playlist List inside Side Panel */
    .ytList {
      flex-grow: 1;
      overflow-y: auto;
      border: 2px solid var(--input-border);
      border-radius: 16px;
      padding: 12px 14px;
      background: var(--input-bg);
      color: var(--input-fg);
      user-select:none;
      box-shadow: inset 0 0 10px #0004;
    }
    .ytList li {
      list-style: none;
      font-weight: 700;
      font-size: 1.1rem;
      padding: 6px 8px;
      margin: 4px 0;
      border-radius: 12px;
      cursor: pointer;
      user-select:none;
      transition: background-color 0.2s ease;
    }
    .ytList li:hover {
      background: var(--button-hover-bg);
      color: var(--button-fg);
    }
    .ytList li.selected {
      background: gold;
      color: #333;
    }

    /* YouTube URL input & Buttons on side panel */
    #playlistControls {
      display: flex;
      gap: 12px;
      user-select:none;
      flex-wrap: wrap;
      margin-top: 11px;
      justify-content: center;
    }
    #playlistControls button, #playlistControls input {
      flex-grow: 1;
      padding: 10px 14px;
      font-weight: 700;
      font-size: 1rem;
      border-radius: 12px;
      border: 2px solid var(--input-border);
      user-select:none;
      transition: border-color 0.3s ease;
    }
    #playlistControls input {
      border-radius: 16px;
      color: var(--input-fg);
      background: var(--input-bg);
      user-select:text;
    }
    #playlistControls input:focus {
      outline: none;
      border-color: var(--accent);
      box-shadow: 0 0 20px var(--accent);
    }
    #playlistControls button {
      cursor: pointer;
      background: var(--button-bg);
      color: var(--button-fg);
      border: none;
      box-shadow: 0 0 15px #0004;
      min-width: 100px;
    }
    #playlistControls button:hover {
      background: var(--button-hover-bg);
    }

    /* Console improvements */
    #consoleModeToggle {
      position: absolute;
      top: 20px;
      right: 20px;
      z-index: 12001;
      user-select:none;
      padding: 6px 15px;
      font-weight: 900;
      font-size: 1rem;
      border-radius: 18px;
      cursor: pointer;
      background: var(--button-bg);
      color: var(--button-fg);
      border:none;
      box-shadow: 0 3px 20px rgba(0,0,0,0.3);
      transition: background-color 0.3s ease;
    }
    #consoleModeToggle:hover {
      background: var(--button-hover-bg);
      box-shadow: 0 5px 28px var(--accent);
    }
    #consoleModeToggle:focus {
      outline: 3px solid var(--accent);
      outline-offset: 6px;
    }

    /* Intro Splash Screen */
    #introSplash {
      position: fixed;
      inset: 0;
      background: radial-gradient(circle at center, #008080, #003533);
      color: #00ffffcc;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-family: "Segoe UI Black", "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      font-weight: 900;
      font-size: clamp(2.5rem, 10vw, 6rem);
      letter-spacing: 0.24em;
      user-select:none;
      z-index: 15000;
      cursor: pointer;
      overflow: hidden;
      animation: slideIn 0.4s ease forwards, flicker 0.12s steps(10) 12 alternate forwards 0.4s, scalePulse 3s ease-in-out 5 alternate forwards;
    }
    #introSplash span {
      font-size: 1.2rem;
      margin-top: 10px;
      letter-spacing: normal;
      font-weight: 700;
      opacity: 0.75;
      color: #00d7d7aa;
      user-select:none;
      animation: fadeInUp 2s ease forwards 0.75s;
    }

    @keyframes slideIn {
      from {
        transform: translateY(35vh);
        opacity: 0;
        filter: blur(7px);
      }
      to {
        transform: translateY(0);
        opacity: 1;
        filter: blur(0);
      }
    }
    @keyframes flicker {
      0% {opacity: 1;}
      50% {opacity: 0.2;}
      100% {opacity: 1;}
    }
    @keyframes scalePulse {
      0% {transform: scale(1);}
      50% {transform: scale(1.06);}
      100% {transform: scale(1);}
    }
    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(4vh);
      }
      to {
        opacity: 0.75;
        transform: translateY(0);
      }
    }
  </style>
  
  <!-- External scripts -->
  <script src="https://cdn.jsdelivr.net/npm/particles.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vanta@latest/dist/vanta.waves.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.12/codemirror.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.12/mode/javascript/javascript.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.12/addon/hint/show-hint.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.12/addon/hint/javascript-hint.min.js"></script>
</head>
<body>

<!-- Intro Splash -->
<div id="introSplash" aria-label="Intro Splash Screen" role="img" tabindex="0" title="Click or press any key to skip">
  ULTIMATE<br/>GAMES &amp; YOUTUBE
  <span>The power to play and code</span>
</div>

<!-- Particles canvas -->
<div id="particles-js"></div>

<!-- Password Modal Overlay -->
<div id="overlay" aria-hidden="false" role="dialog" aria-modal="true" aria-labelledby="passwordTitle" tabindex="0">
  <div id="passwordModal">
      <h2 id="passwordTitle">Enter Password to Access</h2>
      <input type="password" id="passwordInput" aria-describedby="errorMessage" placeholder="Enter Password" autocomplete="current-password" autofocus />
      <button id="submitPassword" aria-label="Submit Password">Submit</button>
      <p id="errorMessage" role="alert" aria-live="assertive"></p>
  </div>
</div>

<!-- Settings Bar -->
<div id="settingsBar" role="navigation" aria-label="Main navigation buttons">
  <button id="settingsButton" aria-haspopup="true" aria-controls="settingsUI">Settings</button>
  <button id="youtubeUnblockerButton" aria-haspopup="true" aria-controls="youtubeEmbedUI">YouTube Player</button>
  <button id="gamesListButton">Games List</button>
  <button id="consoleButton" aria-haspopup="true" aria-controls="consoleUI">Console</button>
</div>

<!-- Settings UI -->
<div id="settingsUI" role="region" aria-label="Settings panel" tabindex="-1">
  <h3>Settings</h3>
  <label><input type="checkbox" id="darkModeToggle" /> Dark Mode (auto detects system if enabled on load)</label>
  <label><input type="checkbox" id="themeCycleToggle" /> Cycle background themes every 30 seconds</label>
  <label>Background Theme:
    <select id="themesDropdown" aria-label="Select background animation theme">
      <option value="none">None</option>
      <option value="waves">Waves</option>
      <option value="net">Net</option>
      <option value="clouds">Clouds</option>
      <option value="fog">Fog</option>
      <option value="birds">Birds</option>
      <option value="cells">Cells</option>
      <option value="halo">Halo</option>
      <option value="rings">Rings</option>
      <option value="globe">Globe</option>
    </select>
  </label>
  <label><input type="checkbox" id="enableDrag" /> Enable drag and drop game reorder</label>
  <label><input type="checkbox" id="toggleFavorites" /> Enable favorites toggle for games</label>
  <label><input type="checkbox" id="hideNonFavorites" /> Hide non-favorite games</label>
  <label><input type="checkbox" id="disableCutscene" /> Disable Intro Splash Screen</label>
  <label>Session Timeout (minutes):
    <input type="number" id="sessionTimeout" min="5" max="120" step="5" value="30" />
  </label>
  <label><input type="checkbox" id="rememberPassword" checked /> Remember password during session</label>
  <h4>Console Settings</h4>
  <label>Font Size:
    <select id="consoleFontSize">
      <option value="14">Small</option>
      <option value="16" selected>Medium</option>
      <option value="18">Large</option>
      <option value="20">Extra Large</option>
    </select>
  </label>
  <label>Theme:
    <select id="consoleTheme">
      <option value="monokai" selected>Monokai (Dark)</option>
      <option value="default">Default (Light)</option>
      <option value="material">Material</option>
    </select>
  </label>
  <label><input type="checkbox" id="enableConsoleKeybindings" checked /> Enable console keybindings</label>
</div>

<!-- YouTube Embed UI -->
<div id="youtubeEmbedUI" role="region" aria-label="YouTube Unblocker Video Player" tabindex="-1">
  <h3>YouTube Unblocker Player</h3>
  <input type="text" id="youtubeURL" placeholder="Enter YouTube link" spellcheck="false" aria-label="YouTube Video URL" />
  <button id="loadVideoButton">Load Video</button>
  <button id="changeVideoButton">Change Video</button>
  <div id="video-container" aria-live="polite" aria-label="YouTube Video Player"></div>

  <!-- Controls navigation -->
  <div id="ytControlsWrapper">
    <button id="ytControlsNavBtnPrev" aria-label="Scroll left controls">&lt;</button>
    <div id="ytControlButtons" tabindex="0" aria-label="YouTube player controls container"></div>
    <button id="ytControlsNavBtnNext" aria-label="Scroll right controls">&gt;</button>
  </div>
</div>

<!-- Side Panel for Likes & Playlists -->
<button id="ytSidePanelToggle" aria-expanded="false" aria-controls="ytSidePanel" aria-label="Toggle Likes and Playlists Panel">Likes &amp; Playlists</button>
<div id="ytSidePanel" role="region" aria-label="Likes and Playlists Panel" tabindex="-1" aria-hidden="true">
  <button class="closeSidePanel" aria-label="Close panel">&times;</button>
  
  <section>
    <h4>Liked Videos</h4>
    <ul id="likedVideosList" class="ytList" tabindex="0" aria-label="List of liked YouTube videos"></ul>
  </section>

  <section style="margin-top: 22px;">
    <h4>Saved Playlists</h4>
    <ul id="playlistList" class="ytList" tabindex="0" aria-label="List of saved YouTube playlists"></ul>
    <input type="text" id="newPlaylistName" placeholder="New playlist name" aria-label="New playlist name input" />
    <button id="createPlaylistBtn" aria-label="Create new playlist">Create Playlist</button>
  </section>
</div>

<!-- Console Mode Toggle -->
<button id="consoleModeToggle" aria-pressed="false" title="Toggle Console Eval Mode">API Mode</button>

<!-- Console UI -->
<div id="consoleUI" role="region" aria-label="Developer Console" tabindex="-1">
  <h3>Custom Console</h3>
  <div class="code-tab-bar" aria-label="Code tabs bar">
    <div id="newCodeButton" class="code-tab" tabindex="0" role="button" aria-label="Create new code tab">+</div>
  </div>
  <textarea id="consoleInput" spellcheck="false" aria-label="Console code input" placeholder="Enter JS/HTML code or API commands here..."></textarea>
  <div style="margin-top:18px;">
    <button id="runConsoleCode">Run</button>
    <button id="saveCodeButton">Save</button>
    <button id="deleteCodeButton">Delete All</button>
    <button id="downloadCodeButton">Download</button>
    <button id="uploadCodeButton">Upload</button>
  </div>
  <pre id="console-output" aria-live="polite" role="log"></pre>
</div>

<!-- Games List Page -->
<div id="gamePage1" class="container" role="region" aria-label="Games list - page 1" tabindex="0">
  <h2>HTML5 Games - Page 1</h2>
  <input type="text" id="gsearchbar" class="search-bar" placeholder="Search games" aria-label="Search games page 1" />
  <div id="glist1" role="list" tabindex="0" aria-activedescendant=""></div>
  <button id="nextPageButton" class="page-button" aria-label="Next page">Next Page</button>
</div>

<div id="gamePage2" class="container" role="region" aria-label="Games list - page 2" tabindex="0" style="display:none;">
  <h2>HTML5 Games - Page 2</h2>
  <input type="text" id="secoundgsearchbar" class="search-bar" placeholder="Search games" aria-label="Search games page 2" />
  <div id="glist2" role="list" tabindex="0" aria-activedescendant=""></div>
  <button id="prevPageButton" class="page-button" aria-label="Previous page">Previous Page</button>
</div>

<!-- Confirmation Dialog -->
<div id="confirmationDialog" role="alertdialog" aria-modal="true" aria-labelledby="confirmMsg" tabindex="-1">
  <p id="confirmMsg">Are you sure you want to open this game?</p>
  <div style="text-align:center;">
    <button id="confirmYes" aria-label="Yes">Yes</button>
    <button id="confirmNo" aria-label="No">No</button>
  </div>
</div>

<script>
(() => {
  "use strict";

  // === Toast system ===
  const toastContainer = document.getElementById('toast-container');
  function showToast(msg, type = 'info', duration = 4000) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    if (type === 'error') toast.style.background = '#d63031';
    else if (type === 'success') toast.style.background = '#00b894';
    toast.textContent = msg;
    toastContainer.appendChild(toast);
    setTimeout(() => toast.classList.add('show'), 50);
    toast.onclick = () => {
      toast.classList.remove('show');
      setTimeout(() => toast.remove(), 350);
    };
    setTimeout(() => {
      toast.classList.remove('show');
      setTimeout(() => toast.remove(), 350);
    }, duration);
  }

  // === Globals & Elements ===
  const overlay = document.getElementById('overlay');
  const passwordInput = document.getElementById('passwordInput');
  const submitPassword = document.getElementById('submitPassword');
  const errorMessage = document.getElementById('errorMessage');
  const introSplash = document.getElementById('introSplash');

  const darkModeToggle = document.getElementById('darkModeToggle');
  const themeCycleToggle = document.getElementById('themeCycleToggle');
  const themesDropdown = document.getElementById('themesDropdown');
  const enableDrag = document.getElementById('enableDrag');
  const toggleFavorites = document.getElementById('toggleFavorites');
  const hideNonFavorites = document.getElementById('hideNonFavorites');
  const disableCutscene = document.getElementById('disableCutscene');
  const sessionTimeoutInput = document.getElementById('sessionTimeout');
  const rememberPasswordToggle = document.getElementById('rememberPassword');
  
  const settingsButton = document.getElementById('settingsButton');
  const settingsUI = document.getElementById('settingsUI');
  const youtubeUnblockerButton = document.getElementById('youtubeUnblockerButton');
  const youtubeEmbedUI = document.getElementById('youtubeEmbedUI');
  const gamesListButton = document.getElementById('gamesListButton');
  const consoleButton = document.getElementById('consoleButton');
  const consoleUI = document.getElementById('consoleUI');

  // YouTube Player Elements
  const youtubeURL = document.getElementById('youtubeURL');
  const loadVideoButton = document.getElementById('loadVideoButton');
  const changeVideoButton = document.getElementById('changeVideoButton');
  const videoContainer = document.getElementById('video-container');
  const ytControlsWrapper = document.getElementById('ytControlsWrapper');
  const ytControlButtons = document.getElementById('ytControlButtons');
  const ytControlsNavBtnPrev = document.getElementById('ytControlsNavBtnPrev');
  const ytControlsNavBtnNext = document.getElementById('ytControlsNavBtnNext');

  // Side panel for likes+playlists
  const ytSidePanelToggle = document.getElementById('ytSidePanelToggle');
  const ytSidePanel = document.getElementById('ytSidePanel');
  const ytSidePanelClose = ytSidePanel.querySelector('button.closeSidePanel');
  const likedVideosList = document.getElementById('likedVideosList');
  const playlistList = document.getElementById('playlistList');
  const newPlaylistName = document.getElementById('newPlaylistName');
  const createPlaylistBtn = document.getElementById('createPlaylistBtn');

  // Console elements
  const consoleInput = document.getElementById('consoleInput');
  const runConsoleCode = document.getElementById('runConsoleCode');
  const saveCodeButton = document.getElementById('saveCodeButton');
  const deleteCodeButton = document.getElementById('deleteCodeButton');
  const downloadCodeButton = document.getElementById('downloadCodeButton');
  const uploadCodeButton = document.getElementById('uploadCodeButton');
  const newCodeButton = document.getElementById('newCodeButton');
  const consoleOutput = document.getElementById('console-output');
  const consoleModeToggle = document.getElementById('consoleModeToggle');

  // Games list pages
  const gamePage1 = document.getElementById('gamePage1');
  const gamePage2 = document.getElementById('gamePage2');
  const nextPageButton = document.getElementById('nextPageButton');
  const prevPageButton = document.getElementById('prevPageButton');
  const gsearchbar = document.getElementById('gsearchbar');
  const secoundgsearchbar = document.getElementById('secoundgsearchbar');
  const glist1 = document.getElementById('glist1');
  const glist2 = document.getElementById('glist2');

  // authentication / session
  const PASSWORD = "dja101";
  let currentSessionKey = "ultimateAppSessionActive";
  const SESSION_TIMEOUT_DEFAULT_MINUTES = 30;
  let sessionTimeout = SESSION_TIMEOUT_DEFAULT_MINUTES; // minutes
  let passwordRemember = true;

  // Vanta background theme
  let activeVantaEffect = null;
  const availableVantaThemes = ['waves','net','clouds','fog','birds','cells','halo','rings','globe'];
  let backgroundCycleInterval = null;

  // Local storage keys
  const LS_KEYS = {
    darkMode:'ultimate_darkMode',
    theme:'ultimate_theme',
    themeCycle:'ultimate_themeCycle',
    drag:'ultimate_enableDrag',
    favoritesToggle:'ultimate_toggleFavorites',
    hideNonFavorites:'ultimate_hideNonFavorites',
    disableIntro:'ultimate_disableIntro',
    sessionTimeout:'ultimate_sessionTimeout',
    rememberPassword:'ultimate_rememberPassword',
    favoritesList:'ultimate_favoritesList',
    likedVideos:'ultimate_likedVideos',
    savedPlaylists:'ultimate_savedPlaylists',
    gameOrder:'ultimate_gameOrder',
    codeTabsStore:'ultimate_codeTabsStore',
    consoleSettings: 'ultimate_consoleSettings'
  };

  // Persistent data & state
  let favoritesList = JSON.parse(localStorage.getItem(LS_KEYS.favoritesList) || '[]');
  let likedVideos = JSON.parse(localStorage.getItem(LS_KEYS.likedVideos) || '{}');
  let savedPlaylists = JSON.parse(localStorage.getItem(LS_KEYS.savedPlaylists) || '{}');
  let gameOrder = JSON.parse(localStorage.getItem(LS_KEYS.gameOrder) || '[]');
  let codeTabsStore = JSON.parse(localStorage.getItem(LS_KEYS.codeTabsStore) || '{}');
  let consoleSettings = JSON.parse(localStorage.getItem(LS_KEYS.consoleSettings) || '{}');

  // Current state
  let dragEnabled = false;
  let toggleFavoritesEnabled = false;
  let hidingNonFavorites = false;
  let disableIntro = false;
  let darkMode = false;
  let themeCycle = false;
  let selectedTheme = 'none';
  let sessionActive = false;

  // For code tabs
  let currentCodeTabId = null;
  let codeTabCounter = Object.keys(codeTabsStore).length || 0;

  // Games data - kept as before, modular for future expansion
  const gameLists = [
    {
      container: glist1,
      games: [
        ["2048","./gfiles/html5/2048/index.html"],
        ["A Dark Room","./gfiles/html5/adarkroom/index.html"],
        ["ASCII Space","./gfiles/html5/asciispace/index.html"],
        ["Asteroids","./gfiles/html5/asteroids/index.html"],
        ["Black Hole Square","./gfiles/html5/blackholesquare/index.html"],
        ["Bounce Back","./gfiles/html5/bounceback/index.html"],
        ["Breaklock","./gfiles/html5/breaklock/index.html"],
        ["Breakout","./gfiles/html5/breakout/index.html"],
        ["Captain Callisto","./gfiles/html5/captaincallisto/index.html"],
        ["Chess","./gfiles/html5/chess/index.html"],
        ["Chroma Incident","./gfiles/html5/chromaincident/index.html"],
        ["Chrome-Dino","./ChromeD.html"],
        ["Connect 3","./gfiles/html5/connect3/index.html"],
        ["Pac-Man","./Pacman.html"],
        ["Cookie Clicker","./gfiles/html5/cookieclicker/index.html"],
        ["Edge not Found","./gfiles/html5/edgenotfound/index.html"],
        ["Evil Glitch","./gfiles/html5/evilglitch/index.html"],
        ["Factory Balls Forever","./gfiles/html5/factoryballsforever/index.html"],
        ["Flappy Bird","./gfiles/html5/flappybird/index.html"],
        ["Geometry Dash","./gfiles/html5/geometrydash/index.html"],
        ["Hextris","./gfiles/html5/hextris/index.html"],
        ["Five nights at freddys","./Selecter.html"],
        ["Konnekt","./gfiles/html5/konnekt/index.html"],
        ["Minecraft","./gfiles/html5/minecraft/index.html"],
        ["Ninja vs Evilcorp","./gfiles/html5/ninjavsevilcorp/index.html"],
        ["Packabunchas","./gfiles/html5/packabunchas/index.html"],
        ["Particle Clicker","./gfiles/html5/particleclicker/index.html"],
        ["Push Back","./gfiles/html5/pushback/index.html"],
        ["Racer","./gfiles/html5/racer/index.html"],
        ["Radius Raid","./gfiles/html5/radiusraid/index.html"],
        ["Retrohaunt","./gfiles/html5/retrohaunt/index.html"],
        ["Road Blocks","./gfiles/html5/roadblocks/index.html"],
        ["Shuttledeck","./gfiles/html5/shuttledeck/index.html"],
        ["Sleeping Beauty","./gfiles/html5/sleepingbeauty/index.html"],
        ["Tetris","./gfiles/html5/tetris/index.html"],
        ["Towermaster","./gfiles/html5/towermaster/index.html"],
        ["Trimps","./gfiles/html5/trimps/index.html"],
        ["xx142-b2.exe","./gfiles/html5/xx142-b2exe/index.html"],
        ["Super-Mario-Bros","./gfiles/html5/FullScreenMario-master/index.html"],
        ["Edge-Surf","./gfiles/html5/MicrosoftEdge-SURF-master/index.html"]
      ]
    },
    {
      container: glist2,
      games: [
        ["Wordle","./gfiles/html5/extragames/games/wordle.html"]
      ]
    }
  ];

  // For YouTube Player
  let currentVideoId = null;
  let ytPlayerIframe = null;
  let playlist = [];
  let currentPlaylistIndex = 0;
  let ytControls = []; // Array of button/select elements in control bar

  // === Initialize everything on DOMContentLoaded ===
  window.addEventListener('DOMContentLoaded', () => {

    // Setup initial theme and UI state
    loadSettings();
    applyStoredSettingsUI();
    bindEventListeners();
    fillGameLists();
    restoreGameListOrder();
    listLikedVideos();
    listPlaylists();

    // Check if session active or show password overlay
    if(checkSessionActive()) {
      unlockPage();
      if(!disableIntro) showIntroSplash();
      else showGamesList(1);
    } else {
      showPasswordOverlay();
    }

    // Setup background theme immediately
    setupBackgroundAnimation(selectedTheme);

    // Setup theme auto cycle if enabled
    if(themeCycle) startThemeCycle();
  });

  // === Helper Functions ===

  // Toast
  let toastTimeout = null;
  function showToast(msg, type='info', dur=4000) {
    const t = document.createElement('div');
    t.className = 'toast';
    t.textContent = msg;
    if(type==='error') t.style.background = '#e74c3c';
    if(type==='success') t.style.background = '#27ae60';
    toastContainer.appendChild(t);
    setTimeout(() => t.classList.add('show'), 50);
    t.onclick = () => { t.classList.remove('show'); setTimeout(() => t.remove(), 300); };
    clearTimeout(toastTimeout);
    toastTimeout = setTimeout(() => { t.classList.remove('show'); setTimeout(() => t.remove(), 300); }, dur);
  }

  // Save all current settings
  function saveSettings() {
    localStorage.setItem(LS_KEYS.darkMode, darkModeToggle.checked);
    localStorage.setItem(LS_KEYS.themeCycle, themeCycleToggle.checked);
    localStorage.setItem(LS_KEYS.theme, themesDropdown.value);
    localStorage.setItem(LS_KEYS.drag, enableDrag.checked);
    localStorage.setItem(LS_KEYS.favoritesToggle, toggleFavorites.checked);
    localStorage.setItem(LS_KEYS.hideNonFavorites, hideNonFavorites.checked);
    localStorage.setItem(LS_KEYS.disableIntro, disableCutscene.checked);
    localStorage.setItem(LS_KEYS.sessionTimeout, sessionTimeoutInput.value);
    localStorage.setItem(LS_KEYS.rememberPassword, rememberPasswordToggle.checked);
    // Clear background cycle interval if needed
    if (!themeCycleToggle.checked) stopThemeCycle();
  }

  // Load stored settings
  function loadSettings() {
    darkMode = JSON.parse(localStorage.getItem(LS_KEYS.darkMode)) || false;
    darkModeToggle.checked = darkMode;
    themeCycle = JSON.parse(localStorage.getItem(LS_KEYS.themeCycle)) || false;
    themeCycleToggle.checked = themeCycle;
    selectedTheme = localStorage.getItem(LS_KEYS.theme) || 'none';
    themesDropdown.value = selectedTheme;
    dragEnabled = JSON.parse(localStorage.getItem(LS_KEYS.drag)) || false;
    enableDrag.checked = dragEnabled;
    toggleFavoritesEnabled = JSON.parse(localStorage.getItem(LS_KEYS.favoritesToggle)) || false;
    toggleFavorites.checked = toggleFavoritesEnabled;
    hidingNonFavorites = JSON.parse(localStorage.getItem(LS_KEYS.hideNonFavorites)) || false;
    hideNonFavorites.checked = hidingNonFavorites;
    disableIntro = JSON.parse(localStorage.getItem(LS_KEYS.disableIntro)) || false;
    disableCutscene.checked = disableIntro;
    sessionTimeout = parseInt(localStorage.getItem(LS_KEYS.sessionTimeout)) || SESSION_TIMEOUT_DEFAULT_MINUTES;
    sessionTimeoutInput.value = sessionTimeout;
    passwordRemember = localStorage.getItem(LS_KEYS.rememberPassword);
    if(passwordRemember === null) passwordRemember = true;
    else passwordRemember = JSON.parse(passwordRemember);
    rememberPasswordToggle.checked = passwordRemember;
  }

  // Apply UI changes from loaded settings
  function applyStoredSettingsUI() {
    document.body.classList.toggle('dark-mode', darkMode);
    dragEnabled = enableDrag.checked;
    toggleFavoritesEnabled = toggleFavorites.checked;
    hidingNonFavorites = hideNonFavorites.checked;
    disableIntro = disableCutscene.checked;
  }

  // Setup background animation using Vanta.js
  function setupBackgroundAnimation(theme) {
    try {
      if(activeVantaEffect) {
        activeVantaEffect.destroy();
        activeVantaEffect = null;
      }
      if(theme === 'none') return;
      switch(theme) {
        case 'waves': activeVantaEffect = VANTA.WAVES({ el: "#particles-js", mouseControls: true, touchControls: true, gyroControls: true }); break;
        case 'net': activeVantaEffect = VANTA.NET({ el: "#particles-js", mouseControls: true, touchControls: true, gyroControls: true }); break;
        case 'clouds': activeVantaEffect = VANTA.CLOUDS({ el: "#particles-js" }); break;
        case 'fog': activeVantaEffect = VANTA.FOG({ el: "#particles-js" }); break;
        case 'birds': activeVantaEffect = VANTA.BIRDS({ el: "#particles-js", mouseControls: true, touchControls: true }); break;
        case 'cells': activeVantaEffect = VANTA.CELLS({ el: "#particles-js", mouseControls: true, touchControls: true }); break;
        case 'halo': activeVantaEffect = VANTA.HALO({ el: "#particles-js", mouseControls: true, touchControls: true }); break;
        case 'rings': activeVantaEffect = VANTA.RINGS({ el: "#particles-js", mouseControls: true, touchControls: true }); break;
        case 'globe': activeVantaEffect = VANTA.GLOBE({ el: "#particles-js", mouseControls: true, touchControls: true }); break;
      }
    } catch (e) {
      console.warn('Background animation load failed:', e);
      showToast('Background animation failed to load', 'error');
    }
  }

  // Start automatic cycling for background theme every 30 sec
  let backgroundCycleTimer = null;
  function startThemeCycle() {
    stopThemeCycle();
    backgroundCycleTimer = setInterval(() => {
      let idx = availableVantaThemes.indexOf(selectedTheme);
      idx = (idx + 1) % availableVantaThemes.length;
      selectedTheme = availableVantaThemes[idx];
      themesDropdown.value = selectedTheme;
      saveSettings();
      setupBackgroundAnimation(selectedTheme);
    }, 30000);
  }
  function stopThemeCycle() {
    if(backgroundCycleTimer) clearInterval(backgroundCycleTimer);
    backgroundCycleTimer = null;
  }

  // === Password overlay/session management ===
  function showPasswordOverlay() {
    overlay.setAttribute('aria-hidden', 'false');
    overlay.style.opacity = '1';
    document.body.classList.add('locked');
    passwordInput.focus();
  }
  function hidePasswordOverlay() {
    overlay.setAttribute('aria-hidden', 'true');
    overlay.style.opacity = '0';
    document.body.classList.remove('locked');
  }
  function checkSessionActive() {
    if(!passwordRemember) return false;
    const active = sessionStorage.getItem(currentSessionKey);
    if(active) {
      const start = parseInt(localStorage.getItem(currentSessionKey + '_start') || '0');
      if(Date.now() - start < sessionTimeout * 60 * 1000) {
        return true;
      }
      // expired
      sessionStorage.removeItem(currentSessionKey);
      return false;
    }
    return false;
  }
  function unlockPage() {
    sessionStorage.setItem(currentSessionKey, 'true');
    localStorage.setItem(currentSessionKey + '_start', Date.now().toString());
    hidePasswordOverlay();
  }
  function lockPage() {
    sessionStorage.removeItem(currentSessionKey);
    localStorage.removeItem(currentSessionKey + '_start');
    showPasswordOverlay();
  }

  submitPassword.addEventListener('click', () => {
    if(passwordInput.value === PASSWORD) {
      unlockPage();
      introSplash.style.display = 'none';
      showIntroSplash();
    } else {
      errorMessage.textContent = 'Incorrect password, try again.';
      showToast('Wrong password! Please retry.', 'error');
    }
  });
  passwordInput.addEventListener('keydown', e => {
    if(e.key === 'Enter') {
      submitPassword.click();
    }
  });

  // === Intro Splash Animation ===
  let introDismissed = false;
  function showIntroSplash() {
    if(disableIntro) {
      introSplash.style.display = 'none';
      showGamesList(1);
      return;
    }
    introSplash.style.display = 'flex';
    introDismissed = false;

    function dismissIntro() {
      if(introDismissed) return;
      introDismissed = true;
      introSplash.style.opacity = '0';
      setTimeout(() => {
        introSplash.style.display = 'none';
        introSplash.style.opacity = '1';
        showGamesList(1);
      }, 700);
    }
    window.setTimeout(dismissIntro, 6000);
    introSplash.onclick = dismissIntro;
    introSplash.onkeydown = e => {
      if(e.key === 'Enter' || e.key === 'Escape' || e.key === ' ') dismissIntro();
    };
  }

  // === Games List & Navigation ===

  function createGameLinkElement(gameName, gameLink) {
    const a = document.createElement('a');
    a.href = 'javascript:void(0)';
    a.className = 'game-link';
    a.setAttribute('data-link', gameLink);
    a.setAttribute('role', 'option');
    a.tabIndex = 0;
    a.textContent = gameName;
    if(isGameFavorited(gameLink)) {
      a.classList.add('favorite');
      a.setAttribute('aria-label', `${gameName} (Favorited)`);
    }
    a.addEventListener('click', () => gameOpenConfirm(gameName, gameLink));
    a.addEventListener('keydown', e => {
      if(e.key === 'Enter' || e.key === ' ') {
        gameOpenConfirm(gameName, gameLink);
        e.preventDefault();
      }
    });
    if(toggleFavoritesEnabled) {
      a.addEventListener('click', toggleFavoriteHandler);
    }
    if(dragEnabled) {
      a.draggable = true;
      a.addEventListener('dragstart', dragStartHandler);
      a.addEventListener('dragover', dragOverHandler);
      a.addEventListener('drop', dropHandler);
      a.addEventListener('dragend', dragEndHandler);
    }
    return a;
  }

  // Render game lists with filtering and ordering
  function fillGameLists() {
    gameLists.forEach(list => {
      list.container.innerHTML = '';
      let filteredGames = list.games;
      if(hidingNonFavorites) {
        filteredGames = filteredGames.filter(g => isGameFavorited(g[1]));
      }
      // sort to put favorites first
      filteredGames.sort((a,b) => {
        return (isGameFavorited(b[1]) ? 1 : 0) - (isGameFavorited(a[1]) ? 1 : 0);
      });
      filteredGames.forEach(g => {
        let el = createGameLinkElement(g[0], g[1]);
        list.container.appendChild(el);
      });
      reorderGamesList(list.container);
    });
  }

  // Stores favorites in localStorage
  function isGameFavorited(link) {
    return favoritesList.includes(link);
  }
  function toggleFavoriteLink(link) {
    if(isGameFavorited(link)) {
      favoritesList = favoritesList.filter(g => g!==link);
    } else {
      favoritesList.push(link);
    }
    localStorage.setItem(LS_KEYS.favoritesList, JSON.stringify(favoritesList));
  }
  function toggleFavoriteHandler(e) {
    e.preventDefault();
    const link = e.currentTarget;
    toggleFavoriteLink(link.getAttribute('data-link'));
    fillGameLists();
  }

  // Drag-n-drop handlers for game reorder
  let dragSource = null;
  function dragStartHandler(e) {
    dragSource = e.target;
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData('text/plain', e.target.getAttribute('data-link'));
    e.target.style.opacity = '0.4';
  }
  function dragOverHandler(e) {
    e.preventDefault();
    const target = e.target.closest('.game-link');
    if(!target || target === dragSource) return;
    const container = target.parentNode;
    const rect = target.getBoundingClientRect();
    const offset = e.clientY - rect.top;
    if(offset > rect.height / 2) {
      container.insertBefore(dragSource, target.nextSibling);
    } else {
      container.insertBefore(dragSource, target);
    }
  }
  function dropHandler(e) {
    e.preventDefault();
    saveGameListOrder();
  }
  function dragEndHandler(e) {
    e.target.style.opacity = '1';
  }

  // Save order of games to localStorage
  function saveGameListOrder() {
    const allLinks = [];
    document.querySelectorAll('.game-link').forEach(a => {
      allLinks.push(a.getAttribute('data-link'));
    });
    localStorage.setItem(LS_KEYS.gameOrder, JSON.stringify(allLinks));
    showToast('Game order saved.', 'success');
  }
  function restoreGameListOrder() {
    const order = JSON.parse(localStorage.getItem(LS_KEYS.gameOrder) || '[]');
    if(!order.length) return;
    gameLists.forEach(list => {
      const container = list.container;
      order.forEach(link => {
        const el = container.querySelector(`.game-link[data-link="${link}"]`);
        if(el) container.appendChild(el);
      });
    });
  }
  function reorderGamesList(container) {
    if(!gameOrder.length) return;
    gameOrder.forEach(link => {
      const el = container.querySelector(`.game-link[data-link="${link}"]`);
      if(el) container.appendChild(el);
    });
  }

  // Filtering 
  gsearchbar.addEventListener('input', () => {
    const val = gsearchbar.value.toLowerCase();
    Array.from(glist1.children).forEach(a => {
      a.style.display = a.textContent.toLowerCase().includes(val) ? 'flex' : 'none';
    });
  });
  secoundgsearchbar.addEventListener('input', () => {
    const val = secoundgsearchbar.value.toLowerCase();
    Array.from(glist2.children).forEach(a => {
      a.style.display = a.textContent.toLowerCase().includes(val) ? 'flex' : 'none';
    });
  });

  // Confirm game open dialog
  const confirmationDialog = document.getElementById('confirmationDialog');
  const confirmYes = document.getElementById('confirmYes');
  const confirmNo = document.getElementById('confirmNo');
  let gameLinkToOpen = null;
  let gameNameToOpen = null;
  function gameOpenConfirm(name, link) {
    if (dragEnabled || toggleFavoritesEnabled) return;
    gameLinkToOpen = link;
    gameNameToOpen = name;
    confirmationDialog.style.display = 'flex';
    confirmationDialog.focus();
    document.getElementById('confirmMsg').textContent = `Open "${name}"?`;
  }
  confirmYes.addEventListener('click', () => {
    if(gameLinkToOpen) {
      window.location.href = gameLinkToOpen;
    }
  });
  confirmNo.addEventListener('click', () => {
    confirmationDialog.style.display = 'none';
    gameLinkToOpen = null;
  });

  // Page buttons
  nextPageButton.addEventListener('click', () => {
    showGamesList(2);
  });
  prevPageButton.addEventListener('click', () => {
    showGamesList(1);
  });
  gamesListButton.addEventListener('click', () => {
    showGamesList(1);
    youtubeEmbedUI.classList.remove('active');
    consoleUI.classList.remove('active');
    settingsUI.classList.remove('active');
  });

  // Show games list by page number (1 or 2)
  function showGamesList(pageNum) {
    gamePage1.style.display = pageNum === 1 ? 'block' : 'none';
    gamePage2.style.display = pageNum === 2 ? 'block' : 'none';
    // Hide others
    youtubeEmbedUI.classList.remove('active');
    consoleUI.classList.remove('active');
    settingsUI.classList.remove('active');
  }

  // === Dynamic Event binding ===
  function bindEventListeners() {
    // Settings bar buttons
    settingsButton.addEventListener('click', () => {
      togglePanel(settingsUI);
      youtubeEmbedUI.classList.remove('active');
      consoleUI.classList.remove('active');
      gamePage1.style.display = gamePage2.style.display = 'none';
    });
    youtubeUnblockerButton.addEventListener('click', () => {
      togglePanel(youtubeEmbedUI);
      settingsUI.classList.remove('active');
      consoleUI.classList.remove('active');
      gamePage1.style.display = gamePage2.style.display = 'none';
    });
    consoleButton.addEventListener('click', () => {
      togglePanel(consoleUI);
      settingsUI.classList.remove('active');
      youtubeEmbedUI.classList.remove('active');
      gamePage1.style.display = gamePage2.style.display = 'none';
    });

    // Settings UI bindings
    darkModeToggle.addEventListener('change', () => {
      darkMode = darkModeToggle.checked;
      document.body.classList.toggle('dark-mode', darkMode);
      saveSettings();
    });
    themeCycleToggle.addEventListener('change', () => {
      themeCycle = themeCycleToggle.checked;
      saveSettings();
      if(themeCycle) startThemeCycle();
      else stopThemeCycle();
    });
    themesDropdown.addEventListener('change', () => {
      selectedTheme = themesDropdown.value;
      saveSettings();
      setupBackgroundAnimation(selectedTheme);
    });
    enableDrag.addEventListener('change', () => {
      dragEnabled = enableDrag.checked;
      saveSettings();
      fillGameLists();
    });
    toggleFavorites.addEventListener('change', () => {
      toggleFavoritesEnabled = toggleFavorites.checked;
      saveSettings();
      fillGameLists();
    });
    hideNonFavorites.addEventListener('change', () => {
      hidingNonFavorites = hideNonFavorites.checked;
      saveSettings();
      fillGameLists();
    });
    disableCutscene.addEventListener('change', () => {
      disableIntro = disableCutscene.checked;
      saveSettings();
    });
    sessionTimeoutInput.addEventListener('change', () => {
      sessionTimeout = parseInt(sessionTimeoutInput.value) || SESSION_TIMEOUT_DEFAULT_MINUTES;
      saveSettings();
    });
    rememberPasswordToggle.addEventListener('change', () => {
      passwordRemember = rememberPasswordToggle.checked;
      saveSettings();
    });

    // YouTube URL & Controls
    loadVideoButton.addEventListener('click', loadYouTubeVideo);
    changeVideoButton.addEventListener('click', resetYouTubePlayer);
    ytControlsNavBtnPrev.addEventListener('click', () => scrollYTControls(-1));
    ytControlsNavBtnNext.addEventListener('click', () => scrollYTControls(1));
    ytSidePanelToggle.addEventListener('click', toggleSidePanel);
    ytSidePanelClose.addEventListener('click', () => closeSidePanel());
    createPlaylistBtn.addEventListener('click', createPlaylist);

    // Console buttons
    runConsoleCode.addEventListener('click', () => {
      runConsoleInput(consoleInput.value, consoleModeToggle.getAttribute('aria-pressed') === 'true');
    });
    saveCodeButton.addEventListener('click', saveCurrentCodeTab);
    deleteCodeButton.addEventListener('click', deleteAllCodeTabs);
    downloadCodeButton.addEventListener('click', downloadCodeToFile);
    uploadCodeButton.addEventListener('click', uploadCodeFromFile);
    newCodeButton.addEventListener('click', createNewCodeTab);
    consoleModeToggle.addEventListener('click', toggleConsoleMode);

    currentCodeTabId = Object.keys(codeTabsStore)[0] || createNewCodeTab();
    renderCodeTabs();
    loadCurrentTab();
  }

  function togglePanel(panel) {
    if(panel.classList.contains('active')) panel.classList.remove('active');
    else panel.classList.add('active');
  }

  // === YouTube Player Logic ===

  function isValidYouTubeURL(str) {
    return /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)/.test(str);
  }
  function extractYouTubeId(url) {
    if(!url) return null;
    const reg = /(?:v=|\/)([a-zA-Z0-9_-]{11})(?:[&?]|$)/;
    const match = url.match(reg);
    return match ? match[1] : null;
  }

  function loadYouTubeVideo() {
    const url = youtubeURL.value.trim();
    if(!isValidYouTubeURL(url)) {
      videoContainer.innerHTML = `<p style="color:red;">Invalid YouTube URL entered. Please try again.</p>`;
      return;
    }
    const videoId = extractYouTubeId(url);
    if(!videoId) {
      videoContainer.innerHTML = `<p style="color:red;">Failed to extract video ID from URL.</p>`;
      return;
    }
    currentVideoId = videoId;
    playlist = [videoId];
    currentPlaylistIndex = 0;
    embedYouTubeVideo(videoId);
    youtubeURL.style.display = 'none';
    loadVideoButton.style.display = 'none';
    changeVideoButton.style.display = 'inline-block';
    buildYTControls();
    updatePlayerControlsState();
  }

  function embedYouTubeVideo(videoId) {
    // Remove any old iframe
    videoContainer.innerHTML = '';
    ytPlayerIframe = document.createElement('iframe');
    ytPlayerIframe.width = '100%';
    ytPlayerIframe.height = '100%';
    ytPlayerIframe.src = `https://www.youtube-nocookie.com/embed/${videoId}?enablejsapi=1&modestbranding=1&rel=0`;
    ytPlayerIframe.frameBorder = '0';
    ytPlayerIframe.allowFullscreen = true;
    videoContainer.appendChild(ytPlayerIframe);
  }

  function resetYouTubePlayer() {
    currentVideoId = null;
    playlist = [];
    currentPlaylistIndex = 0;
    videoContainer.innerHTML = '';
    youtubeURL.style.display = 'inline-block';
    youtubeURL.value = '';
    loadVideoButton.style.display = 'inline-block';
    changeVideoButton.style.display = 'none';
    ytControlButtons.innerHTML = '';
    updatePlayerControlsState();
  }

  // Scroll controls bar left or right
  function scrollYTControls(dir) {
    ytControlButtons.scrollBy({left: dir * 120, behavior: 'smooth'});
  }

  // Rebuild player control buttons & UI
  function buildYTControls() {
    ytControlButtons.innerHTML = '';
    ytControls = [];

    // Play/Pause button
    const playPauseBtn = document.createElement('button');
    playPauseBtn.textContent = '⏯️ Play/Pause';
    playPauseBtn.title = 'Play or pause video (API support limited)';
    playPauseBtn.onclick = () => {
      showToast('Play/Pause control is not supported in iframe embeds.', 'error');
    };
    ytControlButtons.appendChild(playPauseBtn);
    ytControls.push(playPauseBtn);

    // Playback Speed selector
    const speedSelect = document.createElement('select');
    speedSelect.title = 'Playback speed';
    const speeds = [0.25,0.5,0.75,1,1.25,1.5,2];
    speeds.forEach(s => {
      const opt = document.createElement('option');
      opt.value = s;
      opt.textContent = `${s}x`;
      if(s === 1) opt.selected = true;
      speedSelect.appendChild(opt);
    });
    speedSelect.onchange = () => {
      showToast('Playback speed change is not supported in iframe embeds.', 'error');
    };
    ytControlButtons.appendChild(speedSelect);
    ytControls.push(speedSelect);

    // Quality selector - only informational
    const qualitySelect = document.createElement('select');
    qualitySelect.title = 'Playback quality (info only)';
    ['144p','360p','480p','720p','1080p','Highres'].forEach(q => {
      const opt = document.createElement('option');
      opt.value = q.toLowerCase();
      opt.textContent = q;
      qualitySelect.appendChild(opt);
    });
    qualitySelect.onchange = () => {
      showToast('Playback quality change is not supported in iframe embeds.', 'error');
    };
    ytControlButtons.appendChild(qualitySelect);
    ytControls.push(qualitySelect);

    // Captions toggle (checkbox)
    const captionsLabel = document.createElement('label');
    captionsLabel.textContent = 'Subtitles';
    const captionsToggle = document.createElement('input');
    captionsToggle.type = 'checkbox';
    captionsToggle.title = 'Toggle subtitles (not supported)';
    captionsToggle.onchange = () => {
      showToast('Subtitles toggling is not supported in iframe embeds.', 'error');
    };
    captionsLabel.prepend(captionsToggle);
    ytControlButtons.appendChild(captionsLabel);
    ytControls.push(captionsToggle);

    // Like button
    const likeBtn = document.createElement('button');
    function updateLikeBtn() {
      if (currentVideoId && likedVideos[currentVideoId]) {
        likeBtn.textContent = '❤️ Liked';
        likeBtn.style.color = '#ff4655';
      } else {
        likeBtn.textContent = '🤍 Like';
        likeBtn.style.color = 'inherit';
      }
    }
    updateLikeBtn();
    likeBtn.title = 'Like/unlike video';
    likeBtn.onclick = () => {
      if(!currentVideoId) return;
      if(likedVideos[currentVideoId]) {
        delete likedVideos[currentVideoId];
        showToast('Video unliked');
      } else {
        likedVideos[currentVideoId] = true;
        showToast('Video liked');
      }
      localStorage.setItem(LS_KEYS.likedVideos, JSON.stringify(likedVideos));
      updateLikeBtn();
      listLikedVideos();
    };
    ytControlButtons.appendChild(likeBtn);
    ytControls.push(likeBtn);

    // Save current video to playlist button
    const savePlaylistBtn = document.createElement('button');
    savePlaylistBtn.textContent = '💾 Save to Playlist';
    savePlaylistBtn.title = 'Add current video to playlist';
    savePlaylistBtn.onclick = () => addCurrentVideoToPlaylist();
    ytControlButtons.appendChild(savePlaylistBtn);
    ytControls.push(savePlaylistBtn);

    // Show playlists toggle button
    const showPlaylistsBtn = document.createElement('button');
    showPlaylistsBtn.textContent = '📑 Playlists';
    showPlaylistsBtn.title = 'Show saved playlists panel';
    showPlaylistsBtn.onclick = () => {
      toggleSidePanel(true);
    };
    ytControlButtons.appendChild(showPlaylistsBtn);
    ytControls.push(showPlaylistsBtn);
  }

  // Update prev/next nav buttons enable state based on playlist
  function updatePlayerControlsState() {
    ytControlsNavBtnPrev.disabled = currentPlaylistIndex <= 0;
    ytControlsNavBtnNext.disabled = playlist.length <= 1 || currentPlaylistIndex >= playlist.length - 1;
  }

  // Side panel toggle
  function toggleSidePanel(forceOpen) {
    const open = ytSidePanel.classList.contains('open');
    if(forceOpen === true || (!open && forceOpen !== false)) {
      ytSidePanel.classList.add('open');
      ytSidePanel.setAttribute('aria-hidden', 'false');
      ytSidePanelToggle.setAttribute('aria-expanded', 'true');
      ytSidePanel.focus();
    } else {
      ytSidePanel.classList.remove('open');
      ytSidePanel.setAttribute('aria-hidden', 'true');
      ytSidePanelToggle.setAttribute('aria-expanded', 'false');
    }
  }
  function closeSidePanel() {
    toggleSidePanel(false);
  }

  // List liked videos in side panel
  function listLikedVideos() {
    likedVideosList.innerHTML = '';
    const videos = Object.keys(likedVideos);
    if (videos.length === 0) {
      const li = document.createElement('li');
      li.textContent = 'No liked videos yet.';
      likedVideosList.appendChild(li);
      return;
    }
    videos.forEach(id => {
      const li = document.createElement('li');
      li.textContent = id;
      li.title = 'Click to load this liked video';
      li.addEventListener('click', () => {
        currentVideoId = id;
        playlist = [id];
        currentPlaylistIndex = 0;
        embedYouTubeVideo(id);
        toggleSidePanel(false);
      });
      likedVideosList.appendChild(li);
    });
  }

  // Playlist management
  function listPlaylists() {
    playlistList.innerHTML = '';
    const names = Object.keys(savedPlaylists);
    if(names.length === 0) {
      const li = document.createElement('li');
      li.textContent = 'No saved playlists.';
      playlistList.appendChild(li);
      return;
    }
    names.forEach(name => {
      const li = document.createElement('li');
      li.textContent = name;
      li.title = 'Play playlist';
      li.style.display = 'flex';
      li.style.justifyContent = 'space-between';
      li.style.alignItems = 'center';

      const playBtn = document.createElement('button');
      playBtn.textContent = '▶️';
      playBtn.title = `Play playlist ${name}`;
      playBtn.style.marginLeft = '12px';
      playBtn.addEventListener('click', () => {
        playPlaylist(name);
        toggleSidePanel(false);
      });

      const delBtn = document.createElement('button');
      delBtn.textContent = '🗑️';
      delBtn.title = `Delete playlist ${name}`;
      delBtn.style.marginLeft = '8px';
      delBtn.addEventListener('click', () => {
        if(confirm(`Delete playlist "${name}"?`)) {
          delete savedPlaylists[name];
          localStorage.setItem(LS_KEYS.savedPlaylists, JSON.stringify(savedPlaylists));
          listPlaylists();
          showToast('Playlist deleted', 'error');
        }
      });

      li.appendChild(playBtn);
      li.appendChild(delBtn);
      playlistList.appendChild(li);
    });
  }

  // Add current video to playlist by asking user
  function addCurrentVideoToPlaylist() {
    if(!currentVideoId) {
      showToast('No video loaded to add', 'error');
      return;
    }
    let playlistName = prompt('Enter the playlist name to add current video:');
    if(!playlistName) return;
    if(!savedPlaylists[playlistName]) savedPlaylists[playlistName] = [];
    if(savedPlaylists[playlistName].includes(currentVideoId)) {
      showToast('Video already in playlist', 'info');
      return;
    }
    savedPlaylists[playlistName].push(currentVideoId);
    localStorage.setItem(LS_KEYS.savedPlaylists, JSON.stringify(savedPlaylists));
    showToast(`Video added to playlist "${playlistName}"`);
    listPlaylists();
  }

  createPlaylistBtn.addEventListener('click', () => {
    let name = newPlaylistName.value.trim();
    if(!name) {
      alert('Please enter a valid playlist name!');
      return;
    }
    if(savedPlaylists[name]) {
      alert('Playlist already exists.');
      return;
    }
    savedPlaylists[name] = [];
    localStorage.setItem(LS_KEYS.savedPlaylists, JSON.stringify(savedPlaylists));
    newPlaylistName.value = "";
    listPlaylists();
    showToast(`Playlist "${name}" created`);
  });

  // Play playlist by name
  function playPlaylist(name) {
    let vids = savedPlaylists[name];
    if(!vids || vids.length === 0) {
      showToast('Playlist is empty', 'error');
      return;
    }
    playlist = vids.slice();
    currentPlaylistIndex = 0;
    currentVideoId = playlist[currentPlaylistIndex];
    embedYouTubeVideo(currentVideoId);
  }

  // === Console Logic ===
  let evaluationModeRawJS = true; // true: raw JS/HTML, false: API command mode

  // Switch console mode button
  consoleModeToggle.addEventListener('click', () => {
    evaluationModeRawJS = !evaluationModeRawJS;
    consoleModeToggle.setAttribute('aria-pressed', String(!evaluationModeRawJS));
    consoleModeToggle.textContent = evaluationModeRawJS ? 'API Mode' : 'Raw JS/HTML Mode';
    showToast(`Console evaluates: ${evaluationModeRawJS ? 'Raw JS/HTML' : 'Internal API commands'}`);
  });

  // Manage code tabs
  function createNewCodeTab() {
    const id = `tab-${codeTabCounter++}`;
    codeTabsStore[id] = '';
    currentCodeTabId = id;
    saveCodeTabsStore();
    renderCodeTabs();
    loadCurrentTab();
    showToast('New code tab created', 'success');
    return id;
  }

  function saveCodeTabsStore() {
    localStorage.setItem(LS_KEYS.codeTabsStore, JSON.stringify(codeTabsStore));
  }
  function renderCodeTabs() {
    const codeTabBar = document.querySelector('.code-tab-bar');
    // Remove all except newCodeButton
    [...codeTabBar.children].forEach(c => {
      if(c.id !== 'newCodeButton') c.remove();
    });
    Object.keys(codeTabsStore).forEach((id, i) => {
      const tabDiv = document.createElement('div');
      tabDiv.classList.add('code-tab');
      tabDiv.textContent = `Tab ${i + 1}`;
      if(id === currentCodeTabId) tabDiv.classList.add('active');
      tabDiv.dataset.tabId = id;
      tabDiv.tabIndex = 0;
      // Close button
      const closeBtn = document.createElement('span');
      closeBtn.className = 'close-tab';
      closeBtn.textContent = 'x';
      closeBtn.title = 'Close tab';
      closeBtn.onclick = (e) => {
        e.stopPropagation();
        delete codeTabsStore[id];
        if(currentCodeTabId === id) currentCodeTabId = Object.keys(codeTabsStore)[0] || createNewCodeTab();
        saveCodeTabsStore();
        renderCodeTabs();
        loadCurrentTab();
        showToast('Code tab closed', 'error');
      };
      tabDiv.appendChild(closeBtn);
      tabDiv.onclick = () => {
        currentCodeTabId = id;
        renderCodeTabs();
        loadCurrentTab();
      };
      tabDiv.onkeydown = e => {
        if(e.key === 'Enter' || e.key === ' ') tabDiv.onclick();
      };
      codeTabBar.insertBefore(tabDiv, newCodeButton);
    });
  }
  function loadCurrentTab() {
    if(!currentCodeTabId) {
      consoleInput.value = '';
      return;
    }
    consoleInput.value = codeTabsStore[currentCodeTabId];
    consoleInput.focus();
  }

  newCodeButton.onclick = createNewCodeTab;

  // Save current tab code
  function saveCurrentCodeTab() {
    if(!currentCodeTabId) return;
    codeTabsStore[currentCodeTabId] = consoleInput.value;
    saveCodeTabsStore();
    showToast('Code saved', 'success');
  }

  // Delete all tabs
  function deleteAllCodeTabs() {
    if(!confirm('Delete all saved code tabs?')) return;
    codeTabsStore = {};
    currentCodeTabId = null;
    saveCodeTabsStore();
    renderCodeTabs();
    loadCurrentTab();
    showToast('All code tabs deleted', 'error');
  }

  // Download current code
  function downloadCodeToFile() {
    if(!currentCodeTabId) {
      showToast('No code to download', 'error');
      return;
    }
    const blob = new Blob([consoleInput.value], {type: 'text/plain'});
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `code_${currentCodeTabId}.txt`;
    a.click();
    showToast('Code downloaded', 'success');
  }

  // Upload code from file
  function uploadCodeFromFile() {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.txt,.js,.html';
    fileInput.onchange = () => {
      const file = fileInput.files[0];
      if(!file) return;
      const reader = new FileReader();
      reader.onload = () => {
        consoleInput.value = reader.result;
        showToast('Code loaded from file', 'success');
      };
      reader.readAsText(file);
    };
    fileInput.click();
  }

  // Run console input
  async function runConsoleInput(code, rawMode) {
    saveCurrentCodeTab();
    clearConsoleOutput();
    if(rawMode) {
      if(/<\s*!DOCTYPE|<html/i.test(code.trim())) {
        // Open in new tab
        const win = window.open();
        if(win) {
          win.document.write(code);
          win.document.close();
          logToConsole('HTML payload opened in new tab');
        } else {
          logToConsole('Popup blocked by browser', 'error');
        }
        return;
      }
      try {
        const result = evalWithProtection(code);
        if(result !== undefined) logToConsole(result);
        else logToConsole('JS code executed');
      } catch(e) {
        logToConsole(`Error: ${e.message}`, 'error');
      }
    } else {
      // API mode
      try {
        const res = runInternalAPICommands(code);
        if(res !== undefined) logToConsole(res);
        else logToConsole('API command executed');
      } catch(e) {
        logToConsole(`API error: ${e.message}`, 'error');
      }
    }
  }

  // Evaluate code safely with error catches and auto-fixes
  function evalWithProtection(code) {
    try {
      // Could extend with more clever error fixes here
      return new Function(code)();
    } catch(e) {
      logToConsole('Execution error: ' + e.message, 'error');
      // Try simple fix: if missing semicolon at end, retry once
      if(!code.trim().endsWith(';')) {
        return new Function(code + ';')();
      }
      throw e;
    }
  }

  // Log messages to console UI
  function logToConsole(msg, type = 'info') {
    const now = new Date();
    const color = {
      error: '#e74c3c',
      warn: '#f39c12',
      info: '#3498db',
      success: '#27ae60'
    }[type] || '#ddd';
    consoleOutput.innerHTML += `<span style="color:${color}">[${now.toLocaleTimeString()}] ${msg}</span>\n`;
    consoleOutput.scrollTop = consoleOutput.scrollHeight;
  }

  // Clear console output
  function clearConsoleOutput() {
    consoleOutput.innerHTML = '';
  }

  // Internal API commands handler
  function runInternalAPICommands(cmd) {
    // cmd: string like "api.goto('gamePage1')" etc
    // For security: Limit to exposed API only and simple eval
    const api = {
      goto: page => {
        if(['gamePage1','gamePage2','youtubeEmbedUI','consoleUI','settingsUI','none'].includes(page)) {
          // Show desired UI
          gamePage1.style.display = gamePage2.style.display = 'none';
          settingsUI.classList.remove('active');
          youtubeEmbedUI.classList.remove('active');
          consoleUI.classList.remove('active');
          if(page === 'gamePage1') gamePage1.style.display = 'block';
          else if(page === 'gamePage2') gamePage2.style.display = 'block';
          else if(page === 'youtubeEmbedUI') youtubeEmbedUI.classList.add('active');
          else if(page === 'consoleUI') consoleUI.classList.add('active');
          else if(page === 'settingsUI') settingsUI.classList.add('active');
          return `Navigated to ${page}`;
        }
        throw new Error('Unknown UI panel ' + page);
      },
      toggle: panel => {
        if(panel === 'darkMode') {
          darkModeToggle.checked = !darkModeToggle.checked;
          darkModeToggle.dispatchEvent(new Event('change'));
          return `Dark mode toggled ${darkModeToggle.checked}`;
        }
        if(panel === 'settingsUI' || panel === 'youtubeEmbedUI' || panel === 'consoleUI') {
          const ui = {settingsUI, youtubeEmbedUI, consoleUI}[panel];
          if(ui.classList.contains('active')) ui.classList.remove('active');
          else ui.classList.add('active');
          return `${panel} toggled`;
        }
        throw new Error('Unknown panel to toggle: ' + panel);
      },
      gamesList: () => {
        let text = 'Games list:\n';
        gameLists.forEach((list, idx) => {
          text += `Page ${idx+1}:\n`;
          list.games.forEach(g => {
            text += ` - ${g[0]} (${g[1]})\n`;
          });
        });
        return text;
      },
      playVideo: (videoID) => {
        if(typeof videoID !== 'string') throw new Error('Video ID must be a string.');
        currentVideoId = videoID;
        playlist = [videoID];
        currentPlaylistIndex = 0;
        embedYouTubeVideo(videoID);
        return `Playing video ${videoID}`;
      },
      likeVideo: (videoID) => {
        if(typeof videoID !== 'string') throw new Error('Video ID must be a string.');
        likedVideos[videoID] = true;
        localStorage.setItem(LS_KEYS.likedVideos, JSON.stringify(likedVideos));
        listLikedVideos();
        return `Video ${videoID} liked.`;
      },
      showToast: (msg, type='info') => {
        showToast(msg, type);
        return 'Toast shown: ' + msg;
      },
      addButton: (label, parent='ytControlButtons', callbackName=null) => {
        // e.g. api.addButton('MyBtn')
        if(typeof label !== 'string') throw new Error('Label must be string');
        const parentEl = document.getElementById(parent);
        if(!parentEl) throw new Error(`Parent element ${parent} not found.`);
        const btn = document.createElement('button');
        btn.textContent = label;
        btn.style.background = 'var(--button-bg)';
        btn.style.color = 'var(--button-fg)';
        btn.onclick = () => {
          if(callbackName && api[callbackName]) api[callbackName]();
          else showToast(`Button '${label}' clicked.`);
        };
        parentEl.appendChild(btn);
        return `Button '${label}' added to ${parent}`;
      }
    };

    // Execute cmd string with sandboxed API
    const func = new Function('api', `return ${cmd};`);
    return func(api);
  }

  // === Games list keyboard navigation support ===
  // Additional feature – we'll keep the DOM native focus support for accessibility.

  // === Games list page navigation
  // Kept as is from earlier

  // === Save and fill games list on start
  // Already defined earlier

  // === Utilities ===
  function showSidePanelCheckToggle() {
    // Show side panel if there're liked videos or playlists else hide toggle
    const hasLikes = Object.keys(likedVideos).length > 0;
    const hasPlaylists = Object.keys(savedPlaylists).length > 0;
    ytSidePanelToggle.style.display = hasLikes || hasPlaylists ? 'block' : 'none';
  }

  // === Initialization ===

  function initYoutubePlayerControls() {
    setupBackgroundAnimation(selectedTheme); // Load background

    themeCycleToggle.checked = themeCycle;
    if(themeCycle && !backgroundCycleTimer) startThemeCycle();

    // Setup Youtube control nav button disable states
    updatePlayerControlsState();
  }

  // === Utility loading stored favorites, playlists, liked videos on start
  function loadStoredData() {
    try {
      favoritesList = JSON.parse(localStorage.getItem(LS_KEYS.favoritesList)) || [];
      likedVideos = JSON.parse(localStorage.getItem(LS_KEYS.likedVideos)) || {};
      savedPlaylists = JSON.parse(localStorage.getItem(LS_KEYS.savedPlaylists)) || {};
      gameOrder = JSON.parse(localStorage.getItem(LS_KEYS.gameOrder)) || [];
      codeTabsStore = JSON.parse(localStorage.getItem(LS_KEYS.codeTabsStore)) || {};
      consoleSettings = JSON.parse(localStorage.getItem(LS_KEYS.consoleSettings)) || {};
    } catch(e) {
      favoritesList = [];
      likedVideos = {};
      savedPlaylists = {};
      gameOrder = [];
      codeTabsStore = {};
      consoleSettings = {};
    }
  }

  // Initialize
  loadStoredData();

  function unlockAllUI() {
    showGamesList(1);
    youtubeEmbedUI.classList.remove('active');
    consoleUI.classList.remove('active');
    settingsUI.classList.remove('active');
  }

  function unlockPage() {
    sessionStorage.setItem(currentSessionKey, 'true');
    localStorage.setItem(currentSessionKey + '_start', Date.now());
    unlockAllUI();
  }

})();
</script>

</body>
</html>