Guest User

Untitled

a guest
Apr 1st, 2026
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         xAI Pro Studio Frontend (v29 - Video Warnings & Settings Export)
  3. // @namespace    http://tampermonkey.net/
  4. // @version      29
  5. // @description  Full-Screen UI, Exif Fix, Multi-Image Routing, Dynamic Prompts, Auto-Retry, Tag Previews, Configurable Warnings, Export/Import Settings
  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.notifications === 'undefined') appSettings.notifications = true;
  32.     if (typeof appSettings.customCSS === 'undefined') appSettings.customCSS = "";
  33.     if (typeof appSettings.saveAsPng === 'undefined') appSettings.saveAsPng = false;
  34.     if (typeof appSettings.apiBaseUrl === 'undefined') appSettings.apiBaseUrl = "";
  35.     if (typeof appSettings.videoPollTimeout === 'undefined') appSettings.videoPollTimeout = 300;
  36.     if (typeof appSettings.autoRetryStuckVideo === 'undefined') appSettings.autoRetryStuckVideo = false;
  37.  
  38.     // New Settings
  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="margin-top: 4px;">
  594.                         <label>Video Polling Timeout (Seconds)</label>
  595.                         <input type="number" id="set-video-timeout" min="10" step="10">
  596.                     </div>
  597.  
  598.                     <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;"></div>
  599.  
  600.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  601.                         <input type="checkbox" id="set-suppress-warning" style="width: 16px; height: 16px;">
  602.                         <label for="set-suppress-warning" style="margin: 0; cursor: pointer; color: #fcd34d;">Suppress yellow ">8s video edit" warning</label>
  603.                     </div>
  604.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  605.                         <input type="checkbox" id="set-video-autoplay" style="width: 16px; height: 16px;">
  606.                         <label for="set-video-autoplay" style="margin: 0; cursor: pointer;">Autoplay generated videos in gallery</label>
  607.                     </div>
  608.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  609.                         <input type="checkbox" id="set-video-muted" style="width: 16px; height: 16px;">
  610.                         <label for="set-video-muted" style="margin: 0; cursor: pointer;">Start generated videos muted</label>
  611.                     </div>
  612.  
  613.                     <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;">
  614.                         <label>Custom CSS Overrides</label>
  615.                         <textarea id="set-custom-css" style="font-family: monospace; height: 60px; font-size: 11px;" placeholder="/* e.g., #xai-pro-app { background: red; } */"></textarea>
  616.                     </div>
  617.  
  618.                     <div style="display: flex; gap: 8px; margin-top: 5px; border-top: 1px solid #334155; padding-top: 10px;">
  619.                         <button id="export-data-btn" class="btn-secondary" style="flex:1;">📤 Export Data</button>
  620.                         <button id="import-data-btn" class="btn-secondary" style="flex:1;">📥 Import Data</button>
  621.                         <input type="file" id="import-data-file" accept=".json" style="display: none;">
  622.                     </div>
  623.  
  624.                     <div style="display: flex; gap: 8px; margin-top: 5px;">
  625.                         <button id="save-settings-btn" class="btn-primary" style="flex:1;">Save Settings</button>
  626.                         <button id="close-settings-btn" class="btn-secondary" style="flex:1;">Cancel</button>
  627.                     </div>
  628.                 </div>
  629.             </div>
  630.  
  631.             <!-- FAVORITES MODAL -->
  632.             <div id="xai-fav-modal" class="modal-overlay">
  633.                 <div class="modal-box" style="width: 550px;">
  634.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  635.                         <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⭐ Favorite Prompts</h3>
  636.                         <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>
  637.                     </div>
  638.                     <button id="add-current-fav-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);">➕ Save Current Prompt to Favorites</button>
  639.                     <div id="fav-list" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px;"></div>
  640.                 </div>
  641.             </div>
  642.  
  643.             <!-- CUSTOM PAYLOAD DEBUGGER MODAL -->
  644.             <div id="xai-payload-modal" class="modal-overlay">
  645.                 <div class="modal-box" style="width: 550px;">
  646.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  647.                         <h3 style="margin:0; font-size: 15px; color: #f8fafc;">API Payload Debugger</h3>
  648.                         <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>
  649.                     </div>
  650.                     <div><label>Endpoint URL:</label><input type="text" id="payload-endpoint" style="font-family: monospace;" value="/v1/images/generations"></div>
  651.                     <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>
  652.                     <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>
  653.                     <div id="custom-payload-status" style="font-size: 11px; color: #64748b; text-align: center;">Ready</div>
  654.                 </div>
  655.             </div>
  656.         </div>
  657.     `;
  658.  
  659.     // ─── INITIALIZATION ───────────────────────────────────────────────────────
  660.     let updateUIForEditMedia = null;
  661.  
  662.     const initApp = () => {
  663.         if (!document.body) return setTimeout(initApp, 50);
  664.  
  665.         const hideOriginals = () => {
  666.             Array.from(document.body.children).forEach(child => {
  667.                 if (child.id !== 'xai-pro-app' && !['SCRIPT', 'STYLE', 'LINK'].includes(child.tagName)) {
  668.                     child.style.display = 'none';
  669.                 }
  670.             });
  671.         };
  672.         hideOriginals();
  673.         new MutationObserver(hideOriginals).observe(document.body, { childList: true });
  674.  
  675.         if (!document.getElementById('xai-pro-app')) {
  676.             const style = document.createElement('style');
  677.             style.innerHTML = UI_CSS;
  678.             document.head.appendChild(style);
  679.  
  680.             const customStyle = document.createElement('style');
  681.             customStyle.id = 'xai-custom-css-block';
  682.             customStyle.innerHTML = appSettings.customCSS;
  683.             document.head.appendChild(customStyle);
  684.  
  685.             document.body.insertAdjacentHTML('beforeend', UI_HTML);
  686.             bindLogic();
  687.         }
  688.     };
  689.  
  690.     let referenceMedia =[];
  691.     let currentAr = localStorage.getItem('xai_api_ar') || 'Auto';
  692.     let fullPayloadMemory = {};
  693.     let currentAbortController = null;
  694.     let isRequestCancelled = false;
  695.  
  696.     function saveRefs() {
  697.         try {
  698.             localStorage.setItem('xai_api_refs', JSON.stringify(referenceMedia));
  699.         } catch (e) {
  700.             console.warn("[xAI Studio] Could not save references to localStorage (quota exceeded). Images will not persist after refresh.");
  701.         }
  702.     }
  703.  
  704.     function bindLogic() {
  705.         const els = {
  706.             app: document.getElementById('xai-pro-app'),
  707.             prompt: document.getElementById('xai-api-prompt'),
  708.             promptBackdrop: document.getElementById('prompt-backdrop'),
  709.             warningsContainer: document.getElementById('warnings-container'),
  710.             promptContainer: document.querySelector('.prompt-container'),
  711.             action: document.getElementById('master-action'),
  712.             resImg: document.getElementById('xai-api-res-img'),
  713.             resVid: document.getElementById('xai-api-res-vid'),
  714.             n: document.getElementById('xai-api-n'),
  715.             duration: document.getElementById('xai-api-duration'),
  716.             loops: document.getElementById('xai-api-loops'),
  717.  
  718.             settingAr: document.getElementById('setting-ar'),
  719.             settingResImg: document.getElementById('setting-res-img'),
  720.             settingResVid: document.getElementById('setting-res-vid'),
  721.             settingBatch: document.getElementById('setting-batch'),
  722.             settingDuration: document.getElementById('setting-duration'),
  723.             settingLoops: document.getElementById('setting-loops'),
  724.  
  725.             fileInput: document.getElementById('xai-api-file'),
  726.             dropzone: document.getElementById('col-right-dropzone'),
  727.             uploadPlaceholder: document.getElementById('xai-upload-placeholder'),
  728.             refList: document.getElementById('xai-ref-list'),
  729.             refTitle: document.getElementById('ref-panel-title'),
  730.  
  731.             btn: document.getElementById('xai-api-generate'),
  732.             previewBtn: document.getElementById('xai-preview-btn'),
  733.             cancelBtn: document.getElementById('xai-cancel-btn'),
  734.             status: document.getElementById('xai-api-status'),
  735.             history: document.getElementById('xai-history'),
  736.             currentImages: document.getElementById('xai-current-images'),
  737.             reset: document.getElementById('xai-reset-btn'),
  738.  
  739.             arSelectBox: document.getElementById('ar-select-box'),
  740.             arOptionsCont: document.getElementById('ar-options-container'),
  741.             arSelectedIcon: document.getElementById('ar-selected-icon'),
  742.             arSelectedText: document.getElementById('ar-selected-text'),
  743.  
  744.             lightbox: document.getElementById('xai-lightbox'),
  745.             lightboxImg: document.getElementById('xai-lightbox-img'),
  746.             lightboxDl: document.getElementById('xai-lightbox-dl'),
  747.  
  748.             previewBox: document.getElementById('tag-preview-box'),
  749.             previewImg: document.getElementById('tag-preview-img'),
  750.  
  751.             payloadModal: document.getElementById('xai-payload-modal'),
  752.             payloadEndpoint: document.getElementById('payload-endpoint'),
  753.             payloadCode: document.getElementById('payload-code'),
  754.             closePayloadBtn: document.getElementById('close-payload-btn'),
  755.             sendCustomBtn: document.getElementById('send-custom-payload-btn'),
  756.             customStatus: document.getElementById('custom-payload-status'),
  757.  
  758.             settingsBtn: document.getElementById('settings-btn'),
  759.             settingsModal: document.getElementById('xai-settings-modal'),
  760.             closeSettingsBtn: document.getElementById('close-settings-btn'),
  761.             saveSettingsBtn: document.getElementById('save-settings-btn'),
  762.  
  763.             exportDataBtn: document.getElementById('export-data-btn'),
  764.             importDataBtn: document.getElementById('import-data-btn'),
  765.             importDataFile: document.getElementById('import-data-file'),
  766.  
  767.             favBtn: document.getElementById('fav-prompts-btn'),
  768.             favModal: document.getElementById('xai-fav-modal'),
  769.             closeFavBtn: document.getElementById('close-fav-btn'),
  770.             addFavBtn: document.getElementById('add-current-fav-btn'),
  771.             favList: document.getElementById('fav-list')
  772.         };
  773.  
  774.         // ─── DYNAMIC WARNINGS MANAGER ───────────────────────────────────────────────
  775.         function updateWarnings() {
  776.             els.warningsContainer.innerHTML = '';
  777.             let html = '';
  778.  
  779.             // Prompt parameter warning
  780.             if (/--[a-zA-Z0-9_-]+=/.test(els.prompt.value)) {
  781.                 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>`;
  782.             }
  783.  
  784.             const action = els.action.value;
  785.             const duration = parseInt(els.duration.value) || 0;
  786.             const activeRefs = referenceMedia.filter(m => m.active).length;
  787.  
  788.             if (action === 'gen_video') {
  789.                 if (activeRefs > 0 && duration > 10) {
  790.                     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>`;
  791.                 }
  792.                 if (duration > 8 && !appSettings.suppressEditWarning) {
  793.                     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>`;
  794.                }
  795.            }
  796.  
  797.            els.warningsContainer.innerHTML = html;
  798.        }
  799.  
  800.        // ─── PROMPT HELPER & BACKDROP (HOVER) SYSTEM ────────────────────────────
  801.        function syncPromptBackdrop() {
  802.            const val = els.prompt.value;
  803.            updateWarnings();
  804.  
  805.            let html = val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  806.            const activeRefs = referenceMedia.filter(m => m.active);
  807.  
  808.            html = html.replace(/&lt;IMAGE_(\d+)&gt;/g, (match, idxStr) => {
  809.                const idx = parseInt(idxStr);
  810.                if (activeRefs[idx]) return `<span class="prompt-tag" data-idx="${idx}">${match}</span>`;
  811.                return match;
  812.            });
  813.  
  814.            html = html.replace(/\n/g, '<br>') + '<br>';
  815.            els.promptBackdrop.innerHTML = html;
  816.            els.promptBackdrop.scrollTop = els.prompt.scrollTop;
  817.            els.promptBackdrop.scrollLeft = els.prompt.scrollLeft;
  818.        }
  819.  
  820.        function setPromptVal(val) {
  821.            els.prompt.value = val;
  822.            localStorage.setItem('xai_api_prompt', val);
  823.            syncPromptBackdrop();
  824.        }
  825.  
  826.        if (localStorage.getItem('xai_api_prompt')) setPromptVal(localStorage.getItem('xai_api_prompt'));
  827.  
  828.        els.prompt.addEventListener('input', () => setPromptVal(els.prompt.value));
  829.        els.prompt.addEventListener('scroll', () => { els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft; });
  830.  
  831.        let hidePreviewTimeout;
  832.        els.prompt.addEventListener('mousemove', (e) => {
  833.            if (e.buttons !== 0) { els.previewBox.style.display = 'none'; return; }
  834.  
  835.            els.prompt.style.pointerEvents = 'none';
  836.            const el = document.elementFromPoint(e.clientX, e.clientY);
  837.            els.prompt.style.pointerEvents = 'auto';
  838.  
  839.            if (el && el.classList.contains('prompt-tag')) {
  840.                const idx = el.getAttribute('data-idx');
  841.                const activeRefs = referenceMedia.filter(m => m.active);
  842.                const media = activeRefs[parseInt(idx)];
  843.                if (media) {
  844.                    els.previewBox.style.display = 'block';
  845.                    els.previewImg.src = media.thumb || media.base64;
  846.  
  847.                    let targetX = e.clientX + 15; let targetY = e.clientY + 15;
  848.                    if (targetX + 160 > window.innerWidth) targetX = e.clientX - 165;
  849.                    if (targetY + 160 > window.innerHeight) targetY = e.clientY - 165;
  850.  
  851.                    els.previewBox.style.left = targetX + 'px';
  852.                    els.previewBox.style.top = targetY + 'px';
  853.                    clearTimeout(hidePreviewTimeout);
  854.                }
  855.            } else {
  856.                hidePreviewTimeout = setTimeout(() => els.previewBox.style.display = 'none', 50);
  857.            }
  858.        });
  859.        els.prompt.addEventListener('mouseleave', () => els.previewBox.style.display = 'none');
  860.  
  861.  
  862.        try {
  863.            const storedGen = JSON.parse(localStorage.getItem('xai_api_gen_settings') || '{}');
  864.            if (storedGen.action) els.action.value = storedGen.action;
  865.            if (storedGen.resImg) els.resImg.value = storedGen.resImg;
  866.            if (storedGen.resVid) els.resVid.value = storedGen.resVid;
  867.            if (storedGen.n) els.n.value = storedGen.n;
  868.            if (storedGen.duration) els.duration.value = storedGen.duration;
  869.            if (storedGen.loops) els.loops.value = storedGen.loops;
  870.        } catch(e) {}
  871.  
  872.        const updateGenSettingsMemory = () => {
  873.            localStorage.setItem('xai_api_gen_settings', JSON.stringify({
  874.                action: els.action.value, resImg: els.resImg.value, resVid: els.resVid.value,
  875.                n: els.n.value, duration: els.duration.value, loops: els.loops.value
  876.            }));
  877.        };
  878.        [els.action, els.resImg, els.resVid, els.n, els.duration, els.loops].forEach(el => el.addEventListener('change', updateGenSettingsMemory));
  879.        els.duration.addEventListener('change', updateWarnings);
  880.  
  881.        try {
  882.            const storedRefs = JSON.parse(localStorage.getItem('xai_api_refs'));
  883.            if (Array.isArray(storedRefs)) referenceMedia = storedRefs;
  884.        } catch(e) {}
  885.  
  886.        // ─── SETTINGS & EXPORT/IMPORT BINDINGS ───────────────────────────────────
  887.        els.settingsBtn.addEventListener('click', () => {
  888.            document.getElementById('set-retries').value = appSettings.retries;
  889.            document.getElementById('set-delay-min').value = appSettings.delayMin;
  890.            document.getElementById('set-delay-max').value = appSettings.delayMax;
  891.            document.getElementById('set-notifications').checked = appSettings.notifications;
  892.            document.getElementById('set-save-png').checked = appSettings.saveAsPng;
  893.            document.getElementById('set-auto-retry-video').checked = appSettings.autoRetryStuckVideo;
  894.            document.getElementById('set-video-timeout').value = appSettings.videoPollTimeout;
  895.  
  896.            document.getElementById('set-suppress-warning').checked = appSettings.suppressEditWarning;
  897.            document.getElementById('set-video-autoplay').checked = appSettings.videoAutoplay;
  898.            document.getElementById('set-video-muted').checked = appSettings.videoMuted;
  899.  
  900.            document.getElementById('set-api-base-url').value = appSettings.apiBaseUrl || '';
  901.            document.getElementById('set-custom-css').value = appSettings.customCSS || '';
  902.            els.settingsModal.style.display = 'flex';
  903.        });
  904.  
  905.        els.saveSettingsBtn.addEventListener('click', () => {
  906.            appSettings.retries = parseInt(document.getElementById('set-retries').value) || 20;
  907.            appSettings.delayMin = parseInt(document.getElementById('set-delay-min').value) || 2000;
  908.            appSettings.delayMax = Math.max(appSettings.delayMin, parseInt(document.getElementById('set-delay-max').value) || 4000);
  909.            appSettings.notifications = document.getElementById('set-notifications').checked;
  910.            appSettings.saveAsPng = document.getElementById('set-save-png').checked;
  911.            appSettings.autoRetryStuckVideo = document.getElementById('set-auto-retry-video').checked;
  912.            appSettings.videoPollTimeout = parseInt(document.getElementById('set-video-timeout').value) || 300;
  913.  
  914.            appSettings.suppressEditWarning = document.getElementById('set-suppress-warning').checked;
  915.            appSettings.videoAutoplay = document.getElementById('set-video-autoplay').checked;
  916.            appSettings.videoMuted = document.getElementById('set-video-muted').checked;
  917.  
  918.            appSettings.apiBaseUrl = document.getElementById('set-api-base-url').value.trim();
  919.            appSettings.customCSS = document.getElementById('set-custom-css').value;
  920.  
  921.            localStorage.setItem('xai_api_settings', JSON.stringify(appSettings));
  922.            document.getElementById('xai-custom-css-block').innerHTML = appSettings.customCSS;
  923.  
  924.            updateWarnings(); // In case the warning preference changed
  925.            els.settingsModal.style.display = 'none';
  926.        });
  927.  
  928.        els.closeSettingsBtn.addEventListener('click', () => els.settingsModal.style.display = 'none');
  929.  
  930.        // Export/Import Logic
  931.        els.exportDataBtn.addEventListener('click', () => {
  932.            const exportObj = {
  933.                settings: appSettings,
  934.                refs: referenceMedia
  935.            };
  936.            const blob = new Blob([JSON.stringify(exportObj, null, 2)], { type: 'application/json' });
  937.            const url = URL.createObjectURL(blob);
  938.            const a = document.createElement('a');
  939.            a.href = url;
  940.            a.download = `xAI_Pro_Studio_Backup_${makeTimestamp()}.json`;
  941.            a.click();
  942.            URL.revokeObjectURL(url);
  943.        });
  944.  
  945.        els.importDataBtn.addEventListener('click', () => els.importDataFile.click());
  946.        els.importDataFile.addEventListener('change', (e) => {
  947.            const file = e.target.files[0];
  948.            if (!file) return;
  949.            const reader = new FileReader();
  950.            reader.onload = (evt) => {
  951.                try {
  952.                    const parsed = JSON.parse(evt.target.result);
  953.                    if (parsed.settings) {
  954.                        appSettings = { ...appSettings, ...parsed.settings };
  955.                        localStorage.setItem('xai_api_settings', JSON.stringify(appSettings));
  956.                    }
  957.                    if (parsed.refs && Array.isArray(parsed.refs)) {
  958.                        referenceMedia = parsed.refs;
  959.                        saveRefs();
  960.                    }
  961.                    alert("Import successful! The page will now reload to apply settings.");
  962.                    location.reload();
  963.                } catch(err) {
  964.                    alert("Failed to parse the uploaded JSON file. Ensure it is a valid backup.");
  965.                }
  966.            };
  967.            reader.readAsText(file);
  968.            e.target.value = ''; // Reset file input
  969.        });
  970.  
  971.        // ─── FAVORITES BINDINGS ──────────────────────────────────────────────────
  972.        function renderFavList() {
  973.            els.favList.innerHTML = '';
  974.            if (favoritePrompts.length === 0) {
  975.                els.favList.innerHTML = '<div style="color: #64748b; font-size: 12px; text-align: center; margin-top: 15px;">No favorite prompts yet.</div>';
  976.                return;
  977.            }
  978.            favoritePrompts.forEach((promptText, idx) => {
  979.                const div = document.createElement('div');
  980.                div.className = 'fav-item';
  981.                div.innerHTML = `
  982.                    <div class="fav-text" title="${promptText.replace(/"/g, '&quot;')}">${promptText}</div>
  983.                    <button class="btn-secondary" style="padding: 2px 6px; font-size: 10px; border-color: #ef4444; color: #ef4444;">Del</button>
  984.                `;
  985.                div.querySelector('.fav-text').addEventListener('click', () => {
  986.                    setPromptVal(promptText);
  987.                    els.favModal.style.display = 'none';
  988.                });
  989.                div.querySelector('button').addEventListener('click', () => {
  990.                    favoritePrompts.splice(idx, 1);
  991.                    localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts));
  992.                    renderFavList();
  993.                });
  994.                els.favList.appendChild(div);
  995.            });
  996.        }
  997.  
  998.        els.favBtn.addEventListener('click', () => {
  999.            renderFavList();
  1000.            els.favModal.style.display = 'flex';
  1001.        });
  1002.        els.closeFavBtn.addEventListener('click', () => els.favModal.style.display = 'none');
  1003.        els.addFavBtn.addEventListener('click', () => {
  1004.            const p = els.prompt.value.trim();
  1005.            if (!p) return alert("Prompt is empty!");
  1006.            if (favoritePrompts.includes(p)) return alert("Already in favorites!");
  1007.            favoritePrompts.unshift(p);
  1008.            localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts));
  1009.            renderFavList();
  1010.        });
  1011.  
  1012.        // ─── PROMPT BOX EXIF DRAG & DROP ──────────────────────────────────────────
  1013.        els.prompt.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.add('prompt-drag-over'); });
  1014.        els.prompt.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over'); });
  1015.        els.prompt.addEventListener('drop', async (e) => {
  1016.            e.preventDefault(); e.stopPropagation();
  1017.            els.promptContainer.classList.remove('prompt-drag-over');
  1018.            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  1019.                const file = e.dataTransfer.files[0];
  1020.                const oldVal = els.prompt.value;
  1021.                setPromptVal("Extracting prompt from EXIF...");
  1022.                const extractedPrompt = await extractPromptFromImage(file);
  1023.                if (extractedPrompt) {
  1024.                    setPromptVal(extractedPrompt);
  1025.                } else {
  1026.                    setPromptVal(oldVal);
  1027.                    alert("No prompt found in this image's EXIF data (or not a valid JPEG).");
  1028.                }
  1029.            }
  1030.        });
  1031.  
  1032.        // ─── MASTER ACTION UI LOGIC ───────────────────────────────────────────────
  1033.        function getMaxMedia() {
  1034.            const val = els.action.value;
  1035.            if (val === 'gen_image') return 5;
  1036.            if (val === 'gen_video') return 7;
  1037.            return 1;
  1038.        }
  1039.  
  1040.        function updateActionUI() {
  1041.            const val = els.action.value;
  1042.  
  1043.            if (val === 'gen_image') {
  1044.                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';
  1045.            } else if (val === 'gen_video') {
  1046.                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';
  1047.                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>`;
  1048.                if (localStorage.getItem('xai_api_gen_settings') && JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration <= 15) {
  1049.                    els.duration.value = JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration;
  1050.                } else els.duration.value = "5";
  1051.            } else if (val === 'edit_video') {
  1052.                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';
  1053.            } else if (val === 'extend_video') {
  1054.                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';
  1055.                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>`;
  1056.                if (localStorage.getItem('xai_api_gen_settings') && JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration <= 10) {
  1057.                    els.duration.value = JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration;
  1058.                } else els.duration.value = "6";
  1059.            }
  1060.  
  1061.            const max = getMaxMedia();
  1062.            els.refTitle.innerText = `Reference Media (Max Active: ${max})`;
  1063.  
  1064.            let activeCount = 0;
  1065.            referenceMedia.forEach(m => {
  1066.                let valid = true;
  1067.                if ((val === 'gen_image' || val === 'gen_video') && m.isVideo) valid = false;
  1068.                if ((val === 'edit_video' || val === 'extend_video') && !m.isVideo) valid = false;
  1069.  
  1070.                if (!valid) m.active = false;
  1071.                else if (m.active) {
  1072.                    activeCount++;
  1073.                    if (activeCount > max) m.active = false;
  1074.                }
  1075.            });
  1076.            renderRefList();
  1077.            updateWarnings();
  1078.        }
  1079.  
  1080.        els.action.addEventListener('change', updateActionUI);
  1081.        updateActionUI();
  1082.  
  1083.        // ─── INSTANT EDIT BINDING HANDLER ─────────────────────────────────────────
  1084.        updateUIForEditMedia = (mediaUrl, isVideo, fileName) => {
  1085.            referenceMedia.forEach(m => m.active = false);
  1086.  
  1087.            referenceMedia.unshift({
  1088.                id: Date.now() + Math.random(),
  1089.                base64: mediaUrl,
  1090.                isVideo: isVideo,
  1091.                active: true,
  1092.                thumb: isVideo ? null : mediaUrl,
  1093.                fileName: fileName || (isVideo ? 'Edited_Video.mp4' : 'Edited_Image.png')
  1094.            });
  1095.  
  1096.            els.action.value = isVideo ? 'edit_video' : 'gen_image';
  1097.            updateActionUI();
  1098.            updateGenSettingsMemory();
  1099.            renderRefList();
  1100.            saveRefs();
  1101.        };
  1102.  
  1103.        // ─── BUILD PAYLOAD LOGIC ──────────────────────────────────────────────────
  1104.        function buildPayloadData(dynamicPromptText) {
  1105.            const action = els.action.value;
  1106.            const payload = {
  1107.                model: action === 'gen_image' ? "grok-imagine-image" : "grok-imagine-video",
  1108.                prompt: dynamicPromptText,
  1109.            };
  1110.  
  1111.            const ar = currentAr.toLowerCase();
  1112.            const activeRefs = referenceMedia.filter(m => m.active);
  1113.  
  1114.            if (action === 'gen_image') {
  1115.                payload.n = parseInt(els.n.value); payload.resolution = els.resImg.value; payload.response_format = "b64_json";
  1116.                if (ar !== 'auto') payload.aspect_ratio = ar; else if (activeRefs.length > 0) payload.aspect_ratio = 'auto';
  1117.  
  1118.                if (activeRefs.length > 0) {
  1119.                    if (activeRefs.length === 1) payload.image = { url: activeRefs[0].base64 };
  1120.                    else payload.images = activeRefs.map(m => ({ type: "image_url", url: m.base64 }));
  1121.                }
  1122.            } else if (action === 'gen_video') {
  1123.                payload.duration = parseInt(els.duration.value); payload.resolution = els.resVid.value;
  1124.                if (ar !== 'auto') payload.aspect_ratio = ar;
  1125.                if (activeRefs.length > 0) payload.reference_images = activeRefs.map(m => ({ url: m.base64 }));
  1126.            } else if (action === 'edit_video') {
  1127.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  1128.            } else if (action === 'extend_video') {
  1129.                payload.duration = parseInt(els.duration.value);
  1130.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  1131.            }
  1132.            return payload;
  1133.        }
  1134.  
  1135.        // ─── CUSTOM PAYLOAD DEBUGGER LOGIC ────────────────────────────────────────
  1136.        els.previewBtn.addEventListener('click', () => {
  1137.            const dynamicPrompt = parseDynamicPrompt(els.prompt.value.trim());
  1138.            fullPayloadMemory = buildPayloadData(dynamicPrompt);
  1139.            const displayP = JSON.parse(JSON.stringify(fullPayloadMemory));
  1140.            const trunc = "[BASE64_TRUNCATED_FOR_PREVIEW]";
  1141.  
  1142.            if (displayP.image) { if (Array.isArray(displayP.image)) displayP.image.forEach(img => img.url = trunc); else displayP.image.url = trunc; }
  1143.            if (displayP.images && Array.isArray(displayP.images)) displayP.images.forEach(img => img.url = trunc);
  1144.            if (displayP.reference_images && Array.isArray(displayP.reference_images)) displayP.reference_images.forEach(img => img.url = trunc);
  1145.            if (displayP.video) displayP.video.url = trunc;
  1146.  
  1147.            const activeRefs = referenceMedia.filter(m => m.active);
  1148.            let endpoint = '/v1/images/generations';
  1149.            if (els.action.value === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1150.            else if (els.action.value === 'gen_video') endpoint = '/v1/videos/generations';
  1151.            else if (els.action.value === 'edit_video') endpoint = '/v1/videos/edits';
  1152.            else if (els.action.value === 'extend_video') endpoint = '/v1/videos/extensions';
  1153.  
  1154.            els.payloadEndpoint.value = endpoint;
  1155.            els.payloadCode.value = JSON.stringify(displayP, null, 2);
  1156.            els.payloadModal.style.display = 'flex';
  1157.        });
  1158.  
  1159.        els.closePayloadBtn.addEventListener('click', () => els.payloadModal.style.display = 'none');
  1160.  
  1161.        function injectBase64(editedObj, originalObj) {
  1162.            if (!editedObj || typeof editedObj !== 'object') return;
  1163.            for (let key in editedObj) {
  1164.                if (typeof editedObj[key] === 'string' && editedObj[key] === '[BASE64_TRUNCATED_FOR_PREVIEW]') {
  1165.                    if (originalObj && originalObj[key]) editedObj[key] = originalObj[key];
  1166.                } else if (typeof editedObj[key] === 'object') { injectBase64(editedObj[key], originalObj ? originalObj[key] : null); }
  1167.            }
  1168.        }
  1169.  
  1170.        els.sendCustomBtn.addEventListener('click', async () => {
  1171.            initAudio();
  1172.            let customPayload;
  1173.            try { customPayload = JSON.parse(els.payloadCode.value); }
  1174.            catch(e) { return alert("Invalid JSON format in textarea!"); }
  1175.  
  1176.            injectBase64(customPayload, fullPayloadMemory);
  1177.            const endpoint = els.payloadEndpoint.value.trim();
  1178.            const isImage = customPayload.model === "grok-imagine-image";
  1179.  
  1180.            stealthIdentityReset();
  1181.  
  1182.            els.sendCustomBtn.disabled = true;
  1183.            els.sendCustomBtn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Processing...</div>`;
  1184.            isRequestCancelled = false;
  1185.  
  1186.            const ok = await executeGenerationSingle(endpoint, customPayload, isImage, els.customStatus, 1, 1);
  1187.  
  1188.            els.sendCustomBtn.disabled = false;
  1189.            els.sendCustomBtn.innerHTML = `<div class="btn-content">🚀 Send Custom Payload</div>`;
  1190.            if (ok) notifyUser(false); else notifyUser(true);
  1191.        });
  1192.  
  1193.        // ─── CSP-SAFE DELEGATED LIGHTBOX LOGIC ────────────────────────────────────
  1194.        els.app.addEventListener('click', (e) => {
  1195.            if (e.target && e.target.classList.contains('zoomable') && e.target.tagName === 'IMG') {
  1196.                els.lightboxImg.src = e.target.src; els.lightboxDl.href = e.target.src; els.lightboxDl.download = e.target.dataset.filename || 'Reference_Image.jpg';
  1197.                els.lightbox.style.display = 'flex';
  1198.            }
  1199.        });
  1200.        els.lightbox.addEventListener('click', (e) => {
  1201.            if (e.target.closest('#xai-lightbox-dl')) return;
  1202.            if (e.target.closest('.modal-box')) return;
  1203.            els.lightbox.style.display = 'none';
  1204.        });
  1205.        document.addEventListener('keydown', (e) => { if(e.key === 'Escape') { Array.from(document.querySelectorAll('.modal-overlay')).forEach(m => m.style.display = 'none'); } });
  1206.  
  1207.        // ─── FIXED FLOATING AR DROPDOWN LOGIC ─────────────────────────────────────
  1208.        function renderArOptions() {
  1209.            els.arOptionsCont.innerHTML = '';
  1210.            arData.forEach(ar => {
  1211.                const opt = document.createElement('div'); opt.className = 'ar-option';
  1212.                opt.innerHTML = `${createArIcon(ar.w, ar.h, ar.isAuto)} <span>${ar.label}</span>`;
  1213.                opt.addEventListener('click', () => { setAr(ar); els.arOptionsCont.style.display = 'none'; });
  1214.                els.arOptionsCont.appendChild(opt);
  1215.            });
  1216.        }
  1217.        function setAr(arObj) {
  1218.            currentAr = arObj.label; localStorage.setItem('xai_api_ar', currentAr);
  1219.            els.arSelectedIcon.innerHTML = createArIcon(arObj.w, arObj.h, arObj.isAuto); els.arSelectedText.innerText = arObj.label;
  1220.        }
  1221.        renderArOptions();
  1222.        const initialAr = arData.find(a => a.label === currentAr) || arData[0]; setAr(initialAr);
  1223.  
  1224.        els.arSelectBox.addEventListener('click', (e) => {
  1225.            e.stopPropagation();
  1226.            if (els.arOptionsCont.style.display === 'block') { els.arOptionsCont.style.display = 'none'; return; }
  1227.            const rect = els.arSelectBox.getBoundingClientRect();
  1228.            els.arOptionsCont.style.top = (rect.bottom + 5) + 'px'; els.arOptionsCont.style.left = rect.left + 'px'; els.arOptionsCont.style.width = rect.width + 'px';
  1229.            els.arOptionsCont.style.display = 'block';
  1230.        });
  1231.        document.addEventListener('click', (e) => { if (!els.arOptionsCont.contains(e.target)) els.arOptionsCont.style.display = 'none'; });
  1232.  
  1233.        // ─── UNLIMITED MULTI-IMAGE DRAG/DROP WITH VIDEO THUMBNAILS ────────────────
  1234.        async function processFile(file) {
  1235.            const isVid = file.type.startsWith('video/'); const isImg = file.type.startsWith('image/');
  1236.            if (!isVid && !isImg) return;
  1237.  
  1238.            if (isVid && (els.action.value === 'gen_image' || els.action.value === 'gen_video')) { els.action.value = 'edit_video'; updateActionUI(); updateGenSettingsMemory(); }
  1239.            else if (isImg && (els.action.value === 'edit_video' || els.action.value === 'extend_video')) { els.action.value = 'gen_image'; updateActionUI(); updateGenSettingsMemory(); }
  1240.  
  1241.            const max = getMaxMedia();
  1242.            const activeCount = referenceMedia.filter(m => m.active).length;
  1243.  
  1244.            let thumbBase64 = null;
  1245.            if (isVid) thumbBase64 = await generateVideoThumbnail(file);
  1246.  
  1247.            const reader = new FileReader();
  1248.            reader.onload = (event) => {
  1249.                referenceMedia.push({
  1250.                    id: Date.now() + Math.random(),
  1251.                    base64: event.target.result,
  1252.                    isVideo: isVid,
  1253.                    active: activeCount < max,
  1254.                    thumb: thumbBase64,
  1255.                    fileName: file.name
  1256.                });
  1257.                renderRefList();
  1258.                if (isImg) setAr(arData[0]);
  1259.            };
  1260.            reader.readAsDataURL(file);
  1261.        }
  1262.  
  1263.        let draggedIndex = null;
  1264.        function renderRefList() {
  1265.            els.refList.innerHTML = '';
  1266.            referenceMedia.forEach((media, index) => {
  1267.                const item = document.createElement('div');
  1268.                item.className = 'ref-item';
  1269.                item.draggable = true;
  1270.  
  1271.                const activeRefs = referenceMedia.filter(m => m.active);
  1272.                const dynamicIndex = media.active ? activeRefs.indexOf(media) : '?';
  1273.                const actionVal = els.action.value;
  1274.                const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
  1275.  
  1276.                let thumbHtml = '';
  1277.                if (media.isVideo) {
  1278.                    if (media.thumb) {
  1279.                        thumbHtml = `
  1280.                            <div style="position: relative; width: 90px; height: 90px; flex-shrink: 0;">
  1281.                                <img src="${media.thumb}" class="ref-thumb" style="width: 100%; height: 100%;" title="${media.fileName || 'Video'}">
  1282.                                <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>
  1283.                            </div>
  1284.                        `;
  1285.                    } else {
  1286.                        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>`;
  1287.                    }
  1288.                } else {
  1289.                    thumbHtml = `<img src="${media.base64}" class="ref-thumb zoomable" data-filename="${media.fileName || 'Reference_'+(index+1)+'.jpg'}" title="${media.fileName || 'Click to view'}">`;
  1290.                }
  1291.  
  1292.                let insertBtnHtml = '';
  1293.                if (!media.isVideo) {
  1294.                    if (disableInsert) {
  1295.                        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>`;
  1296.                    } else if (!media.active) {
  1297.                        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>`;
  1298.                    } else {
  1299.                        insertBtnHtml = `<button class="ref-action-btn ref-insert" title="Insert into prompt">➕ &lt;IMAGE_${dynamicIndex}&gt;</button>`;
  1300.                    }
  1301.                }
  1302.  
  1303.                item.innerHTML = `
  1304.                    <div class="ref-handle">☰</div>
  1305.                    ${thumbHtml}
  1306.                    <div class="ref-info">
  1307.                        <span style="font-size: 12px; color: #e2e8f0; font-weight: 600;">Ref ${index + 1} ${media.isVideo ? '(Video)' : ''}</span>
  1308.                        <label class="ref-toggle-label">
  1309.                            <input type="checkbox" class="ref-active-toggle" ${media.active ? 'checked' : ''}> Use in Payload
  1310.                        </label>
  1311.                        <div class="ref-btn-group">
  1312.                            ${insertBtnHtml}
  1313.                            <button class="ref-action-btn ref-del">Remove</button>
  1314.                        </div>
  1315.                    </div>
  1316.                `;
  1317.  
  1318.                const insertBtn = item.querySelector('.ref-insert');
  1319.                if (insertBtn && media.active) {
  1320.                    insertBtn.addEventListener('click', (e) => {
  1321.                        const currentAction = els.action.value;
  1322.                        if (currentAction === 'edit_video' || currentAction === 'extend_video') {
  1323.                            e.preventDefault();
  1324.                            return alert("<IMAGE_X> tags are not supported in Edit Video and Extend Video modes.");
  1325.                        }
  1326.  
  1327.                        const promptEl = els.prompt;
  1328.                        const tag = `<IMAGE_${dynamicIndex}>`;
  1329.                        const startPos = promptEl.selectionStart;
  1330.                        const endPos = promptEl.selectionEnd;
  1331.  
  1332.                        setPromptVal(promptEl.value.substring(0, startPos) + tag + promptEl.value.substring(endPos, promptEl.value.length));
  1333.                        promptEl.selectionStart = promptEl.selectionEnd = startPos + tag.length;
  1334.                        promptEl.focus();
  1335.                    });
  1336.                }
  1337.  
  1338.                if (!media.active) item.classList.add('inactive');
  1339.  
  1340.                item.querySelector('.ref-active-toggle').addEventListener('change', (e) => {
  1341.                    const max = getMaxMedia();
  1342.                    const currentlyActive = referenceMedia.filter(r => r.active).length;
  1343.  
  1344.                    if (e.target.checked && currentlyActive >= max) {
  1345.                        alert(`You can only have up to ${max} active references for this mode.`);
  1346.                        e.target.checked = false;
  1347.                        return;
  1348.                    }
  1349.                    media.active = e.target.checked;
  1350.                    saveRefs();
  1351.                    renderRefList();
  1352.                    syncPromptBackdrop();
  1353.                    updateWarnings();
  1354.                });
  1355.  
  1356.                item.addEventListener('dragstart', (e) => { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; setTimeout(() => item.classList.add('dragging'), 0); });
  1357.                item.addEventListener('dragend', () => { item.classList.remove('dragging'); draggedIndex = null; document.querySelectorAll('.ref-item').forEach(el => el.classList.remove('drag-over-top', 'drag-over-bottom')); });
  1358.                item.addEventListener('dragover', (e) => {
  1359.                    e.preventDefault(); if (draggedIndex === null || draggedIndex === index) return;
  1360.                    const rect = item.getBoundingClientRect();
  1361.                    if (e.clientY - rect.top < rect.height / 2) { item.classList.add('drag-over-top'); item.classList.remove('drag-over-bottom'); }
  1362.                    else { item.classList.add('drag-over-bottom'); item.classList.remove('drag-over-top'); }
  1363.                });
  1364.                item.addEventListener('dragleave', () => item.classList.remove('drag-over-top', 'drag-over-bottom'));
  1365.                item.addEventListener('drop', (e) => {
  1366.                    e.preventDefault(); item.classList.remove('drag-over-top', 'drag-over-bottom');
  1367.                    if (draggedIndex === null || draggedIndex === index) return;
  1368.                    const rect = item.getBoundingClientRect();
  1369.                    let insertIndex = (e.clientY - rect.top) < rect.height / 2 ? index : index + 1;
  1370.                    if (draggedIndex < insertIndex) insertIndex--;
  1371.                    const [movedImage] = referenceMedia.splice(draggedIndex, 1);
  1372.                    referenceMedia.splice(insertIndex, 0, movedImage); renderRefList(); syncPromptBackdrop();
  1373.                });
  1374.  
  1375.                item.querySelector('.ref-del').addEventListener('click', () => { referenceMedia.splice(index, 1); renderRefList(); syncPromptBackdrop(); updateWarnings(); });
  1376.                els.refList.appendChild(item);
  1377.            });
  1378.            saveRefs();
  1379.        }
  1380.  
  1381.        els.uploadPlaceholder.addEventListener('click', () => { els.fileInput.click(); });
  1382.        els.fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(processFile); els.fileInput.value = ''; });
  1383.        document.addEventListener('paste', (e) => {
  1384.            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;
  1385.            const items = e.clipboardData.items; for (let i = 0; i < items.length; i++) if (items[i].type.indexOf('image') !== -1) processFile(items[i].getAsFile());
  1386.        });
  1387.  
  1388.        els.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); els.dropzone.classList.add('drag-over'); });
  1389.        els.dropzone.addEventListener('dragleave', () => els.dropzone.classList.remove('drag-over'));
  1390.        els.dropzone.addEventListener('drop', (e) => { e.preventDefault(); els.dropzone.classList.remove('drag-over'); if (e.dataTransfer.files) Array.from(e.dataTransfer.files).forEach(processFile); });
  1391.  
  1392.        // ─── CANCEL BUTTON LOGIC ─────────────────────────────────────────────────
  1393.        els.cancelBtn.addEventListener('click', () => {
  1394.            isRequestCancelled = true;
  1395.            if (currentAbortController) currentAbortController.abort();
  1396.            els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex';
  1397.            els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1398.            els.status.innerText = "Request Cancelled."; els.status.className = ""; els.status.style.color = "#ef4444";
  1399.        });
  1400.  
  1401.        // ─── MASTER GENERATION LOGIC ──────────────────────────────────────────────
  1402.        async function executeGenerationSingle(endpoint, payload, isImageAction, statusEl, currentLoop, totalLoops) {
  1403.            let loopPrefix = totalLoops > 1 ? `[Run ${currentLoop}/${totalLoops}] ` : '';
  1404.            statusEl.innerText = `${loopPrefix}Processing request...`;
  1405.            statusEl.className = "status-pulsing";
  1406.  
  1407.            currentAbortController = new AbortController();
  1408.  
  1409.            let attempts = 0; let success = false;
  1410.            while (attempts < appSettings.retries && !success && !isRequestCancelled) {
  1411.                try {
  1412.                    statusEl.innerText = `${loopPrefix}Sending request to xAI...`;
  1413.  
  1414.                    const fullEndpoint = getApiUrl(endpoint);
  1415.                    const response = await fetch(fullEndpoint, {
  1416.                        method: 'POST',
  1417.                        headers: { 'Content-Type': 'application/json' },
  1418.                        body: JSON.stringify(payload),
  1419.                        signal: currentAbortController.signal
  1420.                    });
  1421.  
  1422.                    if (response.status === 429 || response.status === 503 || response.status === 500 || response.status === 502) {
  1423.                        attempts++;
  1424.                        statusEl.innerText = `${loopPrefix}Busy (Error ${response.status}). Retrying... [${attempts}/${appSettings.retries}]`;
  1425.                        const delay = Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin;
  1426.                        await sleep(delay);
  1427.                        continue;
  1428.                    }
  1429.  
  1430.                    if (!response.ok) {
  1431.                        let errMsg = `HTTP ${response.status}`;
  1432.                        try {
  1433.                            const errData = await response.json();
  1434.                            if (errData.error && errData.error.message) errMsg += `\n${errData.error.message}`;
  1435.                            else if (errData.detail) errMsg += `\n${JSON.stringify(errData.detail)}`;
  1436.                        } catch(e) {}
  1437.                        throw new Error(errMsg);
  1438.                    }
  1439.  
  1440.                    const data = await response.json();
  1441.  
  1442.                    if (isImageAction) {
  1443.                        if (data && data.data && Array.isArray(data.data)) {
  1444.                            success = true;
  1445.                            statusEl.innerText = `${loopPrefix}Processing final images...`;
  1446.                            statusEl.style.color = "#10b981";
  1447.                            statusEl.className = "";
  1448.  
  1449.                            await Promise.all(data.data.map((imgObj, index) =>
  1450.                                processAndRenderImage(imgObj, payload.prompt, index + 1, data.data.length, els.currentImages)
  1451.                            ));
  1452.  
  1453.                            statusEl.innerText = "Ready";
  1454.                            statusEl.style.color = "#64748b";
  1455.                        } else throw new Error("Invalid response format.");
  1456.                    } else {
  1457.                        const reqId = data.request_id;
  1458.                        if (!reqId) throw new Error("No Request ID returned.");
  1459.  
  1460.                        let videoReady = false;
  1461.                        let pollCount = 0;
  1462.                        const MAX_POLLS = Math.max(1, Math.ceil(appSettings.videoPollTimeout / 5));
  1463.  
  1464.                        while (!videoReady && !isRequestCancelled) {
  1465.                            pollCount++;
  1466.                            if (pollCount > MAX_POLLS) throw new Error("Timeout: Video likely dropped by filters or stuck in queue.");
  1467.                            await sleep(5000);
  1468.                            if (isRequestCancelled) break;
  1469.  
  1470.                            const pollRes = await fetch(getApiUrl(`/v1/videos/${reqId}`), { signal: currentAbortController.signal });
  1471.                            if (!pollRes.ok) continue;
  1472.  
  1473.                            const pollData = await pollRes.json();
  1474.                            if (pollData.error) throw new Error(`API Error: ${pollData.error.message || JSON.stringify(pollData.error)}`);
  1475.  
  1476.                            const state = (pollData.status || pollData.state || 'processing').toLowerCase();
  1477.                            statusEl.innerText = `${loopPrefix}Polling video (Status: ${state})...[${pollCount}/${MAX_POLLS}]`;
  1478.  
  1479.                            if (state === 'done' || state === 'completed') {
  1480.                                videoReady = true;
  1481.                                success = true;
  1482.                                statusEl.innerText = "Ready"; statusEl.className = ""; statusEl.style.color = "#94a3b8";
  1483.                                renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1484.                            } else if (['failed', 'expired', 'rejected', 'blocked', 'moderated', 'nsfw'].includes(state) || pollData.is_sensitive) {
  1485.                                if (pollData.video && pollData.video.url) {
  1486.                                    videoReady = true;
  1487.                                    success = true;
  1488.                                    statusEl.innerText = `${loopPrefix}Warning: Flagged as ${state}, but recovered!`;
  1489.                                    statusEl.className = ""; statusEl.style.color = "#d97706";
  1490.                                    renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1491.                                } else {
  1492.                                    throw new Error(`Generation halted. Reason: ${state}`);
  1493.                                }
  1494.                            }
  1495.                        }
  1496.                    }
  1497.  
  1498.                } catch (err) {
  1499.                    if (err.name === 'AbortError' || isRequestCancelled) {
  1500.                        statusEl.innerText = "Request Cancelled."; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1501.                        return false;
  1502.                    } else if ((err.message.includes("Timeout: Video") || err.message.includes("Generation halted.")) && appSettings.autoRetryStuckVideo) {
  1503.                        attempts++;
  1504.                        if (attempts >= appSettings.retries) {
  1505.                            statusEl.innerText = `${loopPrefix}Failed: Max retries reached for stuck video.`;
  1506.                            statusEl.className = ""; statusEl.style.color = "#ef4444";
  1507.                            break;
  1508.                        }
  1509.                        statusEl.innerText = `${loopPrefix}Video Stuck/Failed. Auto-retrying... [${attempts}/${appSettings.retries}]`;
  1510.                        const delay = Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin;
  1511.                        await sleep(delay);
  1512.  
  1513.                        // Anti-caching injection: add a zero-width space to the prompt to force the server to evaluate a fresh generation.
  1514.                        if (payload.prompt) payload.prompt += "\u200B";
  1515.  
  1516.                        continue;
  1517.                    } else {
  1518.                        statusEl.innerText = `${loopPrefix}Error: ${err.message}`; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1519.                        break;
  1520.                    }
  1521.                }
  1522.            }
  1523.  
  1524.            if (!success && !isRequestCancelled) {
  1525.                if (!statusEl.innerText.includes("Failed:") && !statusEl.innerText.includes("Error:")) {
  1526.                    statusEl.innerText = `${loopPrefix}Failed after ${attempts} retries.`;
  1527.                }
  1528.                statusEl.className = ""; statusEl.style.color = "#ef4444";
  1529.                return false;
  1530.            }
  1531.  
  1532.            return success;
  1533.        }
  1534.  
  1535.        els.btn.addEventListener('click', async () => {
  1536.            initAudio();
  1537.            const basePrompt = els.prompt.value.trim();
  1538.            if (!basePrompt) return alert("Please enter a prompt.");
  1539.  
  1540.            const oldImages = Array.from(els.currentImages.children);
  1541.            if (oldImages.length > 0) {
  1542.                if (els.history.innerText.includes("No history")) els.history.innerHTML = '';
  1543.                oldImages.forEach(card => {
  1544.                    card.className = 'history-card';
  1545.                    const promptEl = card.querySelector('p');
  1546.                    promptEl.title = "Click to copy prompt";
  1547.                    promptEl.onclick = () => { setPromptVal(promptEl.innerText); };
  1548.                    els.history.prepend(card);
  1549.                });
  1550.            }
  1551.  
  1552.            const action = els.action.value;
  1553.            const activeRefs = referenceMedia.filter(m => m.active);
  1554.            let endpoint = '/v1/images/generations';
  1555.            if (action === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1556.            else if (action === 'gen_video') endpoint = '/v1/videos/generations';
  1557.            else if (action === 'edit_video') endpoint = '/v1/videos/edits';
  1558.            else if (action === 'extend_video') endpoint = '/v1/videos/extensions';
  1559.  
  1560.            const isImage = action === 'gen_image';
  1561.            const totalLoops = parseInt(els.loops.value) || 1;
  1562.  
  1563.            stealthIdentityReset();
  1564.  
  1565.            els.btn.disabled = true;
  1566.            els.cancelBtn.style.display = 'flex';
  1567.            els.previewBtn.style.display = 'none';
  1568.            isRequestCancelled = false;
  1569.  
  1570.            let allSuccess = true;
  1571.            for (let i = 1; i <= totalLoops; i++) {
  1572.                if (isRequestCancelled) break;
  1573.  
  1574.                const dynamicPrompt = parseDynamicPrompt(basePrompt);
  1575.                const payload = buildPayloadData(dynamicPrompt);
  1576.  
  1577.                els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Gen ${i}/${totalLoops}...</div>`;
  1578.  
  1579.                const ok = await executeGenerationSingle(endpoint, payload, isImage, els.status, i, totalLoops);
  1580.                if (!ok) {
  1581.                    allSuccess = false;
  1582.                    break;
  1583.                }
  1584.            }
  1585.  
  1586.            if (!isRequestCancelled) {
  1587.                els.cancelBtn.style.display = 'none';
  1588.                els.previewBtn.style.display = 'flex';
  1589.                els.btn.disabled = false;
  1590.                els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1591.  
  1592.                if (allSuccess) {
  1593.                    els.status.innerText = "All runs complete.";
  1594.                    els.status.className = "";
  1595.                    els.status.style.color = "#64748b";
  1596.                    notifyUser(false);
  1597.                } else {
  1598.                    notifyUser(true);
  1599.                }
  1600.            }
  1601.        });
  1602.  
  1603.        // ─── SESSION RESETTER ─────────────────────────────────────────────────────
  1604.        els.reset.addEventListener('click', () => {
  1605.            if (!confirm("Wipe cache? (This forces a page reload to clear front-end tokens). Your prompt and settings will be saved.")) return;
  1606.            localStorage.setItem('xai_api_prompt', els.prompt.value);
  1607.            const patterns =[/flushAfter/i, /imagine/i, /generation/i, /grok/i, /mixpanel|mp_/i, /distinct_id/i, /_rst/i, /limit/i, /credit/i];
  1608.            for (let i = localStorage.length - 1; i >= 0; i--) {
  1609.                const k = localStorage.key(i);
  1610.                if (k && !k.startsWith('xai_api_') && patterns.some(p => p.test(k))) localStorage.removeItem(k);
  1611.            }
  1612.            document.cookie.split(';').forEach(c => {
  1613.                const name = c.split('=')[0]?.trim();
  1614.                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 : ''}`; });
  1615.                });
  1616.            });
  1617.            const u = new URL(location.href);
  1618.            ['_r', '_rst'].forEach(k => u.searchParams.set(k, Date.now()));
  1619.            location.replace(u.toString());
  1620.        });
  1621.    }
  1622.  
  1623.    // ─── ASYNC PROCESSORS & RENDERERS ─────────────────────────────────────────
  1624.    async function processAndRenderImage(imgObj, originalPrompt, num, total, galleryEl) {
  1625.        if (!imgObj.b64_json) return;
  1626.        const mime = imgObj.mime_type || "image/png";
  1627.        const b64 = imgObj.b64_json;
  1628.        const pngDataUri = `data:${mime};base64,${b64}`;
  1629.  
  1630.        const finalPrompt = imgObj.revised_prompt || originalPrompt;
  1631.        let finalDataUri = pngDataUri;
  1632.        let filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.png`;
  1633.  
  1634.        if (!appSettings.saveAsPng) {
  1635.            finalDataUri = await convertToJpegWithExif(pngDataUri, finalPrompt);
  1636.            filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.jpg`;
  1637.        }
  1638.  
  1639.        const card = document.createElement('div');
  1640.        card.className = 'current-card';
  1641.        card.innerHTML = `
  1642.            <div class="img-wrapper">
  1643.                <img src="${finalDataUri}" class="zoomable" data-filename="${filename}" title="Click to view fullscreen">
  1644.                <a href="${finalDataUri}" download="${filename}" class="overlay-btn overlay-dl-btn" title="Download Full File">${DOWNLOAD_ICON}</a>
  1645.                <button class="overlay-btn overlay-edit-btn" title="Edit this Image">${EDIT_ICON}</button>
  1646.            </div>
  1647.            <p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${finalPrompt}</p>
  1648.        `;
  1649.  
  1650.        const editBtn = card.querySelector('.overlay-edit-btn');
  1651.        editBtn.addEventListener('click', (e) => {
  1652.            e.preventDefault();
  1653.            if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(finalDataUri, false, filename);
  1654.        });
  1655.  
  1656.        galleryEl.prepend(card);
  1657.    }
  1658.  
  1659.    function renderVideoToGallery(videoUrl, originalPrompt, galleryEl) {
  1660.        const filename = `Grok Video - ${makeTimestamp()}.mp4`;
  1661.        const auto = appSettings.videoAutoplay ? "autoplay" : "";
  1662.        const muted = appSettings.videoMuted ? "muted" : "";
  1663.  
  1664.        const card = document.createElement('div');
  1665.        card.className = 'current-card';
  1666.        card.innerHTML = `
  1667.            <div class="img-wrapper">
  1668.                <video src="${videoUrl}" controls ${auto} ${muted} loop style="width: 100%; display: block; max-height: 50vh; object-fit: contain; background: #000;"></video>
  1669.                <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>
  1670.                <button class="overlay-btn overlay-edit-btn" style="z-index: 50; right: 40px;" title="Edit this Video">${EDIT_ICON}</button>
  1671.            </div>
  1672.            <p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${originalPrompt}</p>
  1673.        `;
  1674.  
  1675.        const editBtn = card.querySelector('.overlay-edit-btn');
  1676.        editBtn.addEventListener('click', (e) => {
  1677.            e.preventDefault();
  1678.            if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename);
  1679.        });
  1680.  
  1681.        const dlBtn = card.querySelector('.overlay-dl-btn');
  1682.        dlBtn.addEventListener('click', (e) => {
  1683.            e.preventDefault();
  1684.            const url = dlBtn.getAttribute('data-url');
  1685.            const fname = dlBtn.getAttribute('data-filename');
  1686.            const originalIcon = dlBtn.innerHTML;
  1687.  
  1688.            dlBtn.innerHTML = '<div class="loading-spinner" style="border-top-color: #10b981;"></div>';
  1689.            dlBtn.style.pointerEvents = 'none';
  1690.  
  1691.            // Use Tampermonkey's GM_xmlhttpRequest to bypass CORS
  1692.            if (typeof GM_xmlhttpRequest !== "undefined") {
  1693.                GM_xmlhttpRequest({
  1694.                    method: 'GET',
  1695.                    url: url,
  1696.                    responseType: 'blob',
  1697.                    onload: function(response) {
  1698.                        if (response.status >= 200 && response.status < 300) {
  1699.                            const blobUrl = URL.createObjectURL(response.response);
  1700.                            const a = document.createElement('a');
  1701.                            a.style.display = 'none';
  1702.                            a.href = blobUrl;
  1703.                            a.download = fname;
  1704.                            document.body.appendChild(a);
  1705.                            a.click();
  1706.                            document.body.removeChild(a);
  1707.                            setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
  1708.                        } else {
  1709.                            window.open(url, '_blank'); // fallback
  1710.                        }
  1711.                        dlBtn.innerHTML = originalIcon;
  1712.                        dlBtn.style.pointerEvents = 'auto';
  1713.                    },
  1714.                    onerror: function() {
  1715.                        window.open(url, '_blank'); // fallback
  1716.                        dlBtn.innerHTML = originalIcon;
  1717.                        dlBtn.style.pointerEvents = 'auto';
  1718.                    }
  1719.                });
  1720.            } else {
  1721.                // Fallback for environments without GM_xmlhttpRequest
  1722.                window.open(url, '_blank');
  1723.                dlBtn.innerHTML = originalIcon;
  1724.                dlBtn.style.pointerEvents = 'auto';
  1725.            }
  1726.        });
  1727.  
  1728.        galleryEl.prepend(card);
  1729.    }
  1730.  
  1731.    if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initApp); }
  1732.    else { initApp(); }
  1733.  
  1734. })();
Add Comment
Please, Sign In to add comment