Guest User

Untitled

a guest
Apr 1st, 2026
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         xAI Pro Studio Frontend (v28.2 - Auto-Retry Fix & Edit Flow + Ref Preview)
  3. // @namespace    http://tampermonkey.net/
  4. // @version      28.2
  5. // @description  Full-Screen UI, Exif Fix, Multi-Image Routing, Dynamic Prompts, Raw PNG Mode, Auto-Retry Moderation, Instant Edit Button, Tag Previews
  6. // @match        https://console.x.ai/playground/imagine*
  7. // @match        https://console.x.ai/team/*/imagine*
  8. // @grant        GM_xmlhttpRequest
  9. // @run-at       document-start
  10. // ==/UserScript==
  11.  
  12. (function() {
  13.     'use strict';
  14.  
  15.     // ─── UTILITIES & DATA STORAGE ─────────────────────────────────────────────
  16.     const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  17.     function pad2(n) { return String(n).padStart(2, '0'); }
  18.     function makeTimestamp() {
  19.         const d = new Date();
  20.         return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}-${pad2(d.getMinutes())}-${pad2(d.getSeconds())}`;
  21.     }
  22.     const DOWNLOAD_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>`;
  23.     const EDIT_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`;
  24.  
  25.     // Load Settings
  26.     let appSettings = JSON.parse(localStorage.getItem('xai_api_settings') || '{}');
  27.     appSettings.retries = parseInt(appSettings.retries) || 20;
  28.     appSettings.delayMin = parseInt(appSettings.delayMin) || 2000;
  29.     appSettings.delayMax = parseInt(appSettings.delayMax) || 4000;
  30.     if (typeof appSettings.notifications === 'undefined') appSettings.notifications = true;
  31.     if (typeof appSettings.customCSS === 'undefined') appSettings.customCSS = "";
  32.     if (typeof appSettings.saveAsPng === 'undefined') appSettings.saveAsPng = false;
  33.     if (typeof appSettings.apiBaseUrl === 'undefined') appSettings.apiBaseUrl = "";
  34.     if (typeof appSettings.videoPollTimeout === 'undefined') appSettings.videoPollTimeout = 300;
  35.     if (typeof appSettings.autoRetryStuckVideo === 'undefined') appSettings.autoRetryStuckVideo = false;
  36.  
  37.     let favoritePrompts = JSON.parse(localStorage.getItem('xai_api_favs') || '[]');
  38.  
  39.     // API URL Helper
  40.     function getApiUrl(path) {
  41.         let base = appSettings.apiBaseUrl || '';
  42.         if (base.endsWith('/')) base = base.slice(0, -1);
  43.         if (!path.startsWith('/') && base) path = '/' + path;
  44.         return base + path;
  45.     }
  46.  
  47.     // ─── DYNAMIC PROMPT PARSER (SPINTAX & RANDOM SEED) ────────────────────────
  48.     function parseDynamicPrompt(text) {
  49.         if (!text) return text;
  50.  
  51.         let parsed = text;
  52.         let prev;
  53.         do {
  54.             prev = parsed;
  55.             parsed = parsed.replace(/\{([^{}]+)\}/g, (match, contents) => {
  56.                 if (contents.includes('|')) {
  57.                     const options = contents.split('|');
  58.                     return options[Math.floor(Math.random() * options.length)];
  59.                 }
  60.                 return match;
  61.             });
  62.         } while (parsed !== prev);
  63.  
  64.         parsed = parsed.replace(/@randomseed/gi, () => {
  65.             return Math.floor(1000000000 + Math.random() * 9000000000).toString();
  66.         });
  67.  
  68.         return parsed.trim();
  69.     }
  70.  
  71.     // ─── BACKGROUND ALERT SYSTEM (AUDIO + TAB BLINK) ──────────────────────────
  72.     let sharedAudioCtx = null;
  73.     let titleBlinkInterval = null;
  74.     const originalTitle = document.title || "xAI Pro Studio";
  75.  
  76.     function initAudio() {
  77.         if (!sharedAudioCtx && appSettings.notifications) {
  78.             try { sharedAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); }
  79.             catch(e) { console.warn("AudioContext not supported"); }
  80.         }
  81.         if (sharedAudioCtx && sharedAudioCtx.state === 'suspended') sharedAudioCtx.resume();
  82.     }
  83.  
  84.     function notifyUser(isError = false) {
  85.         if (!appSettings.notifications) return;
  86.  
  87.         if (sharedAudioCtx) {
  88.             try {
  89.                 const osc = sharedAudioCtx.createOscillator();
  90.                 const gain = sharedAudioCtx.createGain();
  91.                 osc.connect(gain);
  92.                 gain.connect(sharedAudioCtx.destination);
  93.  
  94.                 if (isError) {
  95.                     osc.type = 'sawtooth';
  96.                     osc.frequency.setValueAtTime(300, sharedAudioCtx.currentTime);
  97.                     osc.frequency.exponentialRampToValueAtTime(100, sharedAudioCtx.currentTime + 0.3);
  98.                 } else {
  99.                     osc.type = 'sine';
  100.                     osc.frequency.setValueAtTime(500, sharedAudioCtx.currentTime);
  101.                     osc.frequency.exponentialRampToValueAtTime(1000, sharedAudioCtx.currentTime + 0.2);
  102.                 }
  103.  
  104.                 gain.gain.setValueAtTime(0.1, sharedAudioCtx.currentTime);
  105.                 gain.gain.exponentialRampToValueAtTime(0.01, sharedAudioCtx.currentTime + 0.5);
  106.  
  107.                 osc.start(sharedAudioCtx.currentTime);
  108.                 osc.stop(sharedAudioCtx.currentTime + 0.5);
  109.             } catch(e) {}
  110.         }
  111.  
  112.         if (!document.hasFocus()) {
  113.             if (titleBlinkInterval) clearInterval(titleBlinkInterval);
  114.             let toggle = true;
  115.             titleBlinkInterval = setInterval(() => {
  116.                 document.title = toggle ? (isError ? "❌ FAILED" : "✅ DONE") : originalTitle;
  117.                 toggle = !toggle;
  118.             }, 1000);
  119.  
  120.             const clearBlink = () => {
  121.                 clearInterval(titleBlinkInterval);
  122.                 document.title = originalTitle;
  123.                 window.removeEventListener('focus', clearBlink);
  124.             };
  125.             window.addEventListener('focus', clearBlink);
  126.         }
  127.     }
  128.  
  129.     // ─── STEALTH IDENTITY RESETTER ────────────────────────────────────────────
  130.     function stealthIdentityReset() {
  131.         const trackingCookies =['x-anonuserid', 'mixpanel', 'mp_', 'distinct_id'];
  132.         document.cookie.split(';').forEach(c => {
  133.             const name = c.split('=')[0].trim();
  134.             if (trackingCookies.some(tc => name.includes(tc))) {['.x.ai', 'console.x.ai', ''].forEach(d => {['/', '/playground/imagine', ''].forEach(p => {
  135.                         document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${p}${d ? ';domain=' + d : ''}`;
  136.                     });
  137.                 });
  138.             }
  139.         });
  140.  
  141.         for (let i = localStorage.length - 1; i >= 0; i--) {
  142.             const k = localStorage.key(i);
  143.             if (k && !k.startsWith('xai_api_') && trackingCookies.some(tc => k.includes(tc))) {
  144.                 localStorage.removeItem(k);
  145.             }
  146.         }
  147.     }
  148.  
  149.     // ─── EXIF LIBRARY LOADER & WINDOWS METADATA ENCODER ───────────────────────
  150.     let piexifLoaded = false;
  151.     function loadPiexif() {
  152.         if (piexifLoaded) return Promise.resolve(window.piexif);
  153.         return new Promise(resolve => {
  154.             const script = document.createElement('script');
  155.             script.src = 'https://cdn.jsdelivr.net/npm/piexifjs';
  156.             script.onload = () => { piexifLoaded = true; resolve(window.piexif); };
  157.             document.head.appendChild(script);
  158.         });
  159.     }
  160.  
  161.     function toUTF16LE(str) {
  162.         const arr =[];
  163.         for (let i = 0; i < str.length; i++) {
  164.             const code = str.charCodeAt(i);
  165.             arr.push(code & 0xFF); arr.push((code >> 8) & 0xFF);
  166.         }
  167.         arr.push(0, 0); return arr;
  168.     }
  169.  
  170.     function convertToJpegWithExif(base64PngUri, prompt) {
  171.         return new Promise((resolve, reject) => {
  172.             const img = new Image();
  173.             img.onload = async () => {
  174.                 const canvas = document.createElement('canvas');
  175.                 canvas.width = img.width; canvas.height = img.height;
  176.                 const ctx = canvas.getContext('2d');
  177.                 ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height);
  178.                 ctx.drawImage(img, 0, 0);
  179.  
  180.                 let jpegUri = canvas.toDataURL('image/jpeg', 0.95);
  181.                 if (prompt) {
  182.                     try {
  183.                         const piexif = await loadPiexif();
  184.                         const exifObj = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "Interop": {}};
  185.                         const safePrompt = unescape(encodeURIComponent(prompt));
  186.                         exifObj['0th'][piexif.ImageIFD.ImageDescription] = safePrompt;
  187.  
  188.                         const utf16Prompt = toUTF16LE(prompt);
  189.                         exifObj['0th'][40091] = utf16Prompt;
  190.                         exifObj['0th'][40092] = utf16Prompt;
  191.                         exifObj['0th'][40093] = utf16Prompt;
  192.  
  193.                         jpegUri = piexif.insert(piexif.dump(exifObj), jpegUri);
  194.                     } catch (e) {}
  195.                 }
  196.                 resolve(jpegUri);
  197.             };
  198.             img.onerror = reject; img.src = base64PngUri;
  199.         });
  200.     }
  201.  
  202.     async function extractPromptFromImage(file) {
  203.         if (!file.type.includes('image')) return null;
  204.         try {
  205.             const piexif = await loadPiexif();
  206.             return new Promise((resolve) => {
  207.                 const reader = new FileReader();
  208.                 reader.onload = (e) => {
  209.                     try {
  210.                         const exifData = piexif.load(e.target.result);
  211.                         let prompt = exifData['0th'] && exifData['0th'][piexif.ImageIFD.ImageDescription];
  212.                         if (Array.isArray(prompt)) prompt = String.fromCharCode.apply(null, prompt).replace(/\0/g, '');
  213.                         if (prompt) { try { prompt = decodeURIComponent(escape(prompt)); } catch(e) {} }
  214.  
  215.                         if (!prompt && exifData['0th'] && exifData['0th'][40091]) {
  216.                             const xpTitleArr = exifData['0th'][40091];
  217.                             let str = '';
  218.                             for (let i = 0; i < xpTitleArr.length; i += 2) {
  219.                                 const charCode = xpTitleArr[i] | (xpTitleArr[i+1] << 8);
  220.                                 if (charCode === 0) break;
  221.                                 str += String.fromCharCode(charCode);
  222.                             }
  223.                             prompt = str;
  224.                         }
  225.                         resolve(prompt ? prompt.trim() : null);
  226.                     } catch (err) { resolve(null); }
  227.                 };
  228.                 reader.readAsDataURL(file);
  229.             });
  230.         } catch (e) { return null; }
  231.     }
  232.  
  233.     // ─── VIDEO THUMBNAIL EXTRACTOR ────────────────────────────────────────────
  234.     function generateVideoThumbnail(file) {
  235.         return new Promise((resolve) => {
  236.             const video = document.createElement('video');
  237.             video.preload = 'metadata';
  238.             video.muted = true;
  239.             video.playsInline = true;
  240.  
  241.             const url = URL.createObjectURL(file);
  242.             video.src = url;
  243.  
  244.             let isSeeked = false;
  245.  
  246.             video.onloadeddata = () => {
  247.                 video.currentTime = Math.min(0.5, video.duration / 2 || 0);
  248.             };
  249.  
  250.             video.onseeked = () => {
  251.                 if (isSeeked) return;
  252.                 isSeeked = true;
  253.                 try {
  254.                     const canvas = document.createElement('canvas');
  255.                     canvas.width = video.videoWidth || 140;
  256.                     canvas.height = video.videoHeight || 140;
  257.                     const ctx = canvas.getContext('2d');
  258.                     ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  259.                     URL.revokeObjectURL(url);
  260.                     resolve(canvas.toDataURL('image/jpeg', 0.8));
  261.                 } catch(e) {
  262.                     URL.revokeObjectURL(url);
  263.                     resolve(null);
  264.                 }
  265.             };
  266.  
  267.             video.onerror = () => {
  268.                 URL.revokeObjectURL(url);
  269.                 resolve(null);
  270.             };
  271.  
  272.             setTimeout(() => { if (!isSeeked) { URL.revokeObjectURL(url); resolve(null); } }, 2000);
  273.         });
  274.     }
  275.  
  276.     // ─── ASPECT RATIO DATA ────────────────────────────────────────────────────
  277.     const arData =[
  278.         { label: 'Auto', w: 1, h: 1, isAuto: true },
  279.         { label: '1:1', w: 1, h: 1 }, { label: '3:4', w: 3, h: 4 }, { label: '4:3', w: 4, h: 3 },
  280.         { label: '9:16', w: 9, h: 16 }, { label: '16:9', w: 16, h: 9 }, { label: '2:3', w: 2, h: 3 },
  281.         { label: '3:2', w: 3, h: 2 }, { label: '9:19.5', w: 9, h: 19.5 }, { label: '19.5:9', w: 19.5, h: 9 },
  282.         { label: '9:20', w: 9, h: 20 }, { label: '20:9', w: 20, h: 9 }, { label: '1:2', w: 1, h: 2 }, { label: '2:1', w: 2, h: 1 }
  283.     ];
  284.  
  285.     function createArIcon(w, h, isAuto) {
  286.         if (isAuto) return `<div style="width: 12px; height: 12px; border: 1px dashed #64748b; border-radius: 2px; display: flex; align-items: center; justify-content: center; font-size: 9px; color: #94a3b8;">A</div>`;
  287.         const scale = 12 / Math.max(w, h);
  288.         return `<div style="width: 14px; height: 14px; display: flex; align-items: center; justify-content: center;"><div style="width: ${w * scale}px; height: ${h * scale}px; border: 1.5px solid #cbd5e1; border-radius: 2px;"></div></div>`;
  289.     }
  290.  
  291.     // ─── UI INJECTION (COMPACT CSS) ───────────────────────────────────────────
  292.     const UI_CSS = `
  293.         ::-webkit-scrollbar { width: 6px; }
  294.         ::-webkit-scrollbar-track { background: #0f172a; }
  295.         ::-webkit-scrollbar-thumb { background: #475569; border-radius: 6px; }
  296.  
  297.         @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  298.         @keyframes pulse { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
  299.  
  300.         .loading-spinner { width: 14px; height: 14px; border: 2px solid rgba(255,255,255,0.3); border-top-color: #fff; border-radius: 50%; animation: spin 1s linear infinite; flex-shrink: 0; }
  301.         .btn-content { display: flex; align-items: center; justify-content: center; gap: 6px; }
  302.         .status-pulsing { animation: pulse 2s ease-in-out infinite; color: #3b82f6 !important; font-weight: 600; }
  303.  
  304.         #xai-pro-app { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 9999999; background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); font-family: 'Inter', -apple-system, sans-serif; color: #e2e8f0; display: flex; gap: 10px; padding: 10px; box-sizing: border-box; }
  305.         #xai-pro-app * { box-sizing: border-box; }
  306.  
  307.         .panel { background: #1e293b; border-radius: 10px; border: 1px solid #334155; box-shadow: 0 4px 15px rgba(0,0,0,0.4); display: flex; flex-direction: column; overflow: hidden; }
  308.         .panel-title { font-size: 11px; font-weight: 700; color: #94a3b8; letter-spacing: 0.5px; padding: 10px; border-bottom: 1px solid #334155; text-transform: uppercase; }
  309.  
  310.         .col-left { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; }
  311.         .col-center { flex: 1; display: flex; flex-direction: column; gap: 10px; min-width: 0; min-height: 0; }
  312.         .col-right { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; transition: 0.2s; }
  313.         .col-right.drag-over { background: #064e3b; border-color: #10b981; box-shadow: 0 0 0 4px rgba(16,185,129,0.15); border-radius: 10px; }
  314.  
  315.         textarea, select, input[type="text"], input[type="number"], input[type="checkbox"] { background: #0f172a; border: 1px solid #334155; border-radius: 6px; padding: 8px; color: #f8fafc; font-size: 13px; outline: none; transition: 0.2s; color-scheme: dark; }
  316.         textarea, select, input[type="text"], input[type="number"] { width: 100%; }
  317.         textarea:focus, select:focus, input[type="text"]:focus, input[type="number"]:focus { border-color: #64748b; background: #1e293b; box-shadow: 0 0 0 2px rgba(100,116,139,0.2); }
  318.         label { font-size: 11px; font-weight: 600; color: #94a3b8; margin-bottom: 4px; display: block; }
  319.  
  320.         .btn-primary { background: linear-gradient(180deg, #6366f1 0%, #4f46e5 100%); color: #fff; border: none; border-radius: 6px; padding: 8px 14px; font-size: 13px; font-weight: 600; cursor: pointer; transition: 0.2s; box-shadow: 0 2px 4px rgba(0,0,0,0.3); display: flex; justify-content: center; align-items: center; }
  321.         .btn-primary:hover:not(:disabled) { background: linear-gradient(180deg, #4f46e5 0%, #4338ca 100%); transform: translateY(-1px); }
  322.         .btn-primary:disabled { opacity: 0.8; cursor: not-allowed; }
  323.  
  324.         .btn-secondary { background: #1e293b; color: #cbd5e1; border: 1px solid #475569; border-radius: 6px; padding: 8px 14px; font-size: 13px; font-weight: 600; cursor: pointer; transition: 0.2s; display: flex; justify-content: center; align-items: center; }
  325.         .btn-secondary:hover:not(:disabled) { background: #334155; border-color: #64748b; }
  326.  
  327.         .ar-select-box { background: #0f172a; border: 1px solid #334155; border-radius: 6px; padding: 8px; display: flex; align-items: center; gap: 8px; cursor: pointer; color: #f8fafc; font-size: 13px; }
  328.         #ar-options-container { position: fixed; background: #1e293b; border: 1px solid #334155; border-radius: 6px; box-shadow: 0 10px 25px rgba(0,0,0,0.4); max-height: 250px; overflow-y: auto; display: none; z-index: 99999999; }
  329.         .ar-option { display: flex; align-items: center; gap: 8px; padding: 6px 8px; cursor: pointer; font-size: 12px; color: #cbd5e1; }
  330.         .ar-option:hover { background: #334155; color: #f8fafc; }
  331.  
  332.         .img-wrapper { position: relative; display: block; }
  333.         .zoomable { cursor: zoom-in; transition: transform 0.2s; width: 100%; display: block; }
  334.  
  335.         .overlay-btn { position: absolute; top: 6px; background: rgba(15, 23, 42, 0.6); color: white; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; text-decoration: none; backdrop-filter: blur(4px); transition: 0.2s; opacity: 0.75; z-index: 50; cursor: pointer; border: none; padding: 0; }
  336.         .overlay-btn:hover { background: rgba(15, 23, 42, 0.9); opacity: 1; transform: scale(1.05); }
  337.         .overlay-dl-btn { right: 6px; }
  338.         .overlay-edit-btn { right: 40px; color: #10b981; }
  339.  
  340.         .ref-item { display: flex; align-items: center; gap: 10px; padding: 8px; background: #1e293b; border: 1px solid #334155; border-radius: 6px; margin-bottom: 6px; cursor: grab; box-shadow: 0 2px 4px rgba(0,0,0,0.2); transition: 0.1s; }
  341.         .ref-item.inactive { opacity: 0.6; filter: grayscale(0.8); }
  342.         .ref-item:active { cursor: grabbing; }
  343.         .ref-item.dragging { opacity: 0.4; }
  344.         .ref-handle { font-size: 14px; color: #475569; cursor: grab; padding: 0 4px; }
  345.         .ref-thumb { width: 90px; height: 90px; border-radius: 4px; object-fit: cover; border: 1px solid #334155; background: #0f172a; transition: 0.2s; }
  346.         .ref-info { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 6px; min-width: 0; }
  347.         .ref-toggle-label { font-size: 11px; color: #cbd5e1; display: flex; align-items: center; gap: 4px; cursor: pointer; user-select: none; }
  348.         .ref-toggle-label input { width: 12px; height: 12px; cursor: pointer; accent-color: #10b981; margin: 0; padding: 0; }
  349.         .ref-btn-group { display: flex; gap: 4px; width: 100%; margin-top: auto; }
  350.         .ref-action-btn { flex: 1; border-radius: 4px; padding: 4px 0; cursor: pointer; font-size: 10px; transition: 0.2s; font-weight: bold; text-align: center; }
  351.         .ref-insert { background: #0f766e; color: #ccfbf1; border: 1px solid #115e59; }
  352.         .ref-insert:hover { background: #115e59; color: #f0fdfa; }
  353.         .ref-del { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
  354.         .ref-del:hover { background: #7f1d1d; color: #fee2e2; }
  355.         .drag-over-top { border-top: 2px solid #22c55e !important; }
  356.         .drag-over-bottom { border-bottom: 2px solid #22c55e !important; }
  357.  
  358.         .history-card { background: #0f172a; border: 1px solid #334155; border-radius: 6px; overflow: hidden; margin-bottom: 10px; }
  359.         .history-card .overlay-btn { width: 24px; height: 24px; top: 4px; border-radius: 4px; }
  360.         .history-card .overlay-dl-btn { right: 4px; }
  361.         .history-card .overlay-edit-btn { right: 32px; }
  362.         .history-card p { padding: 8px; margin: 0; font-size: 11px; color: #94a3b8; cursor: pointer; transition: 0.2s; }
  363.         .history-card p:hover { background: #1e293b; color: #e2e8f0; }
  364.  
  365.         .current-card { border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.3); border: 1px solid #334155; background: #1e293b; }
  366.         .current-card img, .current-card video { max-height: 50vh; object-fit: contain; background: #0f172a; }
  367.  
  368.         /* Modals Generic Classes */
  369.         .modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 999999999; display: none; justify-content: center; align-items: center; backdrop-filter: blur(5px); }
  370.         .modal-box { background: #1e293b; border-radius: 10px; width: 500px; max-width: 90vw; padding: 15px; display: flex; flex-direction: column; gap: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); border: 1px solid #334155; max-height: 90vh; }
  371.         .fav-item { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 8px; border-radius: 6px; border: 1px solid #334155; }
  372.         .fav-text { flex: 1; font-size: 12px; color: #cbd5e1; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-right: 10px; transition: color 0.2s; }
  373.         .fav-text:hover { color: #10b981; }
  374.  
  375.         #settings-btn { position: fixed; top: 10px; right: 15px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
  376.         #settings-btn:hover { transform: rotate(45deg); opacity: 1; }
  377.  
  378.         #xai-lightbox { cursor: zoom-out; }
  379.         #xai-lightbox-wrapper { position: relative; display: inline-block; max-width: 95vw; max-height: 95vh; }
  380.         #xai-lightbox-img { max-width: 100%; max-height: 95vh; display: block; border-radius: 8px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); }
  381.  
  382.         /* NEW PROMPT CONTAINER CSS (For hover previews) */
  383.         .prompt-container { position: relative; width: 100%; height: 100px; min-height: 70px; margin-bottom: 10px; resize: vertical; overflow: hidden; border: 1px solid #334155; border-radius: 6px; background: #0f172a; transition: 0.2s; box-sizing: border-box; font-family: 'Inter', -apple-system, sans-serif; }
  384.         .prompt-container:focus-within { border-color: #64748b; background: #1e293b; box-shadow: 0 0 0 2px rgba(100,116,139,0.2); }
  385.         .prompt-container.prompt-drag-over { border-color: #10b981 !important; background: #064e3b !important; box-shadow: 0 0 0 2px rgba(16,185,129,0.15) !important; }
  386.  
  387.         #prompt-backdrop { position: absolute; top: 0; left: 0; right: 0; bottom: 0; padding: 8px; font-size: 13px; font-family: inherit; white-space: pre-wrap; word-wrap: break-word; overflow-y: auto; color: transparent; z-index: 1; opacity: 0; box-sizing: border-box; pointer-events: none; }
  388.         .prompt-tag { pointer-events: auto; }
  389.  
  390.         #xai-api-prompt { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; resize: none; background: transparent; border: none; box-shadow: none; outline: none; padding: 8px; font-size: 13px; font-family: inherit; color: #f8fafc; box-sizing: border-box; margin: 0; }
  391.         #xai-api-prompt:focus { background: transparent; border: none; box-shadow: none; }
  392.     `;
  393.  
  394.     const UI_HTML = `
  395.         <div id="xai-pro-app">
  396.             <div id="settings-btn" title="Studio Settings">⚙️</div>
  397.  
  398.             <!-- LEFT COLUMN -->
  399.             <div class="col-left">
  400.                 <div class="panel" style="flex-shrink: 0;">
  401.                     <div style="display: flex; background: rgba(0,0,0,0.2); border-radius: 0 0 6px 6px; margin-bottom: 10px; border-bottom: 1px solid #334155; padding: 10px;">
  402.                         <div style="flex: 1;">
  403.                             <label>Master Action</label>
  404.                             <select id="master-action" style="font-weight: bold; color: #f8fafc; border-color: #475569; box-shadow: 0 2px 4px rgba(0,0,0,0.3);">
  405.                                 <option value="gen_image">🖼️ Generate Image</option>
  406.                                 <option value="gen_video">🎥 Generate Video</option>
  407.                                 <option value="edit_video">✂️ Edit Video</option>
  408.                                 <option value="extend_video">➡️ Extend Video</option>
  409.                             </select>
  410.                         </div>
  411.                     </div>
  412.  
  413.                     <div style="padding: 10px; display: flex; flex-direction: column; gap: 10px;">
  414.                         <div id="setting-ar">
  415.                             <label>Aspect Ratio</label>
  416.                             <div class="ar-select-box" id="ar-select-box">
  417.                                 <div id="ar-selected-icon"></div>
  418.                                 <span id="ar-selected-text">Auto</span>
  419.                             </div>
  420.                         </div>
  421.  
  422.                         <div style="display: flex; gap: 8px;">
  423.                             <div id="setting-res-img" style="flex: 1;">
  424.                                 <label>Resolution</label>
  425.                                 <select id="xai-api-res-img">
  426.                                     <option value="2k" selected>2K (Pro)</option>
  427.                                     <option value="1k">1K</option>
  428.                                 </select>
  429.                             </div>
  430.                             <div id="setting-res-vid" style="flex: 1; display: none;">
  431.                                 <label>Resolution</label>
  432.                                 <select id="xai-api-res-vid">
  433.                                     <option value="720p" selected>720p (HD)</option>
  434.                                     <option value="480p">480p (SD)</option>
  435.                                 </select>
  436.                             </div>
  437.  
  438.                             <div id="setting-batch" style="flex: 1;">
  439.                                 <label>Batch Size</label>
  440.                                 <select id="xai-api-n">
  441.                                     <option value="1" selected>1 Image</option>
  442.                                     <option value="2">2 Images</option>
  443.                                     <option value="3">3 Images</option>
  444.                                     <option value="4">4 Images</option>
  445.                                     <option value="5">5 Images</option>
  446.                                     <option value="8">8 Images</option>
  447.                                     <option value="10">10 Images</option>
  448.                                 </select>
  449.                             </div>
  450.                             <div id="setting-duration" style="flex: 1; display: none;">
  451.                                 <label>Duration</label>
  452.                                 <select id="xai-api-duration">
  453.                                     <option value="5" selected>5 Seconds</option>
  454.                                     <option value="8">8 Seconds</option>
  455.                                     <option value="10">10 Seconds</option>
  456.                                     <option value="12">12 Seconds</option>
  457.                                     <option value="15">15 Seconds</option>
  458.                                     <option value="2">2s Extension</option>
  459.                                     <option value="4">4s Extension</option>
  460.                                     <option value="6">6s Extension</option>
  461.                                 </select>
  462.                             </div>
  463.  
  464.                             <div id="setting-loops" style="flex: 1;">
  465.                                 <label title="How many consecutive API calls to perform in a row">Loops</label>
  466.                                 <input type="number" id="xai-api-loops" value="1" min="1" max="100">
  467.                             </div>
  468.                         </div>
  469.                     </div>
  470.                 </div>
  471.  
  472.                 <div class="panel" style="flex: 1; min-height: 0;">
  473.                     <div class="panel-title" style="display:flex; justify-content: space-between; align-items: center;">
  474.                         <span>Previous Results</span>
  475.                         <span id="xai-reset-btn" style="cursor: pointer; color: #ef4444; text-transform: none; text-decoration: underline;">Wipe Cache</span>
  476.                     </div>
  477.                     <div id="xai-history" style="flex: 1; overflow-y: auto; padding: 10px;">
  478.                         <div style="color: #94a3b8; font-size: 11px; text-align: center; margin-top: 20px;">No history yet.</div>
  479.                     </div>
  480.                 </div>
  481.             </div>
  482.  
  483.             <!-- CENTER COLUMN -->
  484.             <div class="col-center">
  485.                 <div class="panel" style="flex: 1; background: transparent; border: none; box-shadow: none; min-height: 0;">
  486.                     <div class="panel-title" style="background: #1e293b; border-radius: 8px; border: 1px solid #334155; margin-bottom: 10px; flex-shrink: 0;">Current Generation</div>
  487.                     <div id="xai-current-images" style="flex: 1; overflow-y: auto; display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 10px; align-content: start; padding-bottom: 10px;"></div>
  488.                 </div>
  489.  
  490.                 <div class="panel" style="flex-shrink: 0; padding: 12px;">
  491.                     <label style="font-size: 13px; color: #e2e8f0; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
  492.                         <span style="display: flex; align-items: center; gap: 8px;">
  493.                             <span>Prompt</span>
  494.                             <button id="fav-prompts-btn" class="btn-secondary" style="padding: 2px 8px; font-size: 10px; height: 22px;">⭐ Favorites</button>
  495.                         </span>
  496.                         <span style="font-size: 10px; font-weight: 400; color: #94a3b8;">(Drop image here for EXIF)</span>
  497.                     </label>
  498.  
  499.                     <div id="prompt-warning" style="display: none; background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; border-radius: 6px; padding: 6px 10px; font-size: 11px; margin-bottom: 8px; font-weight: 500;">
  500.                         ⚠️ A gentle reminder that --parameter=value has never been shown to do anything at all, including --seed and --sid, but you do you!
  501.                     </div>
  502.  
  503.                     <div class="prompt-container">
  504.                         <div id="prompt-backdrop"></div>
  505.                         <textarea id="xai-api-prompt" placeholder="Describe what you want to see... Supports Spintax {cat|dog} and @randomseed"></textarea>
  506.                     </div>
  507.  
  508.                     <div style="display: flex; align-items: center; justify-content: space-between;">
  509.                         <div id="xai-api-status" style="font-size: 12px; color: #64748b; font-weight: 500;">Ready</div>
  510.                         <div style="display: flex; gap: 8px;">
  511.                             <button id="xai-preview-btn" class="btn-secondary">🔍 Payload</button>
  512.                             <button id="xai-cancel-btn" class="btn-secondary" style="display: none; color: #ef4444; border-color: #ef4444;">🛑 Cancel</button>
  513.                             <button id="xai-api-generate" class="btn-primary" style="width: 120px;"><div class="btn-content">Generate</div></button>
  514.                         </div>
  515.                     </div>
  516.                 </div>
  517.             </div>
  518.  
  519.             <!-- RIGHT COLUMN -->
  520.             <div class="col-right" id="col-right-dropzone">
  521.                 <div class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
  522.                     <div class="panel-title" id="ref-panel-title">Reference Media</div>
  523.                     <div style="padding: 10px; flex: 1; display: flex; flex-direction: column; overflow: hidden;">
  524.                         <div id="xai-upload-placeholder" style="border: 2px dashed #475569; border-radius: 8px; width: 100%; padding: 15px 10px; color: #94a3b8; cursor: pointer; text-align: center; transition: 0.2s; margin-bottom: 10px; background: rgba(0,0,0,0.1);">
  525.                             <div style="font-size: 20px; margin-bottom: 4px;">📥</div>
  526.                             <div style="font-size: 12px; font-weight: 600;">Drag & Drop / Ctrl+V</div>
  527.                         </div>
  528.                         <input type="file" id="xai-api-file" accept="image/*, video/mp4, video/webm" multiple style="display: none;">
  529.                         <div style="font-size: 10px; color: #94a3b8; margin-bottom: 4px; text-transform: uppercase; font-weight: bold; flex-shrink: 0;">Upload Order (Top = First)</div>
  530.                         <div id="xai-ref-list" style="flex: 1; overflow-y: auto; padding-right: 4px;"></div>
  531.                     </div>
  532.                 </div>
  533.             </div>
  534.  
  535.             <!-- FIXED FLOATING DROPDOWN -->
  536.             <div id="ar-options-container"></div>
  537.  
  538.             <!-- MODALS -->
  539.             <div id="xai-lightbox" class="modal-overlay">
  540.                 <div id="xai-lightbox-wrapper">
  541.                     <img id="xai-lightbox-img" src="">
  542.                     <a id="xai-lightbox-dl" href="#" download="" target="_blank" class="overlay-btn overlay-dl-btn" style="top: 15px; right: 15px; width: 44px; height: 44px; border-radius: 50%; background: rgba(0,0,0,0.7);" title="Download File">${DOWNLOAD_ICON}</a>
  543.                 </div>
  544.             </div>
  545.  
  546.             <div id="tag-preview-box" style="position: fixed; display: none; z-index: 99999999; background: #1e293b; border: 1px solid #334155; border-radius: 6px; padding: 4px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); pointer-events: none;">
  547.                 <img id="tag-preview-img" style="max-width: 150px; max-height: 150px; border-radius: 4px; display: block; object-fit: cover;">
  548.             </div>
  549.  
  550.             <!-- SETTINGS MODAL -->
  551.             <div id="xai-settings-modal" class="modal-overlay">
  552.                 <div class="modal-box" style="width: 500px;">
  553.                     <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⚙️ Studio Settings</h3>
  554.                     <div style="display:flex; gap:10px;">
  555.                         <div style="flex:1;">
  556.                             <label>Max Retries</label>
  557.                             <input type="number" id="set-retries" min="1" max="100">
  558.                         </div>
  559.                         <div style="flex:1;">
  560.                             <label>Delay Min (ms)</label>
  561.                             <input type="number" id="set-delay-min" min="500" step="500">
  562.                         </div>
  563.                         <div style="flex:1;">
  564.                             <label>Delay Max (ms)</label>
  565.                             <input type="number" id="set-delay-max" min="1000" step="500">
  566.                         </div>
  567.                     </div>
  568.                     <div>
  569.                         <label>API Base URL (Leave empty for default console.x.ai)</label>
  570.                         <input type="text" id="set-api-base-url" placeholder="e.g., https://api.proxy.com">
  571.                     </div>
  572.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  573.                         <input type="checkbox" id="set-notifications" style="width: 16px; height: 16px;">
  574.                         <label for="set-notifications" style="margin: 0; cursor: pointer;">Enable Notifications (Sound & Tab Blink)</label>
  575.                     </div>
  576.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  577.                         <input type="checkbox" id="set-save-png" style="width: 16px; height: 16px;">
  578.                         <label for="set-save-png" style="margin: 0; cursor: pointer;">Save as Original PNG (Disable JPEG / EXIF Prompt)</label>
  579.                     </div>
  580.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  581.                         <input type="checkbox" id="set-auto-retry-video" style="width: 16px; height: 16px;">
  582.                         <label for="set-auto-retry-video" style="margin: 0; cursor: pointer;">Auto-Retry Stuck Videos (Timeout / Moderated)</label>
  583.                     </div>
  584.                     <div style="margin-top: 4px;">
  585.                         <label>Video Polling Timeout (Seconds)</label>
  586.                         <input type="number" id="set-video-timeout" min="10" step="10">
  587.                     </div>
  588.                     <div>
  589.                         <label>Custom CSS Overrides</label>
  590.                         <textarea id="set-custom-css" style="font-family: monospace; height: 100px; font-size: 11px;" placeholder="/* e.g., #xai-pro-app { background: red; } */"></textarea>
  591.                     </div>
  592.                     <div style="display: flex; gap: 8px; margin-top: 5px;">
  593.                         <button id="save-settings-btn" class="btn-primary" style="flex:1;">Save Settings</button>
  594.                         <button id="close-settings-btn" class="btn-secondary" style="flex:1;">Cancel</button>
  595.                     </div>
  596.                 </div>
  597.             </div>
  598.  
  599.             <!-- FAVORITES MODAL -->
  600.             <div id="xai-fav-modal" class="modal-overlay">
  601.                 <div class="modal-box" style="width: 550px;">
  602.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  603.                         <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⭐ Favorite Prompts</h3>
  604.                         <button id="close-fav-btn" style="background: none; border: none; color: #ef4444; font-size: 20px; cursor: pointer; font-weight: bold; line-height: 1;">&times;</button>
  605.                     </div>
  606.                     <button id="add-current-fav-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);">➕ Save Current Prompt to Favorites</button>
  607.                     <div id="fav-list" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px;"></div>
  608.                 </div>
  609.             </div>
  610.  
  611.             <!-- CUSTOM PAYLOAD DEBUGGER MODAL -->
  612.             <div id="xai-payload-modal" class="modal-overlay">
  613.                 <div class="modal-box" style="width: 550px;">
  614.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  615.                         <h3 style="margin:0; font-size: 15px; color: #f8fafc;">API Payload Debugger</h3>
  616.                         <button id="close-payload-btn" style="background: #ef4444; color: #fff; border: none; border-radius: 6px; padding: 4px 8px; cursor: pointer; font-weight: bold; font-size: 11px;">Close</button>
  617.                     </div>
  618.                     <div><label>Endpoint URL:</label><input type="text" id="payload-endpoint" style="font-family: monospace;" value="/v1/images/generations"></div>
  619.                     <div><label>JSON Payload (Editable):</label><textarea id="payload-code" style="background: #0f172a; color: #e2e8f0; padding: 10px; border-radius: 6px; font-family: monospace; font-size: 12px; height: 250px; resize: vertical; border: 1px solid #334155;"></textarea></div>
  620.                     <button id="send-custom-payload-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);"><div class="btn-content">🚀 Send Custom Payload</div></button>
  621.                     <div id="custom-payload-status" style="font-size: 11px; color: #64748b; text-align: center;">Ready</div>
  622.                 </div>
  623.             </div>
  624.         </div>
  625.     `;
  626.  
  627.     // ─── INITIALIZATION ───────────────────────────────────────────────────────
  628.     let updateUIForEditMedia = null;
  629.  
  630.     const initApp = () => {
  631.         if (!document.body) return setTimeout(initApp, 50);
  632.  
  633.         const hideOriginals = () => {
  634.             Array.from(document.body.children).forEach(child => {
  635.                 if (child.id !== 'xai-pro-app' && !['SCRIPT', 'STYLE', 'LINK'].includes(child.tagName)) {
  636.                     child.style.display = 'none';
  637.                 }
  638.             });
  639.         };
  640.         hideOriginals();
  641.         new MutationObserver(hideOriginals).observe(document.body, { childList: true });
  642.  
  643.         if (!document.getElementById('xai-pro-app')) {
  644.             const style = document.createElement('style');
  645.             style.innerHTML = UI_CSS;
  646.             document.head.appendChild(style);
  647.  
  648.             const customStyle = document.createElement('style');
  649.             customStyle.id = 'xai-custom-css-block';
  650.             customStyle.innerHTML = appSettings.customCSS;
  651.             document.head.appendChild(customStyle);
  652.  
  653.             document.body.insertAdjacentHTML('beforeend', UI_HTML);
  654.             bindLogic();
  655.         }
  656.     };
  657.  
  658.     let referenceMedia =[];
  659.     let currentAr = localStorage.getItem('xai_api_ar') || 'Auto';
  660.     let fullPayloadMemory = {};
  661.     let currentAbortController = null;
  662.     let isRequestCancelled = false;
  663.  
  664.     function saveRefs() {
  665.         try {
  666.             localStorage.setItem('xai_api_refs', JSON.stringify(referenceMedia));
  667.         } catch (e) {
  668.             console.warn("[xAI Studio] Could not save references to localStorage (quota exceeded). Images will not persist after refresh.");
  669.         }
  670.     }
  671.  
  672.     function bindLogic() {
  673.         const els = {
  674.             app: document.getElementById('xai-pro-app'),
  675.             prompt: document.getElementById('xai-api-prompt'),
  676.             promptBackdrop: document.getElementById('prompt-backdrop'),
  677.             promptWarning: document.getElementById('prompt-warning'),
  678.             promptContainer: document.querySelector('.prompt-container'),
  679.             action: document.getElementById('master-action'),
  680.             resImg: document.getElementById('xai-api-res-img'),
  681.             resVid: document.getElementById('xai-api-res-vid'),
  682.             n: document.getElementById('xai-api-n'),
  683.             duration: document.getElementById('xai-api-duration'),
  684.             loops: document.getElementById('xai-api-loops'),
  685.  
  686.             settingAr: document.getElementById('setting-ar'),
  687.             settingResImg: document.getElementById('setting-res-img'),
  688.             settingResVid: document.getElementById('setting-res-vid'),
  689.             settingBatch: document.getElementById('setting-batch'),
  690.             settingDuration: document.getElementById('setting-duration'),
  691.             settingLoops: document.getElementById('setting-loops'),
  692.  
  693.             fileInput: document.getElementById('xai-api-file'),
  694.             dropzone: document.getElementById('col-right-dropzone'),
  695.             uploadPlaceholder: document.getElementById('xai-upload-placeholder'),
  696.             refList: document.getElementById('xai-ref-list'),
  697.             refTitle: document.getElementById('ref-panel-title'),
  698.  
  699.             btn: document.getElementById('xai-api-generate'),
  700.             previewBtn: document.getElementById('xai-preview-btn'),
  701.             cancelBtn: document.getElementById('xai-cancel-btn'),
  702.             status: document.getElementById('xai-api-status'),
  703.             history: document.getElementById('xai-history'),
  704.             currentImages: document.getElementById('xai-current-images'),
  705.             reset: document.getElementById('xai-reset-btn'),
  706.  
  707.             arSelectBox: document.getElementById('ar-select-box'),
  708.             arOptionsCont: document.getElementById('ar-options-container'),
  709.             arSelectedIcon: document.getElementById('ar-selected-icon'),
  710.             arSelectedText: document.getElementById('ar-selected-text'),
  711.  
  712.             lightbox: document.getElementById('xai-lightbox'),
  713.             lightboxImg: document.getElementById('xai-lightbox-img'),
  714.             lightboxDl: document.getElementById('xai-lightbox-dl'),
  715.  
  716.             previewBox: document.getElementById('tag-preview-box'),
  717.             previewImg: document.getElementById('tag-preview-img'),
  718.  
  719.             payloadModal: document.getElementById('xai-payload-modal'),
  720.             payloadEndpoint: document.getElementById('payload-endpoint'),
  721.             payloadCode: document.getElementById('payload-code'),
  722.             closePayloadBtn: document.getElementById('close-payload-btn'),
  723.             sendCustomBtn: document.getElementById('send-custom-payload-btn'),
  724.             customStatus: document.getElementById('custom-payload-status'),
  725.  
  726.             settingsBtn: document.getElementById('settings-btn'),
  727.             settingsModal: document.getElementById('xai-settings-modal'),
  728.             closeSettingsBtn: document.getElementById('close-settings-btn'),
  729.             saveSettingsBtn: document.getElementById('save-settings-btn'),
  730.  
  731.             favBtn: document.getElementById('fav-prompts-btn'),
  732.             favModal: document.getElementById('xai-fav-modal'),
  733.             closeFavBtn: document.getElementById('close-fav-btn'),
  734.             addFavBtn: document.getElementById('add-current-fav-btn'),
  735.             favList: document.getElementById('fav-list')
  736.         };
  737.  
  738.         // ─── PROMPT HELPER & BACKDROP (HOVER) SYSTEM ────────────────────────────
  739.         function syncPromptBackdrop() {
  740.             const val = els.prompt.value;
  741.  
  742.             if (/--[a-zA-Z0-9_-]+=/.test(val)) els.promptWarning.style.display = 'block';
  743.             else els.promptWarning.style.display = 'none';
  744.  
  745.             let html = val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  746.             const activeRefs = referenceMedia.filter(m => m.active);
  747.  
  748.             html = html.replace(/&lt;IMAGE_(\d+)&gt;/g, (match, idxStr) => {
  749.                 const idx = parseInt(idxStr);
  750.                 if (activeRefs[idx]) return `<span class="prompt-tag" data-idx="${idx}">${match}</span>`;
  751.                 return match;
  752.             });
  753.  
  754.             html = html.replace(/\n/g, '<br>') + '<br>';
  755.             els.promptBackdrop.innerHTML = html;
  756.             els.promptBackdrop.scrollTop = els.prompt.scrollTop;
  757.             els.promptBackdrop.scrollLeft = els.prompt.scrollLeft;
  758.         }
  759.  
  760.         function setPromptVal(val) {
  761.             els.prompt.value = val;
  762.             localStorage.setItem('xai_api_prompt', val);
  763.             syncPromptBackdrop();
  764.         }
  765.  
  766.         if (localStorage.getItem('xai_api_prompt')) setPromptVal(localStorage.getItem('xai_api_prompt'));
  767.  
  768.         els.prompt.addEventListener('input', () => setPromptVal(els.prompt.value));
  769.         els.prompt.addEventListener('scroll', () => { els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft; });
  770.  
  771.         let hidePreviewTimeout;
  772.         els.prompt.addEventListener('mousemove', (e) => {
  773.             if (e.buttons !== 0) { els.previewBox.style.display = 'none'; return; }
  774.  
  775.             els.prompt.style.pointerEvents = 'none';
  776.             const el = document.elementFromPoint(e.clientX, e.clientY);
  777.             els.prompt.style.pointerEvents = 'auto';
  778.  
  779.             if (el && el.classList.contains('prompt-tag')) {
  780.                 const idx = el.getAttribute('data-idx');
  781.                 const activeRefs = referenceMedia.filter(m => m.active);
  782.                 const media = activeRefs[parseInt(idx)];
  783.                 if (media) {
  784.                     els.previewBox.style.display = 'block';
  785.                     els.previewImg.src = media.thumb || media.base64;
  786.  
  787.                     let targetX = e.clientX + 15; let targetY = e.clientY + 15;
  788.                     if (targetX + 160 > window.innerWidth) targetX = e.clientX - 165;
  789.                     if (targetY + 160 > window.innerHeight) targetY = e.clientY - 165;
  790.  
  791.                     els.previewBox.style.left = targetX + 'px';
  792.                     els.previewBox.style.top = targetY + 'px';
  793.                     clearTimeout(hidePreviewTimeout);
  794.                 }
  795.             } else {
  796.                 hidePreviewTimeout = setTimeout(() => els.previewBox.style.display = 'none', 50);
  797.             }
  798.         });
  799.         els.prompt.addEventListener('mouseleave', () => els.previewBox.style.display = 'none');
  800.  
  801.  
  802.         try {
  803.             const storedGen = JSON.parse(localStorage.getItem('xai_api_gen_settings') || '{}');
  804.             if (storedGen.action) els.action.value = storedGen.action;
  805.             if (storedGen.resImg) els.resImg.value = storedGen.resImg;
  806.             if (storedGen.resVid) els.resVid.value = storedGen.resVid;
  807.             if (storedGen.n) els.n.value = storedGen.n;
  808.             if (storedGen.duration) els.duration.value = storedGen.duration;
  809.             if (storedGen.loops) els.loops.value = storedGen.loops;
  810.         } catch(e) {}
  811.  
  812.         const updateGenSettingsMemory = () => {
  813.             localStorage.setItem('xai_api_gen_settings', JSON.stringify({
  814.                 action: els.action.value, resImg: els.resImg.value, resVid: els.resVid.value,
  815.                 n: els.n.value, duration: els.duration.value, loops: els.loops.value
  816.             }));
  817.         };
  818.         [els.action, els.resImg, els.resVid, els.n, els.duration, els.loops].forEach(el => el.addEventListener('change', updateGenSettingsMemory));
  819.  
  820.         try {
  821.             const storedRefs = JSON.parse(localStorage.getItem('xai_api_refs'));
  822.             if (Array.isArray(storedRefs)) referenceMedia = storedRefs;
  823.         } catch(e) {}
  824.  
  825.         // ─── SETTINGS BINDINGS ───────────────────────────────────────────────────
  826.         els.settingsBtn.addEventListener('click', () => {
  827.             document.getElementById('set-retries').value = appSettings.retries;
  828.             document.getElementById('set-delay-min').value = appSettings.delayMin;
  829.             document.getElementById('set-delay-max').value = appSettings.delayMax;
  830.             document.getElementById('set-notifications').checked = appSettings.notifications;
  831.             document.getElementById('set-save-png').checked = appSettings.saveAsPng;
  832.             document.getElementById('set-auto-retry-video').checked = appSettings.autoRetryStuckVideo;
  833.             document.getElementById('set-video-timeout').value = appSettings.videoPollTimeout;
  834.             document.getElementById('set-api-base-url').value = appSettings.apiBaseUrl || '';
  835.             document.getElementById('set-custom-css').value = appSettings.customCSS || '';
  836.             els.settingsModal.style.display = 'flex';
  837.         });
  838.  
  839.         els.saveSettingsBtn.addEventListener('click', () => {
  840.             appSettings.retries = parseInt(document.getElementById('set-retries').value) || 20;
  841.             appSettings.delayMin = parseInt(document.getElementById('set-delay-min').value) || 2000;
  842.             appSettings.delayMax = Math.max(appSettings.delayMin, parseInt(document.getElementById('set-delay-max').value) || 4000);
  843.             appSettings.notifications = document.getElementById('set-notifications').checked;
  844.             appSettings.saveAsPng = document.getElementById('set-save-png').checked;
  845.             appSettings.autoRetryStuckVideo = document.getElementById('set-auto-retry-video').checked;
  846.             appSettings.videoPollTimeout = parseInt(document.getElementById('set-video-timeout').value) || 300;
  847.             appSettings.apiBaseUrl = document.getElementById('set-api-base-url').value.trim();
  848.             appSettings.customCSS = document.getElementById('set-custom-css').value;
  849.  
  850.             localStorage.setItem('xai_api_settings', JSON.stringify(appSettings));
  851.             document.getElementById('xai-custom-css-block').innerHTML = appSettings.customCSS;
  852.  
  853.             els.settingsModal.style.display = 'none';
  854.         });
  855.  
  856.         els.closeSettingsBtn.addEventListener('click', () => els.settingsModal.style.display = 'none');
  857.  
  858.         // ─── FAVORITES BINDINGS ──────────────────────────────────────────────────
  859.         function renderFavList() {
  860.             els.favList.innerHTML = '';
  861.             if (favoritePrompts.length === 0) {
  862.                 els.favList.innerHTML = '<div style="color: #64748b; font-size: 12px; text-align: center; margin-top: 15px;">No favorite prompts yet.</div>';
  863.                 return;
  864.             }
  865.             favoritePrompts.forEach((promptText, idx) => {
  866.                 const div = document.createElement('div');
  867.                 div.className = 'fav-item';
  868.                 div.innerHTML = `
  869.                     <div class="fav-text" title="${promptText.replace(/"/g, '&quot;')}">${promptText}</div>
  870.                    <button class="btn-secondary" style="padding: 2px 6px; font-size: 10px; border-color: #ef4444; color: #ef4444;">Del</button>
  871.                `;
  872.                div.querySelector('.fav-text').addEventListener('click', () => {
  873.                    setPromptVal(promptText);
  874.                    els.favModal.style.display = 'none';
  875.                });
  876.                div.querySelector('button').addEventListener('click', () => {
  877.                    favoritePrompts.splice(idx, 1);
  878.                    localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts));
  879.                    renderFavList();
  880.                });
  881.                els.favList.appendChild(div);
  882.            });
  883.        }
  884.  
  885.        els.favBtn.addEventListener('click', () => {
  886.            renderFavList();
  887.            els.favModal.style.display = 'flex';
  888.        });
  889.        els.closeFavBtn.addEventListener('click', () => els.favModal.style.display = 'none');
  890.        els.addFavBtn.addEventListener('click', () => {
  891.            const p = els.prompt.value.trim();
  892.            if (!p) return alert("Prompt is empty!");
  893.            if (favoritePrompts.includes(p)) return alert("Already in favorites!");
  894.            favoritePrompts.unshift(p);
  895.            localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts));
  896.            renderFavList();
  897.        });
  898.  
  899.        // ─── PROMPT BOX EXIF DRAG & DROP ──────────────────────────────────────────
  900.        els.prompt.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.add('prompt-drag-over'); });
  901.        els.prompt.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over'); });
  902.        els.prompt.addEventListener('drop', async (e) => {
  903.            e.preventDefault(); e.stopPropagation();
  904.            els.promptContainer.classList.remove('prompt-drag-over');
  905.            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  906.                const file = e.dataTransfer.files[0];
  907.                const oldVal = els.prompt.value;
  908.                setPromptVal("Extracting prompt from EXIF...");
  909.                const extractedPrompt = await extractPromptFromImage(file);
  910.                if (extractedPrompt) {
  911.                    setPromptVal(extractedPrompt);
  912.                } else {
  913.                    setPromptVal(oldVal);
  914.                    alert("No prompt found in this image's EXIF data (or not a valid JPEG).");
  915.                }
  916.            }
  917.        });
  918.  
  919.        // ─── MASTER ACTION UI LOGIC ───────────────────────────────────────────────
  920.        function getMaxMedia() {
  921.            const val = els.action.value;
  922.            if (val === 'gen_image') return 5;
  923.            if (val === 'gen_video') return 7;
  924.            return 1;
  925.        }
  926.  
  927.        function updateActionUI() {
  928.            const val = els.action.value;
  929.  
  930.            if (val === 'gen_image') {
  931.                els.settingAr.style.display = 'block'; els.settingResImg.style.display = 'block'; els.settingResVid.style.display = 'none'; els.settingBatch.style.display = 'block'; els.settingDuration.style.display = 'none';
  932.            } else if (val === 'gen_video') {
  933.                els.settingAr.style.display = 'block'; els.settingResImg.style.display = 'none'; els.settingResVid.style.display = 'block'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'block';
  934.                els.duration.innerHTML = `<option value="5">5 Seconds</option><option value="8">8 Seconds</option><option value="10">10 Seconds</option><option value="12">12 Seconds</option><option value="15">15 Seconds</option>`;
  935.                if (localStorage.getItem('xai_api_gen_settings') && JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration <= 15) {
  936.                    els.duration.value = JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration;
  937.                } else els.duration.value = "5";
  938.            } else if (val === 'edit_video') {
  939.                els.settingAr.style.display = 'none'; els.settingResImg.style.display = 'none'; els.settingResVid.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'none';
  940.            } else if (val === 'extend_video') {
  941.                els.settingAr.style.display = 'none'; els.settingResImg.style.display = 'none'; els.settingResVid.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'block';
  942.                els.duration.innerHTML = `<option value="2">2s Extension</option><option value="4">4s Extension</option><option value="6">6s Extension</option><option value="8">8s Extension</option><option value="10">10s Extension</option>`;
  943.                if (localStorage.getItem('xai_api_gen_settings') && JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration <= 10) {
  944.                    els.duration.value = JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration;
  945.                } else els.duration.value = "6";
  946.            }
  947.  
  948.            const max = getMaxMedia();
  949.            els.refTitle.innerText = `Reference Media (Max Active: ${max})`;
  950.  
  951.            let activeCount = 0;
  952.            referenceMedia.forEach(m => {
  953.                let valid = true;
  954.                if ((val === 'gen_image' || val === 'gen_video') && m.isVideo) valid = false;
  955.                if ((val === 'edit_video' || val === 'extend_video') && !m.isVideo) valid = false;
  956.  
  957.                if (!valid) m.active = false;
  958.                else if (m.active) {
  959.                    activeCount++;
  960.                    if (activeCount > max) m.active = false;
  961.                }
  962.            });
  963.            renderRefList();
  964.        }
  965.  
  966.        els.action.addEventListener('change', updateActionUI);
  967.        updateActionUI();
  968.  
  969.        // ─── INSTANT EDIT BINDING HANDLER ─────────────────────────────────────────
  970.        updateUIForEditMedia = (mediaUrl, isVideo, fileName) => {
  971.            referenceMedia.forEach(m => m.active = false);
  972.  
  973.            referenceMedia.unshift({
  974.                id: Date.now() + Math.random(),
  975.                base64: mediaUrl,
  976.                isVideo: isVideo,
  977.                active: true,
  978.                thumb: isVideo ? null : mediaUrl,
  979.                fileName: fileName || (isVideo ? 'Edited_Video.mp4' : 'Edited_Image.png')
  980.            });
  981.  
  982.            els.action.value = isVideo ? 'edit_video' : 'gen_image';
  983.            updateActionUI();
  984.            updateGenSettingsMemory();
  985.            renderRefList();
  986.            saveRefs();
  987.        };
  988.  
  989.        // ─── BUILD PAYLOAD LOGIC ──────────────────────────────────────────────────
  990.        function buildPayloadData(dynamicPromptText) {
  991.            const action = els.action.value;
  992.            const payload = {
  993.                model: action === 'gen_image' ? "grok-imagine-image" : "grok-imagine-video",
  994.                prompt: dynamicPromptText,
  995.            };
  996.  
  997.            const ar = currentAr.toLowerCase();
  998.            const activeRefs = referenceMedia.filter(m => m.active);
  999.  
  1000.            if (action === 'gen_image') {
  1001.                payload.n = parseInt(els.n.value); payload.resolution = els.resImg.value; payload.response_format = "b64_json";
  1002.                if (ar !== 'auto') payload.aspect_ratio = ar; else if (activeRefs.length > 0) payload.aspect_ratio = 'auto';
  1003.  
  1004.                if (activeRefs.length > 0) {
  1005.                    if (activeRefs.length === 1) payload.image = { url: activeRefs[0].base64 };
  1006.                    else payload.images = activeRefs.map(m => ({ type: "image_url", url: m.base64 }));
  1007.                }
  1008.            } else if (action === 'gen_video') {
  1009.                payload.duration = parseInt(els.duration.value); payload.resolution = els.resVid.value;
  1010.                if (ar !== 'auto') payload.aspect_ratio = ar;
  1011.                if (activeRefs.length > 0) payload.reference_images = activeRefs.map(m => ({ url: m.base64 }));
  1012.            } else if (action === 'edit_video') {
  1013.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  1014.            } else if (action === 'extend_video') {
  1015.                payload.duration = parseInt(els.duration.value);
  1016.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  1017.            }
  1018.            return payload;
  1019.        }
  1020.  
  1021.        // ─── CUSTOM PAYLOAD DEBUGGER LOGIC ────────────────────────────────────────
  1022.        els.previewBtn.addEventListener('click', () => {
  1023.            const dynamicPrompt = parseDynamicPrompt(els.prompt.value.trim());
  1024.            fullPayloadMemory = buildPayloadData(dynamicPrompt);
  1025.            const displayP = JSON.parse(JSON.stringify(fullPayloadMemory));
  1026.            const trunc = "[BASE64_TRUNCATED_FOR_PREVIEW]";
  1027.  
  1028.            if (displayP.image) { if (Array.isArray(displayP.image)) displayP.image.forEach(img => img.url = trunc); else displayP.image.url = trunc; }
  1029.            if (displayP.images && Array.isArray(displayP.images)) displayP.images.forEach(img => img.url = trunc);
  1030.            if (displayP.reference_images && Array.isArray(displayP.reference_images)) displayP.reference_images.forEach(img => img.url = trunc);
  1031.            if (displayP.video) displayP.video.url = trunc;
  1032.  
  1033.            const activeRefs = referenceMedia.filter(m => m.active);
  1034.            let endpoint = '/v1/images/generations';
  1035.            if (els.action.value === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1036.            else if (els.action.value === 'gen_video') endpoint = '/v1/videos/generations';
  1037.            else if (els.action.value === 'edit_video') endpoint = '/v1/videos/edits';
  1038.            else if (els.action.value === 'extend_video') endpoint = '/v1/videos/extensions';
  1039.  
  1040.            els.payloadEndpoint.value = endpoint;
  1041.            els.payloadCode.value = JSON.stringify(displayP, null, 2);
  1042.            els.payloadModal.style.display = 'flex';
  1043.        });
  1044.  
  1045.        els.closePayloadBtn.addEventListener('click', () => els.payloadModal.style.display = 'none');
  1046.  
  1047.        function injectBase64(editedObj, originalObj) {
  1048.            if (!editedObj || typeof editedObj !== 'object') return;
  1049.            for (let key in editedObj) {
  1050.                if (typeof editedObj[key] === 'string' && editedObj[key] === '[BASE64_TRUNCATED_FOR_PREVIEW]') {
  1051.                    if (originalObj && originalObj[key]) editedObj[key] = originalObj[key];
  1052.                } else if (typeof editedObj[key] === 'object') { injectBase64(editedObj[key], originalObj ? originalObj[key] : null); }
  1053.            }
  1054.        }
  1055.  
  1056.        els.sendCustomBtn.addEventListener('click', async () => {
  1057.            initAudio();
  1058.            let customPayload;
  1059.            try { customPayload = JSON.parse(els.payloadCode.value); }
  1060.            catch(e) { return alert("Invalid JSON format in textarea!"); }
  1061.  
  1062.            injectBase64(customPayload, fullPayloadMemory);
  1063.            const endpoint = els.payloadEndpoint.value.trim();
  1064.            const isImage = customPayload.model === "grok-imagine-image";
  1065.  
  1066.            stealthIdentityReset();
  1067.  
  1068.            els.sendCustomBtn.disabled = true;
  1069.            els.sendCustomBtn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Processing...</div>`;
  1070.            isRequestCancelled = false;
  1071.  
  1072.            const ok = await executeGenerationSingle(endpoint, customPayload, isImage, els.customStatus, 1, 1);
  1073.  
  1074.            els.sendCustomBtn.disabled = false;
  1075.            els.sendCustomBtn.innerHTML = `<div class="btn-content">🚀 Send Custom Payload</div>`;
  1076.            if (ok) notifyUser(false); else notifyUser(true);
  1077.        });
  1078.  
  1079.        // ─── CSP-SAFE DELEGATED LIGHTBOX LOGIC ────────────────────────────────────
  1080.        els.app.addEventListener('click', (e) => {
  1081.            if (e.target && e.target.classList.contains('zoomable') && e.target.tagName === 'IMG') {
  1082.                els.lightboxImg.src = e.target.src; els.lightboxDl.href = e.target.src; els.lightboxDl.download = e.target.dataset.filename || 'Reference_Image.jpg';
  1083.                els.lightbox.style.display = 'flex';
  1084.            }
  1085.        });
  1086.        els.lightbox.addEventListener('click', (e) => {
  1087.            if (e.target.closest('#xai-lightbox-dl')) return;
  1088.            if (e.target.closest('.modal-box')) return;
  1089.            els.lightbox.style.display = 'none';
  1090.        });
  1091.        document.addEventListener('keydown', (e) => { if(e.key === 'Escape') { Array.from(document.querySelectorAll('.modal-overlay')).forEach(m => m.style.display = 'none'); } });
  1092.  
  1093.        // ─── FIXED FLOATING AR DROPDOWN LOGIC ─────────────────────────────────────
  1094.        function renderArOptions() {
  1095.            els.arOptionsCont.innerHTML = '';
  1096.            arData.forEach(ar => {
  1097.                const opt = document.createElement('div'); opt.className = 'ar-option';
  1098.                opt.innerHTML = `${createArIcon(ar.w, ar.h, ar.isAuto)} <span>${ar.label}</span>`;
  1099.                opt.addEventListener('click', () => { setAr(ar); els.arOptionsCont.style.display = 'none'; });
  1100.                els.arOptionsCont.appendChild(opt);
  1101.            });
  1102.        }
  1103.        function setAr(arObj) {
  1104.            currentAr = arObj.label; localStorage.setItem('xai_api_ar', currentAr);
  1105.            els.arSelectedIcon.innerHTML = createArIcon(arObj.w, arObj.h, arObj.isAuto); els.arSelectedText.innerText = arObj.label;
  1106.        }
  1107.        renderArOptions();
  1108.        const initialAr = arData.find(a => a.label === currentAr) || arData[0]; setAr(initialAr);
  1109.  
  1110.        els.arSelectBox.addEventListener('click', (e) => {
  1111.            e.stopPropagation();
  1112.            if (els.arOptionsCont.style.display === 'block') { els.arOptionsCont.style.display = 'none'; return; }
  1113.            const rect = els.arSelectBox.getBoundingClientRect();
  1114.            els.arOptionsCont.style.top = (rect.bottom + 5) + 'px'; els.arOptionsCont.style.left = rect.left + 'px'; els.arOptionsCont.style.width = rect.width + 'px';
  1115.            els.arOptionsCont.style.display = 'block';
  1116.        });
  1117.        document.addEventListener('click', (e) => { if (!els.arOptionsCont.contains(e.target)) els.arOptionsCont.style.display = 'none'; });
  1118.  
  1119.        // ─── UNLIMITED MULTI-IMAGE DRAG/DROP WITH VIDEO THUMBNAILS ────────────────
  1120.        async function processFile(file) {
  1121.            const isVid = file.type.startsWith('video/'); const isImg = file.type.startsWith('image/');
  1122.            if (!isVid && !isImg) return;
  1123.  
  1124.            if (isVid && (els.action.value === 'gen_image' || els.action.value === 'gen_video')) { els.action.value = 'edit_video'; updateActionUI(); updateGenSettingsMemory(); }
  1125.            else if (isImg && (els.action.value === 'edit_video' || els.action.value === 'extend_video')) { els.action.value = 'gen_image'; updateActionUI(); updateGenSettingsMemory(); }
  1126.  
  1127.            const max = getMaxMedia();
  1128.            const activeCount = referenceMedia.filter(m => m.active).length;
  1129.  
  1130.            let thumbBase64 = null;
  1131.            if (isVid) thumbBase64 = await generateVideoThumbnail(file);
  1132.  
  1133.            const reader = new FileReader();
  1134.            reader.onload = (event) => {
  1135.                referenceMedia.push({
  1136.                    id: Date.now() + Math.random(),
  1137.                    base64: event.target.result,
  1138.                    isVideo: isVid,
  1139.                    active: activeCount < max,
  1140.                    thumb: thumbBase64,
  1141.                    fileName: file.name
  1142.                });
  1143.                renderRefList();
  1144.                if (isImg) setAr(arData[0]);
  1145.            };
  1146.            reader.readAsDataURL(file);
  1147.        }
  1148.  
  1149.        let draggedIndex = null;
  1150.        function renderRefList() {
  1151.            els.refList.innerHTML = '';
  1152.            referenceMedia.forEach((media, index) => {
  1153.                const item = document.createElement('div');
  1154.                item.className = 'ref-item';
  1155.                item.draggable = true;
  1156.  
  1157.                const activeRefs = referenceMedia.filter(m => m.active);
  1158.                const dynamicIndex = media.active ? activeRefs.indexOf(media) : '?';
  1159.                const actionVal = els.action.value;
  1160.                const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
  1161.  
  1162.                let thumbHtml = '';
  1163.                if (media.isVideo) {
  1164.                    if (media.thumb) {
  1165.                        thumbHtml = `
  1166.                            <div style="position: relative; width: 90px; height: 90px; flex-shrink: 0;">
  1167.                                <img src="${media.thumb}" class="ref-thumb" style="width: 100%; height: 100%;" title="${media.fileName || 'Video'}">
  1168.                                <div style="position: absolute; top: 4px; right: 4px; background: rgba(0,0,0,0.7); color: white; border-radius: 4px; padding: 2px 4px; font-size: 10px;">🎥</div>
  1169.                            </div>
  1170.                        `;
  1171.                    } else {
  1172.                        thumbHtml = `<div class="ref-thumb" style="display:flex; align-items:center; justify-content:center; flex-direction:column; background:#1e293b; color:#94a3b8; font-size:24px;" title="${media.fileName || 'Video'}">🎥<span style="font-size:9px; margin-top:4px; max-width:80px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${media.fileName || 'Video'}</span></div>`;
  1173.                    }
  1174.                } else {
  1175.                    thumbHtml = `<img src="${media.base64}" class="ref-thumb zoomable" data-filename="${media.fileName || 'Reference_'+(index+1)+'.jpg'}" title="${media.fileName || 'Click to view'}">`;
  1176.                }
  1177.  
  1178.                let insertBtnHtml = '';
  1179.                if (!media.isVideo) {
  1180.                    if (disableInsert) {
  1181.                        insertBtnHtml = `<button class="ref-action-btn ref-insert" disabled style="opacity: 0.4; filter: grayscale(1); cursor: not-allowed;" title="Not available in this mode">➕ &lt;IMAGE_X&gt;</button>`;
  1182.                    } else if (!media.active) {
  1183.                        insertBtnHtml = `<button class="ref-action-btn ref-insert" disabled style="opacity: 0.4; cursor: not-allowed;" title="Check 'Use in Payload' first">➕ &lt;IMAGE_?&gt;</button>`;
  1184.                    } else {
  1185.                        insertBtnHtml = `<button class="ref-action-btn ref-insert" title="Insert into prompt">➕ &lt;IMAGE_${dynamicIndex}&gt;</button>`;
  1186.                    }
  1187.                }
  1188.  
  1189.                item.innerHTML = `
  1190.                    <div class="ref-handle">☰</div>
  1191.                    ${thumbHtml}
  1192.                    <div class="ref-info">
  1193.                        <span style="font-size: 12px; color: #e2e8f0; font-weight: 600;">Ref ${index + 1} ${media.isVideo ? '(Video)' : ''}</span>
  1194.                        <label class="ref-toggle-label">
  1195.                            <input type="checkbox" class="ref-active-toggle" ${media.active ? 'checked' : ''}> Use in Payload
  1196.                        </label>
  1197.                        <div class="ref-btn-group">
  1198.                            ${insertBtnHtml}
  1199.                            <button class="ref-action-btn ref-del">Remove</button>
  1200.                        </div>
  1201.                    </div>
  1202.                `;
  1203.  
  1204.                const insertBtn = item.querySelector('.ref-insert');
  1205.                if (insertBtn && media.active) {
  1206.                    insertBtn.addEventListener('click', (e) => {
  1207.                        const currentAction = els.action.value;
  1208.                        if (currentAction === 'edit_video' || currentAction === 'extend_video') {
  1209.                            e.preventDefault();
  1210.                            return alert("<IMAGE_X> tags are not supported in Edit Video and Extend Video modes.");
  1211.                        }
  1212.  
  1213.                        const promptEl = els.prompt;
  1214.                        const tag = `<IMAGE_${dynamicIndex}>`;
  1215.                        const startPos = promptEl.selectionStart;
  1216.                        const endPos = promptEl.selectionEnd;
  1217.  
  1218.                        setPromptVal(promptEl.value.substring(0, startPos) + tag + promptEl.value.substring(endPos, promptEl.value.length));
  1219.                        promptEl.selectionStart = promptEl.selectionEnd = startPos + tag.length;
  1220.                        promptEl.focus();
  1221.                    });
  1222.                }
  1223.  
  1224.                if (!media.active) item.classList.add('inactive');
  1225.  
  1226.                item.querySelector('.ref-active-toggle').addEventListener('change', (e) => {
  1227.                    const max = getMaxMedia();
  1228.                    const currentlyActive = referenceMedia.filter(r => r.active).length;
  1229.  
  1230.                    if (e.target.checked && currentlyActive >= max) {
  1231.                        alert(`You can only have up to ${max} active references for this mode.`);
  1232.                        e.target.checked = false;
  1233.                        return;
  1234.                    }
  1235.                    media.active = e.target.checked;
  1236.                    saveRefs();
  1237.                    renderRefList();
  1238.                    syncPromptBackdrop();
  1239.                });
  1240.  
  1241.                item.addEventListener('dragstart', (e) => { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; setTimeout(() => item.classList.add('dragging'), 0); });
  1242.                item.addEventListener('dragend', () => { item.classList.remove('dragging'); draggedIndex = null; document.querySelectorAll('.ref-item').forEach(el => el.classList.remove('drag-over-top', 'drag-over-bottom')); });
  1243.                item.addEventListener('dragover', (e) => {
  1244.                    e.preventDefault(); if (draggedIndex === null || draggedIndex === index) return;
  1245.                    const rect = item.getBoundingClientRect();
  1246.                    if (e.clientY - rect.top < rect.height / 2) { item.classList.add('drag-over-top'); item.classList.remove('drag-over-bottom'); }
  1247.                    else { item.classList.add('drag-over-bottom'); item.classList.remove('drag-over-top'); }
  1248.                });
  1249.                item.addEventListener('dragleave', () => item.classList.remove('drag-over-top', 'drag-over-bottom'));
  1250.                item.addEventListener('drop', (e) => {
  1251.                    e.preventDefault(); item.classList.remove('drag-over-top', 'drag-over-bottom');
  1252.                    if (draggedIndex === null || draggedIndex === index) return;
  1253.                    const rect = item.getBoundingClientRect();
  1254.                    let insertIndex = (e.clientY - rect.top) < rect.height / 2 ? index : index + 1;
  1255.                    if (draggedIndex < insertIndex) insertIndex--;
  1256.                    const [movedImage] = referenceMedia.splice(draggedIndex, 1);
  1257.                    referenceMedia.splice(insertIndex, 0, movedImage); renderRefList(); syncPromptBackdrop();
  1258.                });
  1259.  
  1260.                item.querySelector('.ref-del').addEventListener('click', () => { referenceMedia.splice(index, 1); renderRefList(); syncPromptBackdrop(); });
  1261.                els.refList.appendChild(item);
  1262.            });
  1263.            saveRefs();
  1264.        }
  1265.  
  1266.        els.uploadPlaceholder.addEventListener('click', () => { els.fileInput.click(); });
  1267.        els.fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(processFile); els.fileInput.value = ''; });
  1268.        document.addEventListener('paste', (e) => {
  1269.            if (e.target && (e.target.id === 'payload-code' || e.target.id === 'xai-api-prompt' || e.target.id === 'set-custom-css' || e.target.tagName === 'INPUT')) return;
  1270.            const items = e.clipboardData.items; for (let i = 0; i < items.length; i++) if (items[i].type.indexOf('image') !== -1) processFile(items[i].getAsFile());
  1271.        });
  1272.  
  1273.        els.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); els.dropzone.classList.add('drag-over'); });
  1274.        els.dropzone.addEventListener('dragleave', () => els.dropzone.classList.remove('drag-over'));
  1275.        els.dropzone.addEventListener('drop', (e) => { e.preventDefault(); els.dropzone.classList.remove('drag-over'); if (e.dataTransfer.files) Array.from(e.dataTransfer.files).forEach(processFile); });
  1276.  
  1277.        // ─── CANCEL BUTTON LOGIC ─────────────────────────────────────────────────
  1278.        els.cancelBtn.addEventListener('click', () => {
  1279.            isRequestCancelled = true;
  1280.            if (currentAbortController) currentAbortController.abort();
  1281.            els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex';
  1282.            els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1283.            els.status.innerText = "Request Cancelled."; els.status.className = ""; els.status.style.color = "#ef4444";
  1284.        });
  1285.  
  1286.        // ─── MASTER GENERATION LOGIC ──────────────────────────────────────────────
  1287.        async function executeGenerationSingle(endpoint, payload, isImageAction, statusEl, currentLoop, totalLoops) {
  1288.            let loopPrefix = totalLoops > 1 ? `[Run ${currentLoop}/${totalLoops}] ` : '';
  1289.            statusEl.innerText = `${loopPrefix}Processing request...`;
  1290.            statusEl.className = "status-pulsing";
  1291.  
  1292.            currentAbortController = new AbortController();
  1293.  
  1294.            let attempts = 0; let success = false;
  1295.            while (attempts < appSettings.retries && !success && !isRequestCancelled) {
  1296.                try {
  1297.                    statusEl.innerText = `${loopPrefix}Sending request to xAI...`;
  1298.  
  1299.                    const fullEndpoint = getApiUrl(endpoint);
  1300.                    const response = await fetch(fullEndpoint, {
  1301.                        method: 'POST',
  1302.                        headers: { 'Content-Type': 'application/json' },
  1303.                        body: JSON.stringify(payload),
  1304.                        signal: currentAbortController.signal
  1305.                    });
  1306.  
  1307.                    if (response.status === 429 || response.status === 503 || response.status === 500 || response.status === 502) {
  1308.                        attempts++;
  1309.                        statusEl.innerText = `${loopPrefix}Busy (Error ${response.status}). Retrying... [${attempts}/${appSettings.retries}]`;
  1310.                        const delay = Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin;
  1311.                        await sleep(delay);
  1312.                        continue;
  1313.                    }
  1314.  
  1315.                    if (!response.ok) {
  1316.                        let errMsg = `HTTP ${response.status}`;
  1317.                        try {
  1318.                            const errData = await response.json();
  1319.                            if (errData.error && errData.error.message) errMsg += `\n${errData.error.message}`;
  1320.                            else if (errData.detail) errMsg += `\n${JSON.stringify(errData.detail)}`;
  1321.                        } catch(e) {}
  1322.                        throw new Error(errMsg);
  1323.                    }
  1324.  
  1325.                    const data = await response.json();
  1326.  
  1327.                    if (isImageAction) {
  1328.                        if (data && data.data && Array.isArray(data.data)) {
  1329.                            success = true;
  1330.                            statusEl.innerText = `${loopPrefix}Processing final images...`;
  1331.                            statusEl.style.color = "#10b981";
  1332.                            statusEl.className = "";
  1333.  
  1334.                            await Promise.all(data.data.map((imgObj, index) =>
  1335.                                processAndRenderImage(imgObj, payload.prompt, index + 1, data.data.length, els.currentImages)
  1336.                            ));
  1337.  
  1338.                            statusEl.innerText = "Ready";
  1339.                            statusEl.style.color = "#64748b";
  1340.                        } else throw new Error("Invalid response format.");
  1341.                    } else {
  1342.                        const reqId = data.request_id;
  1343.                        if (!reqId) throw new Error("No Request ID returned.");
  1344.  
  1345.                        let videoReady = false;
  1346.                        let pollCount = 0;
  1347.                        const MAX_POLLS = Math.max(1, Math.ceil(appSettings.videoPollTimeout / 5));
  1348.  
  1349.                        while (!videoReady && !isRequestCancelled) {
  1350.                            pollCount++;
  1351.                            if (pollCount > MAX_POLLS) throw new Error("Timeout: Video likely dropped by filters or stuck in queue.");
  1352.                            await sleep(5000);
  1353.                            if (isRequestCancelled) break;
  1354.  
  1355.                            const pollRes = await fetch(getApiUrl(`/v1/videos/${reqId}`), { signal: currentAbortController.signal });
  1356.                            if (!pollRes.ok) continue;
  1357.  
  1358.                            const pollData = await pollRes.json();
  1359.                            if (pollData.error) throw new Error(`API Error: ${pollData.error.message || JSON.stringify(pollData.error)}`);
  1360.  
  1361.                            const state = (pollData.status || pollData.state || 'processing').toLowerCase();
  1362.                            statusEl.innerText = `${loopPrefix}Polling video (Status: ${state})...[${pollCount}/${MAX_POLLS}]`;
  1363.  
  1364.                            if (state === 'done' || state === 'completed') {
  1365.                                videoReady = true;
  1366.                                success = true;
  1367.                                statusEl.innerText = "Ready"; statusEl.className = ""; statusEl.style.color = "#94a3b8";
  1368.                                renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1369.                            } else if (['failed', 'expired', 'rejected', 'blocked', 'moderated', 'nsfw'].includes(state) || pollData.is_sensitive) {
  1370.                                if (pollData.video && pollData.video.url) {
  1371.                                    videoReady = true;
  1372.                                    success = true;
  1373.                                    statusEl.innerText = `${loopPrefix}Warning: Flagged as ${state}, but recovered!`;
  1374.                                    statusEl.className = ""; statusEl.style.color = "#d97706";
  1375.                                    renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1376.                                } else {
  1377.                                    throw new Error(`Generation halted. Reason: ${state}`);
  1378.                                }
  1379.                            }
  1380.                        }
  1381.                    }
  1382.  
  1383.                } catch (err) {
  1384.                    if (err.name === 'AbortError' || isRequestCancelled) {
  1385.                        statusEl.innerText = "Request Cancelled."; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1386.                        return false;
  1387.                    } else if ((err.message.includes("Timeout: Video") || err.message.includes("Generation halted.")) && appSettings.autoRetryStuckVideo) {
  1388.                        attempts++;
  1389.                        if (attempts >= appSettings.retries) {
  1390.                            statusEl.innerText = `${loopPrefix}Failed: Max retries reached for stuck video.`;
  1391.                            statusEl.className = ""; statusEl.style.color = "#ef4444";
  1392.                            break;
  1393.                        }
  1394.                        statusEl.innerText = `${loopPrefix}Video Stuck/Failed. Auto-retrying... [${attempts}/${appSettings.retries}]`;
  1395.                        const delay = Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin;
  1396.                        await sleep(delay);
  1397.  
  1398.                        // Anti-caching injection: add a zero-width space to the prompt to force the server to evaluate a fresh generation.
  1399.                        if (payload.prompt) payload.prompt += "\u200B";
  1400.  
  1401.                        continue;
  1402.                    } else {
  1403.                        statusEl.innerText = `${loopPrefix}Error: ${err.message}`; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1404.                        break;
  1405.                    }
  1406.                }
  1407.            }
  1408.  
  1409.            if (!success && !isRequestCancelled) {
  1410.                if (!statusEl.innerText.includes("Failed:") && !statusEl.innerText.includes("Error:")) {
  1411.                    statusEl.innerText = `${loopPrefix}Failed after ${attempts} retries.`;
  1412.                }
  1413.                statusEl.className = ""; statusEl.style.color = "#ef4444";
  1414.                return false;
  1415.            }
  1416.  
  1417.            return success;
  1418.        }
  1419.  
  1420.        els.btn.addEventListener('click', async () => {
  1421.            initAudio();
  1422.            const basePrompt = els.prompt.value.trim();
  1423.            if (!basePrompt) return alert("Please enter a prompt.");
  1424.  
  1425.            const oldImages = Array.from(els.currentImages.children);
  1426.            if (oldImages.length > 0) {
  1427.                if (els.history.innerText.includes("No history")) els.history.innerHTML = '';
  1428.                oldImages.forEach(card => {
  1429.                    card.className = 'history-card';
  1430.                    const promptEl = card.querySelector('p');
  1431.                    promptEl.title = "Click to copy prompt";
  1432.                    promptEl.onclick = () => { setPromptVal(promptEl.innerText); };
  1433.                    els.history.prepend(card);
  1434.                });
  1435.            }
  1436.  
  1437.            const action = els.action.value;
  1438.            const activeRefs = referenceMedia.filter(m => m.active);
  1439.            let endpoint = '/v1/images/generations';
  1440.            if (action === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1441.            else if (action === 'gen_video') endpoint = '/v1/videos/generations';
  1442.            else if (action === 'edit_video') endpoint = '/v1/videos/edits';
  1443.            else if (action === 'extend_video') endpoint = '/v1/videos/extensions';
  1444.  
  1445.            const isImage = action === 'gen_image';
  1446.            const totalLoops = parseInt(els.loops.value) || 1;
  1447.  
  1448.            stealthIdentityReset();
  1449.  
  1450.            els.btn.disabled = true;
  1451.            els.cancelBtn.style.display = 'flex';
  1452.            els.previewBtn.style.display = 'none';
  1453.            isRequestCancelled = false;
  1454.  
  1455.            let allSuccess = true;
  1456.            for (let i = 1; i <= totalLoops; i++) {
  1457.                if (isRequestCancelled) break;
  1458.  
  1459.                const dynamicPrompt = parseDynamicPrompt(basePrompt);
  1460.                const payload = buildPayloadData(dynamicPrompt);
  1461.  
  1462.                els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Gen ${i}/${totalLoops}...</div>`;
  1463.  
  1464.                const ok = await executeGenerationSingle(endpoint, payload, isImage, els.status, i, totalLoops);
  1465.                if (!ok) {
  1466.                    allSuccess = false;
  1467.                    break;
  1468.                }
  1469.            }
  1470.  
  1471.            if (!isRequestCancelled) {
  1472.                els.cancelBtn.style.display = 'none';
  1473.                els.previewBtn.style.display = 'flex';
  1474.                els.btn.disabled = false;
  1475.                els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1476.  
  1477.                if (allSuccess) {
  1478.                    els.status.innerText = "All runs complete.";
  1479.                    els.status.className = "";
  1480.                    els.status.style.color = "#64748b";
  1481.                    notifyUser(false);
  1482.                } else {
  1483.                    notifyUser(true);
  1484.                }
  1485.            }
  1486.        });
  1487.  
  1488.        // ─── SESSION RESETTER ─────────────────────────────────────────────────────
  1489.        els.reset.addEventListener('click', () => {
  1490.            if (!confirm("Wipe cache? (This forces a page reload to clear front-end tokens). Your prompt and settings will be saved.")) return;
  1491.            localStorage.setItem('xai_api_prompt', els.prompt.value);
  1492.            const patterns =[/flushAfter/i, /imagine/i, /generation/i, /grok/i, /mixpanel|mp_/i, /distinct_id/i, /_rst/i, /limit/i, /credit/i];
  1493.            for (let i = localStorage.length - 1; i >= 0; i--) {
  1494.                const k = localStorage.key(i);
  1495.                if (k && !k.startsWith('xai_api_') && patterns.some(p => p.test(k))) localStorage.removeItem(k);
  1496.            }
  1497.            document.cookie.split(';').forEach(c => {
  1498.                const name = c.split('=')[0]?.trim();
  1499.                if (!name || !patterns.some(p => name.toLowerCase().includes(p.toLowerCase()))) return;['.x.ai', 'console.x.ai', ''].forEach(d => {['/', '/playground/imagine', ''].forEach(p => { document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${p}${d ? ';domain=' + d : ''}`; });
  1500.                });
  1501.            });
  1502.            const u = new URL(location.href);
  1503.            ['_r', '_rst'].forEach(k => u.searchParams.set(k, Date.now()));
  1504.            location.replace(u.toString());
  1505.        });
  1506.    }
  1507.  
  1508.    // ─── ASYNC PROCESSORS & RENDERERS ─────────────────────────────────────────
  1509.    async function processAndRenderImage(imgObj, originalPrompt, num, total, galleryEl) {
  1510.        if (!imgObj.b64_json) return;
  1511.        const mime = imgObj.mime_type || "image/png";
  1512.        const b64 = imgObj.b64_json;
  1513.        const pngDataUri = `data:${mime};base64,${b64}`;
  1514.  
  1515.        const finalPrompt = imgObj.revised_prompt || originalPrompt;
  1516.        let finalDataUri = pngDataUri;
  1517.        let filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.png`;
  1518.  
  1519.        if (!appSettings.saveAsPng) {
  1520.            finalDataUri = await convertToJpegWithExif(pngDataUri, finalPrompt);
  1521.            filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.jpg`;
  1522.        }
  1523.  
  1524.        const card = document.createElement('div');
  1525.        card.className = 'current-card';
  1526.        card.innerHTML = `
  1527.            <div class="img-wrapper">
  1528.                <img src="${finalDataUri}" class="zoomable" data-filename="${filename}" title="Click to view fullscreen">
  1529.                <a href="${finalDataUri}" download="${filename}" class="overlay-btn overlay-dl-btn" title="Download Full File">${DOWNLOAD_ICON}</a>
  1530.                <button class="overlay-btn overlay-edit-btn" title="Edit this Image">${EDIT_ICON}</button>
  1531.            </div>
  1532.            <p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${finalPrompt}</p>
  1533.        `;
  1534.  
  1535.        const editBtn = card.querySelector('.overlay-edit-btn');
  1536.        editBtn.addEventListener('click', (e) => {
  1537.            e.preventDefault();
  1538.            if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(finalDataUri, false, filename);
  1539.        });
  1540.  
  1541.        galleryEl.prepend(card);
  1542.    }
  1543.  
  1544.    function renderVideoToGallery(videoUrl, originalPrompt, galleryEl) {
  1545.        const filename = `Grok Video - ${makeTimestamp()}.mp4`;
  1546.        const card = document.createElement('div');
  1547.        card.className = 'current-card';
  1548.        card.innerHTML = `
  1549.            <div class="img-wrapper">
  1550.                <video src="${videoUrl}" controls autoplay loop style="width: 100%; display: block; max-height: 50vh; object-fit: contain; background: #000;"></video>
  1551.                <button class="overlay-btn overlay-dl-btn force-dl" data-url="${videoUrl}" data-filename="${filename}" style="z-index: 50; right: 6px;" title="Download MP4">${DOWNLOAD_ICON}</button>
  1552.                <button class="overlay-btn overlay-edit-btn" style="z-index: 50; right: 40px;" title="Edit this Video">${EDIT_ICON}</button>
  1553.            </div>
  1554.            <p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${originalPrompt}</p>
  1555.        `;
  1556.  
  1557.        const editBtn = card.querySelector('.overlay-edit-btn');
  1558.        editBtn.addEventListener('click', (e) => {
  1559.            e.preventDefault();
  1560.            if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename);
  1561.        });
  1562.  
  1563.        const dlBtn = card.querySelector('.overlay-dl-btn');
  1564.        dlBtn.addEventListener('click', (e) => {
  1565.            e.preventDefault();
  1566.            const url = dlBtn.getAttribute('data-url');
  1567.            const fname = dlBtn.getAttribute('data-filename');
  1568.            const originalIcon = dlBtn.innerHTML;
  1569.  
  1570.            dlBtn.innerHTML = '<div class="loading-spinner" style="border-top-color: #10b981;"></div>';
  1571.            dlBtn.style.pointerEvents = 'none';
  1572.  
  1573.            // Use Tampermonkey's GM_xmlhttpRequest to bypass CORS
  1574.             if (typeof GM_xmlhttpRequest !== "undefined") {
  1575.                 GM_xmlhttpRequest({
  1576.                     method: 'GET',
  1577.                     url: url,
  1578.                     responseType: 'blob',
  1579.                     onload: function(response) {
  1580.                         if (response.status >= 200 && response.status < 300) {
  1581.                             const blobUrl = URL.createObjectURL(response.response);
  1582.                             const a = document.createElement('a');
  1583.                             a.style.display = 'none';
  1584.                             a.href = blobUrl;
  1585.                             a.download = fname;
  1586.                             document.body.appendChild(a);
  1587.                             a.click();
  1588.                             document.body.removeChild(a);
  1589.                             setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
  1590.                         } else {
  1591.                             window.open(url, '_blank'); // fallback
  1592.                         }
  1593.                         dlBtn.innerHTML = originalIcon;
  1594.                         dlBtn.style.pointerEvents = 'auto';
  1595.                     },
  1596.                     onerror: function() {
  1597.                         window.open(url, '_blank'); // fallback
  1598.                         dlBtn.innerHTML = originalIcon;
  1599.                         dlBtn.style.pointerEvents = 'auto';
  1600.                     }
  1601.                 });
  1602.             } else {
  1603.                 // Fallback for environments without GM_xmlhttpRequest
  1604.                 window.open(url, '_blank');
  1605.                 dlBtn.innerHTML = originalIcon;
  1606.                 dlBtn.style.pointerEvents = 'auto';
  1607.             }
  1608.         });
  1609.  
  1610.         galleryEl.prepend(card);
  1611.     }
  1612.  
  1613.     if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initApp); }
  1614.     else { initApp(); }
  1615.  
  1616. })();
Add Comment
Please, Sign In to add comment