Guest User

Untitled

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