Guest User

Untitled

a guest
Mar 31st, 2026
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         xAI Pro Studio Frontend (v24 - Consecutive Loop Generations)
  3. // @namespace    http://tampermonkey.net/
  4. // @version      24.0
  5. // @description  Full-Screen UI, Exif Fix, Multi-Image Routing, Consecutive Loops, Debugger, Persistence, Compact Layout, CSS Overrides
  6. // @match        https://console.x.ai/playground/imagine*
  7. // @match        https://console.x.ai/team/*/imagine*
  8. // @grant        none
  9. // @run-at       document-start
  10. // ==/UserScript==
  11.  
  12. (function() {
  13.     'use strict';
  14.  
  15.     // ─── UTILITIES & DATA STORAGE ─────────────────────────────────────────────
  16.     const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  17.     function pad2(n) { return String(n).padStart(2, '0'); }
  18.     function makeTimestamp() {
  19.         const d = new Date();
  20.         return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}-${pad2(d.getMinutes())}-${pad2(d.getSeconds())}`;
  21.     }
  22.     const DOWNLOAD_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>`;
  23.  
  24.     // Load Settings
  25.     let appSettings = JSON.parse(localStorage.getItem('xai_api_settings') || '{}');
  26.     appSettings.retries = parseInt(appSettings.retries) || 20;
  27.     appSettings.delayMin = parseInt(appSettings.delayMin) || 2000;
  28.     appSettings.delayMax = parseInt(appSettings.delayMax) || 4000;
  29.     if (typeof appSettings.notifications === 'undefined') appSettings.notifications = true;
  30.     if (typeof appSettings.customCSS === 'undefined') appSettings.customCSS = "";
  31.  
  32.     let favoritePrompts = JSON.parse(localStorage.getItem('xai_api_favs') || '[]');
  33.  
  34.     // ─── BACKGROUND ALERT SYSTEM (AUDIO + TAB BLINK) ──────────────────────────
  35.     let sharedAudioCtx = null;
  36.     let titleBlinkInterval = null;
  37.     const originalTitle = document.title || "xAI Pro Studio";
  38.  
  39.     function initAudio() {
  40.         if (!sharedAudioCtx && appSettings.notifications) {
  41.             try { sharedAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); }
  42.             catch(e) { console.warn("AudioContext not supported"); }
  43.         }
  44.         if (sharedAudioCtx && sharedAudioCtx.state === 'suspended') sharedAudioCtx.resume();
  45.     }
  46.  
  47.     function notifyUser(isError = false) {
  48.         if (!appSettings.notifications) return;
  49.  
  50.         if (sharedAudioCtx) {
  51.             try {
  52.                 const osc = sharedAudioCtx.createOscillator();
  53.                 const gain = sharedAudioCtx.createGain();
  54.                 osc.connect(gain);
  55.                 gain.connect(sharedAudioCtx.destination);
  56.  
  57.                 if (isError) {
  58.                     osc.type = 'sawtooth';
  59.                     osc.frequency.setValueAtTime(300, sharedAudioCtx.currentTime);
  60.                     osc.frequency.exponentialRampToValueAtTime(100, sharedAudioCtx.currentTime + 0.3);
  61.                 } else {
  62.                     osc.type = 'sine';
  63.                     osc.frequency.setValueAtTime(500, sharedAudioCtx.currentTime);
  64.                     osc.frequency.exponentialRampToValueAtTime(1000, sharedAudioCtx.currentTime + 0.2);
  65.                 }
  66.  
  67.                 gain.gain.setValueAtTime(0.1, sharedAudioCtx.currentTime);
  68.                 gain.gain.exponentialRampToValueAtTime(0.01, sharedAudioCtx.currentTime + 0.5);
  69.  
  70.                 osc.start(sharedAudioCtx.currentTime);
  71.                 osc.stop(sharedAudioCtx.currentTime + 0.5);
  72.             } catch(e) {}
  73.         }
  74.  
  75.         if (!document.hasFocus()) {
  76.             if (titleBlinkInterval) clearInterval(titleBlinkInterval);
  77.             let toggle = true;
  78.             titleBlinkInterval = setInterval(() => {
  79.                 document.title = toggle ? (isError ? "❌ FAILED" : "✅ DONE") : originalTitle;
  80.                 toggle = !toggle;
  81.             }, 1000);
  82.  
  83.             const clearBlink = () => {
  84.                 clearInterval(titleBlinkInterval);
  85.                 document.title = originalTitle;
  86.                 window.removeEventListener('focus', clearBlink);
  87.             };
  88.             window.addEventListener('focus', clearBlink);
  89.         }
  90.     }
  91.  
  92.     // ─── STEALTH IDENTITY RESETTER ────────────────────────────────────────────
  93.     function stealthIdentityReset() {
  94.         const trackingCookies =['x-anonuserid', 'mixpanel', 'mp_', 'distinct_id'];
  95.         document.cookie.split(';').forEach(c => {
  96.             const name = c.split('=')[0].trim();
  97.             if (trackingCookies.some(tc => name.includes(tc))) {['.x.ai', 'console.x.ai', ''].forEach(d => {['/', '/playground/imagine', ''].forEach(p => {
  98.                         document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${p}${d ? ';domain=' + d : ''}`;
  99.                     });
  100.                 });
  101.             }
  102.         });
  103.  
  104.         for (let i = localStorage.length - 1; i >= 0; i--) {
  105.             const k = localStorage.key(i);
  106.             if (k && !k.startsWith('xai_api_') && trackingCookies.some(tc => k.includes(tc))) {
  107.                 localStorage.removeItem(k);
  108.             }
  109.         }
  110.     }
  111.  
  112.     // ─── EXIF LIBRARY LOADER & WINDOWS METADATA ENCODER ───────────────────────
  113.     let piexifLoaded = false;
  114.     function loadPiexif() {
  115.         if (piexifLoaded) return Promise.resolve(window.piexif);
  116.         return new Promise(resolve => {
  117.             const script = document.createElement('script');
  118.             script.src = 'https://cdn.jsdelivr.net/npm/piexifjs';
  119.             script.onload = () => { piexifLoaded = true; resolve(window.piexif); };
  120.             document.head.appendChild(script);
  121.         });
  122.     }
  123.  
  124.     function toUTF16LE(str) {
  125.         const arr =[];
  126.         for (let i = 0; i < str.length; i++) {
  127.             const code = str.charCodeAt(i);
  128.             arr.push(code & 0xFF); arr.push((code >> 8) & 0xFF);
  129.         }
  130.         arr.push(0, 0); return arr;
  131.     }
  132.  
  133.     function convertToJpegWithExif(base64PngUri, prompt) {
  134.         return new Promise((resolve, reject) => {
  135.             const img = new Image();
  136.             img.onload = async () => {
  137.                 const canvas = document.createElement('canvas');
  138.                 canvas.width = img.width; canvas.height = img.height;
  139.                 const ctx = canvas.getContext('2d');
  140.                 ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height);
  141.                 ctx.drawImage(img, 0, 0);
  142.  
  143.                 let jpegUri = canvas.toDataURL('image/jpeg', 0.95);
  144.                 if (prompt) {
  145.                     try {
  146.                         const piexif = await loadPiexif();
  147.                         const exifObj = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "Interop": {}};
  148.                         const safePrompt = unescape(encodeURIComponent(prompt));
  149.                         exifObj['0th'][piexif.ImageIFD.ImageDescription] = safePrompt;
  150.  
  151.                         const utf16Prompt = toUTF16LE(prompt);
  152.                         exifObj['0th'][40091] = utf16Prompt;
  153.                         exifObj['0th'][40092] = utf16Prompt;
  154.                         exifObj['0th'][40093] = utf16Prompt;
  155.  
  156.                         jpegUri = piexif.insert(piexif.dump(exifObj), jpegUri);
  157.                     } catch (e) {}
  158.                 }
  159.                 resolve(jpegUri);
  160.             };
  161.             img.onerror = reject; img.src = base64PngUri;
  162.         });
  163.     }
  164.  
  165.     async function extractPromptFromImage(file) {
  166.         if (!file.type.includes('image')) return null;
  167.         try {
  168.             const piexif = await loadPiexif();
  169.             return new Promise((resolve) => {
  170.                 const reader = new FileReader();
  171.                 reader.onload = (e) => {
  172.                     try {
  173.                         const exifData = piexif.load(e.target.result);
  174.                         let prompt = exifData['0th'] && exifData['0th'][piexif.ImageIFD.ImageDescription];
  175.                         if (Array.isArray(prompt)) prompt = String.fromCharCode.apply(null, prompt).replace(/\0/g, '');
  176.                         if (prompt) { try { prompt = decodeURIComponent(escape(prompt)); } catch(e) {} }
  177.  
  178.                         if (!prompt && exifData['0th'] && exifData['0th'][40091]) {
  179.                             const xpTitleArr = exifData['0th'][40091];
  180.                             let str = '';
  181.                             for (let i = 0; i < xpTitleArr.length; i += 2) {
  182.                                 const charCode = xpTitleArr[i] | (xpTitleArr[i+1] << 8);
  183.                                 if (charCode === 0) break;
  184.                                 str += String.fromCharCode(charCode);
  185.                             }
  186.                             prompt = str;
  187.                         }
  188.                         resolve(prompt ? prompt.trim() : null);
  189.                     } catch (err) { resolve(null); }
  190.                 };
  191.                 reader.readAsDataURL(file);
  192.             });
  193.         } catch (e) { return null; }
  194.     }
  195.  
  196.     // ─── ASPECT RATIO DATA ────────────────────────────────────────────────────
  197.     const arData =[
  198.         { label: 'Auto', w: 1, h: 1, isAuto: true },
  199.         { label: '1:1', w: 1, h: 1 }, { label: '3:4', w: 3, h: 4 }, { label: '4:3', w: 4, h: 3 },
  200.         { label: '9:16', w: 9, h: 16 }, { label: '16:9', w: 16, h: 9 }, { label: '2:3', w: 2, h: 3 },
  201.         { 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 },
  202.         { 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 }
  203.     ];
  204.  
  205.     function createArIcon(w, h, isAuto) {
  206.         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>`;
  207.         const scale = 12 / Math.max(w, h);
  208.         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>`;
  209.     }
  210.  
  211.     // ─── UI INJECTION (COMPACT CSS) ───────────────────────────────────────────
  212.     const UI_CSS = `
  213.         ::-webkit-scrollbar { width: 6px; }
  214.         ::-webkit-scrollbar-track { background: #0f172a; }
  215.         ::-webkit-scrollbar-thumb { background: #475569; border-radius: 6px; }
  216.  
  217.         @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  218.         @keyframes pulse { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
  219.  
  220.         .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; }
  221.         .btn-content { display: flex; align-items: center; justify-content: center; gap: 6px; }
  222.         .status-pulsing { animation: pulse 2s ease-in-out infinite; color: #3b82f6 !important; font-weight: 600; }
  223.  
  224.         #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; }
  225.         #xai-pro-app * { box-sizing: border-box; }
  226.  
  227.         .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; }
  228.         .panel-title { font-size: 11px; font-weight: 700; color: #94a3b8; letter-spacing: 0.5px; padding: 10px; border-bottom: 1px solid #334155; text-transform: uppercase; }
  229.  
  230.         .col-left { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; }
  231.         .col-center { flex: 1; display: flex; flex-direction: column; gap: 10px; min-width: 0; min-height: 0; }
  232.         .col-right { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; transition: 0.2s; }
  233.         .col-right.drag-over { background: #064e3b; border-color: #10b981; box-shadow: 0 0 0 4px rgba(16,185,129,0.15); border-radius: 10px; }
  234.  
  235.         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; }
  236.         textarea, select, input[type="text"], input[type="number"] { width: 100%; }
  237.         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); }
  238.         .prompt-drag-over { border-color: #10b981 !important; background: #064e3b !important; box-shadow: 0 0 0 2px rgba(16,185,129,0.15) !important; }
  239.         label { font-size: 11px; font-weight: 600; color: #94a3b8; margin-bottom: 4px; display: block; }
  240.  
  241.         .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; }
  242.         .btn-primary:hover:not(:disabled) { background: linear-gradient(180deg, #4f46e5 0%, #4338ca 100%); transform: translateY(-1px); }
  243.         .btn-primary:disabled { opacity: 0.8; cursor: not-allowed; }
  244.  
  245.         .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; }
  246.         .btn-secondary:hover:not(:disabled) { background: #334155; border-color: #64748b; }
  247.  
  248.         .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; }
  249.         #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; }
  250.         .ar-option { display: flex; align-items: center; gap: 8px; padding: 6px 8px; cursor: pointer; font-size: 12px; color: #cbd5e1; }
  251.         .ar-option:hover { background: #334155; color: #f8fafc; }
  252.  
  253.         .img-wrapper { position: relative; display: block; }
  254.         .zoomable { cursor: zoom-in; transition: transform 0.2s; width: 100%; display: block; }
  255.         .overlay-dl-btn { position: absolute; top: 6px; right: 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; }
  256.         .overlay-dl-btn:hover { background: rgba(15, 23, 42, 0.9); opacity: 1; transform: scale(1.05); }
  257.  
  258.         .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; }
  259.         .ref-item.inactive { opacity: 0.6; filter: grayscale(0.8); }
  260.         .ref-item:active { cursor: grabbing; }
  261.         .ref-item.dragging { opacity: 0.4; }
  262.         .ref-handle { font-size: 14px; color: #475569; cursor: grab; padding: 0 4px; }
  263.         .ref-thumb { width: 90px; height: 90px; border-radius: 4px; object-fit: cover; border: 1px solid #334155; background: #0f172a; transition: 0.2s; }
  264.         .ref-info { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 6px; }
  265.         .ref-toggle-label { font-size: 11px; color: #cbd5e1; display: flex; align-items: center; gap: 4px; cursor: pointer; user-select: none; }
  266.         .ref-toggle-label input { width: 12px; height: 12px; cursor: pointer; accent-color: #10b981; margin: 0; padding: 0; }
  267.         .ref-del { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; border-radius: 4px; padding: 6px; cursor: pointer; font-size: 11px; transition: 0.2s; font-weight: bold; width: 100%; text-align: center; }
  268.         .ref-del:hover { background: #7f1d1d; color: #fee2e2; }
  269.         .drag-over-top { border-top: 2px solid #22c55e !important; }
  270.         .drag-over-bottom { border-bottom: 2px solid #22c55e !important; }
  271.  
  272.         .history-card { background: #0f172a; border: 1px solid #334155; border-radius: 6px; overflow: hidden; margin-bottom: 10px; }
  273.         .history-card .overlay-dl-btn { width: 24px; height: 24px; top: 4px; right: 4px; border-radius: 4px; }
  274.         .history-card p { padding: 8px; margin: 0; font-size: 11px; color: #94a3b8; cursor: pointer; transition: 0.2s; }
  275.         .history-card p:hover { background: #1e293b; color: #e2e8f0; }
  276.  
  277.         .current-card { border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.3); border: 1px solid #334155; background: #1e293b; }
  278.         .current-card img, .current-card video { max-height: 50vh; object-fit: contain; background: #0f172a; }
  279.  
  280.         /* Modals Generic Classes */
  281.         .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); }
  282.         .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; }
  283.         .fav-item { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 8px; border-radius: 6px; border: 1px solid #334155; }
  284.         .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; }
  285.         .fav-text:hover { color: #10b981; }
  286.  
  287.         #settings-btn { position: fixed; top: 10px; right: 15px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
  288.         #settings-btn:hover { transform: rotate(45deg); opacity: 1; }
  289.  
  290.         #xai-lightbox { cursor: zoom-out; }
  291.         #xai-lightbox-wrapper { position: relative; display: inline-block; max-width: 95vw; max-height: 95vh; }
  292.         #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); }
  293.     `;
  294.  
  295.     const UI_HTML = `
  296.         <div id="xai-pro-app">
  297.             <div id="settings-btn" title="Studio Settings">⚙️</div>
  298.  
  299.             <!-- LEFT COLUMN -->
  300.             <div class="col-left">
  301.                 <div class="panel" style="flex-shrink: 0;">
  302.                     <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;">
  303.                         <div style="flex: 1;">
  304.                             <label>Master Action</label>
  305.                             <select id="master-action" style="font-weight: bold; color: #f8fafc; border-color: #475569; box-shadow: 0 2px 4px rgba(0,0,0,0.3);">
  306.                                 <option value="gen_image">🖼️ Generate Image</option>
  307.                                 <option value="gen_video">🎥 Generate Video</option>
  308.                                 <option value="edit_video">✂️ Edit Video</option>
  309.                                 <option value="extend_video">➡️ Extend Video</option>
  310.                             </select>
  311.                         </div>
  312.                     </div>
  313.  
  314.                     <div style="padding: 10px; display: flex; flex-direction: column; gap: 10px;">
  315.                         <div id="setting-ar">
  316.                             <label>Aspect Ratio</label>
  317.                             <div class="ar-select-box" id="ar-select-box">
  318.                                 <div id="ar-selected-icon"></div>
  319.                                 <span id="ar-selected-text">Auto</span>
  320.                             </div>
  321.                         </div>
  322.  
  323.                         <div style="display: flex; gap: 8px;">
  324.                             <div id="setting-res-img" style="flex: 1;">
  325.                                 <label>Resolution</label>
  326.                                 <select id="xai-api-res-img">
  327.                                     <option value="2k" selected>2K (Pro)</option>
  328.                                     <option value="1k">1K</option>
  329.                                 </select>
  330.                             </div>
  331.                             <div id="setting-res-vid" style="flex: 1; display: none;">
  332.                                 <label>Resolution</label>
  333.                                 <select id="xai-api-res-vid">
  334.                                     <option value="720p" selected>720p (HD)</option>
  335.                                     <option value="480p">480p (SD)</option>
  336.                                 </select>
  337.                             </div>
  338.  
  339.                             <div id="setting-batch" style="flex: 1;">
  340.                                 <label>Batch Size</label>
  341.                                 <select id="xai-api-n">
  342.                                     <option value="1" selected>1 Image</option>
  343.                                     <option value="2">2 Images</option>
  344.                                     <option value="3">3 Images</option>
  345.                                     <option value="4">4 Images</option>
  346.                                     <option value="5">5 Images</option>
  347.                                     <option value="8">8 Images</option>
  348.                                     <option value="10">10 Images</option>
  349.                                 </select>
  350.                             </div>
  351.                             <div id="setting-duration" style="flex: 1; display: none;">
  352.                                 <label>Duration</label>
  353.                                 <select id="xai-api-duration">
  354.                                     <option value="5" selected>5 Seconds</option>
  355.                                     <option value="8">8 Seconds</option>
  356.                                     <option value="10">10 Seconds</option>
  357.                                     <option value="12">12 Seconds</option>
  358.                                     <option value="15">15 Seconds</option>
  359.                                     <option value="2">2s Extension</option>
  360.                                     <option value="4">4s Extension</option>
  361.                                     <option value="6">6s Extension</option>
  362.                                 </select>
  363.                             </div>
  364.  
  365.                             <!-- NEW: Consecutive Runs -->
  366.                             <div id="setting-loops" style="flex: 1;">
  367.                                 <label title="How many consecutive API calls to perform in a row">Loops</label>
  368.                                 <input type="number" id="xai-api-loops" value="1" min="1" max="100">
  369.                             </div>
  370.                         </div>
  371.                     </div>
  372.                 </div>
  373.  
  374.                 <div class="panel" style="flex: 1; min-height: 0;">
  375.                     <div class="panel-title" style="display:flex; justify-content: space-between; align-items: center;">
  376.                         <span>Previous Results</span>
  377.                         <span id="xai-reset-btn" style="cursor: pointer; color: #ef4444; text-transform: none; text-decoration: underline;">Wipe Cache</span>
  378.                     </div>
  379.                     <div id="xai-history" style="flex: 1; overflow-y: auto; padding: 10px;">
  380.                         <div style="color: #94a3b8; font-size: 11px; text-align: center; margin-top: 20px;">No history yet.</div>
  381.                     </div>
  382.                 </div>
  383.             </div>
  384.  
  385.             <!-- CENTER COLUMN -->
  386.             <div class="col-center">
  387.                 <div class="panel" style="flex: 1; background: transparent; border: none; box-shadow: none; min-height: 0;">
  388.                     <div class="panel-title" style="background: #1e293b; border-radius: 8px; border: 1px solid #334155; margin-bottom: 10px; flex-shrink: 0;">Current Generation</div>
  389.                     <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>
  390.                 </div>
  391.  
  392.                 <div class="panel" style="flex-shrink: 0; padding: 12px;">
  393.                     <label style="font-size: 13px; color: #e2e8f0; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
  394.                         <span style="display: flex; align-items: center; gap: 8px;">
  395.                             <span>Prompt</span>
  396.                             <button id="fav-prompts-btn" class="btn-secondary" style="padding: 2px 8px; font-size: 10px; height: 22px;">⭐ Favorites</button>
  397.                         </span>
  398.                         <span style="font-size: 10px; font-weight: 400; color: #94a3b8;">(Drop image here for EXIF)</span>
  399.                     </label>
  400.                     <textarea id="xai-api-prompt" placeholder="Describe what you want to see..." style="height: 100px; min-height: 70px; margin-bottom: 10px; font-size: 13px;"></textarea>
  401.  
  402.                     <div style="display: flex; align-items: center; justify-content: space-between;">
  403.                         <div id="xai-api-status" style="font-size: 12px; color: #64748b; font-weight: 500;">Ready</div>
  404.                         <div style="display: flex; gap: 8px;">
  405.                             <button id="xai-preview-btn" class="btn-secondary">🔍 Payload</button>
  406.                             <button id="xai-cancel-btn" class="btn-secondary" style="display: none; color: #ef4444; border-color: #ef4444;">🛑 Cancel</button>
  407.                             <button id="xai-api-generate" class="btn-primary" style="width: 120px;"><div class="btn-content">Generate</div></button>
  408.                         </div>
  409.                     </div>
  410.                 </div>
  411.             </div>
  412.  
  413.             <!-- RIGHT COLUMN -->
  414.             <div class="col-right" id="col-right-dropzone">
  415.                 <div class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
  416.                     <div class="panel-title" id="ref-panel-title">Reference Media</div>
  417.                     <div style="padding: 10px; flex: 1; display: flex; flex-direction: column; overflow: hidden;">
  418.                         <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);">
  419.                             <div style="font-size: 20px; margin-bottom: 4px;">📥</div>
  420.                             <div style="font-size: 12px; font-weight: 600;">Drag & Drop / Ctrl+V</div>
  421.                         </div>
  422.                         <input type="file" id="xai-api-file" accept="image/*, video/mp4, video/webm" multiple style="display: none;">
  423.                         <div style="font-size: 10px; color: #94a3b8; margin-bottom: 4px; text-transform: uppercase; font-weight: bold; flex-shrink: 0;">Upload Order (Top = First)</div>
  424.                         <div id="xai-ref-list" style="flex: 1; overflow-y: auto; padding-right: 4px;"></div>
  425.                     </div>
  426.                 </div>
  427.             </div>
  428.  
  429.             <!-- FIXED FLOATING DROPDOWN -->
  430.             <div id="ar-options-container"></div>
  431.  
  432.             <!-- MODALS -->
  433.             <div id="xai-lightbox" class="modal-overlay">
  434.                 <div id="xai-lightbox-wrapper">
  435.                     <img id="xai-lightbox-img" src="">
  436.                     <a id="xai-lightbox-dl" href="#" download="" target="_blank" class="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>
  437.                 </div>
  438.             </div>
  439.  
  440.             <!-- SETTINGS MODAL -->
  441.             <div id="xai-settings-modal" class="modal-overlay">
  442.                 <div class="modal-box" style="width: 450px;">
  443.                     <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⚙️ Studio Settings</h3>
  444.                     <div style="display:flex; gap:10px;">
  445.                         <div style="flex:1;">
  446.                             <label>Max Retries</label>
  447.                             <input type="number" id="set-retries" min="1" max="100">
  448.                         </div>
  449.                         <div style="flex:1;">
  450.                             <label>Delay Min (ms)</label>
  451.                             <input type="number" id="set-delay-min" min="500" step="500">
  452.                         </div>
  453.                         <div style="flex:1;">
  454.                             <label>Delay Max (ms)</label>
  455.                             <input type="number" id="set-delay-max" min="1000" step="500">
  456.                         </div>
  457.                     </div>
  458.                     <div style="display:flex; align-items:center; gap: 8px;">
  459.                         <input type="checkbox" id="set-notifications" style="width: 16px; height: 16px;">
  460.                         <label for="set-notifications" style="margin: 0; cursor: pointer;">Enable Notifications (Sound & Tab Blink)</label>
  461.                     </div>
  462.                     <div>
  463.                         <label>Custom CSS Overrides</label>
  464.                         <textarea id="set-custom-css" style="font-family: monospace; height: 120px; font-size: 11px;" placeholder="/* e.g., #xai-pro-app { background: red; } */"></textarea>
  465.                     </div>
  466.                     <div style="display: flex; gap: 8px; margin-top: 5px;">
  467.                         <button id="save-settings-btn" class="btn-primary" style="flex:1;">Save Settings</button>
  468.                         <button id="close-settings-btn" class="btn-secondary" style="flex:1;">Cancel</button>
  469.                     </div>
  470.                 </div>
  471.             </div>
  472.  
  473.             <!-- FAVORITES MODAL -->
  474.             <div id="xai-fav-modal" class="modal-overlay">
  475.                 <div class="modal-box" style="width: 550px;">
  476.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  477.                         <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⭐ Favorite Prompts</h3>
  478.                         <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>
  479.                     </div>
  480.                     <button id="add-current-fav-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);">➕ Save Current Prompt to Favorites</button>
  481.                     <div id="fav-list" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px;"></div>
  482.                 </div>
  483.             </div>
  484.  
  485.             <!-- CUSTOM PAYLOAD DEBUGGER MODAL -->
  486.             <div id="xai-payload-modal" class="modal-overlay">
  487.                 <div class="modal-box" style="width: 550px;">
  488.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  489.                         <h3 style="margin:0; font-size: 15px; color: #f8fafc;">API Payload Debugger</h3>
  490.                         <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>
  491.                     </div>
  492.                     <div><label>Endpoint URL:</label><input type="text" id="payload-endpoint" style="font-family: monospace;" value="/v1/images/generations"></div>
  493.                     <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>
  494.                     <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>
  495.                     <div id="custom-payload-status" style="font-size: 11px; color: #64748b; text-align: center;">Ready</div>
  496.                 </div>
  497.             </div>
  498.         </div>
  499.     `;
  500.  
  501.     // ─── INITIALIZATION ───────────────────────────────────────────────────────
  502.     const initApp = () => {
  503.         if (!document.body) return setTimeout(initApp, 50);
  504.  
  505.         const hideOriginals = () => {
  506.             Array.from(document.body.children).forEach(child => {
  507.                 if (child.id !== 'xai-pro-app' && !['SCRIPT', 'STYLE', 'LINK'].includes(child.tagName)) {
  508.                     child.style.display = 'none';
  509.                 }
  510.             });
  511.         };
  512.         hideOriginals();
  513.         new MutationObserver(hideOriginals).observe(document.body, { childList: true });
  514.  
  515.         if (!document.getElementById('xai-pro-app')) {
  516.             const style = document.createElement('style');
  517.             style.innerHTML = UI_CSS;
  518.             document.head.appendChild(style);
  519.  
  520.             // Inject Custom CSS block
  521.             const customStyle = document.createElement('style');
  522.             customStyle.id = 'xai-custom-css-block';
  523.             customStyle.innerHTML = appSettings.customCSS;
  524.             document.head.appendChild(customStyle);
  525.  
  526.             document.body.insertAdjacentHTML('beforeend', UI_HTML);
  527.             bindLogic();
  528.         }
  529.     };
  530.  
  531.     let referenceMedia =[];
  532.     let currentAr = localStorage.getItem('xai_api_ar') || 'Auto';
  533.     let fullPayloadMemory = {};
  534.     let currentAbortController = null;
  535.     let isRequestCancelled = false;
  536.  
  537.     // Helper to safely persist references to memory
  538.     function saveRefs() {
  539.         try {
  540.             localStorage.setItem('xai_api_refs', JSON.stringify(referenceMedia));
  541.         } catch (e) {
  542.             console.warn("[xAI Studio] Could not save references to localStorage (quota exceeded). Images will not persist after refresh.");
  543.         }
  544.     }
  545.  
  546.     function bindLogic() {
  547.         const els = {
  548.             app: document.getElementById('xai-pro-app'),
  549.             prompt: document.getElementById('xai-api-prompt'),
  550.             action: document.getElementById('master-action'),
  551.             resImg: document.getElementById('xai-api-res-img'),
  552.             resVid: document.getElementById('xai-api-res-vid'),
  553.             n: document.getElementById('xai-api-n'),
  554.             duration: document.getElementById('xai-api-duration'),
  555.             loops: document.getElementById('xai-api-loops'),
  556.  
  557.             settingAr: document.getElementById('setting-ar'),
  558.             settingResImg: document.getElementById('setting-res-img'),
  559.             settingResVid: document.getElementById('setting-res-vid'),
  560.             settingBatch: document.getElementById('setting-batch'),
  561.             settingDuration: document.getElementById('setting-duration'),
  562.             settingLoops: document.getElementById('setting-loops'),
  563.  
  564.             fileInput: document.getElementById('xai-api-file'),
  565.             dropzone: document.getElementById('col-right-dropzone'),
  566.             uploadPlaceholder: document.getElementById('xai-upload-placeholder'),
  567.             refList: document.getElementById('xai-ref-list'),
  568.             refTitle: document.getElementById('ref-panel-title'),
  569.  
  570.             btn: document.getElementById('xai-api-generate'),
  571.             previewBtn: document.getElementById('xai-preview-btn'),
  572.             cancelBtn: document.getElementById('xai-cancel-btn'),
  573.             status: document.getElementById('xai-api-status'),
  574.             history: document.getElementById('xai-history'),
  575.             currentImages: document.getElementById('xai-current-images'),
  576.             reset: document.getElementById('xai-reset-btn'),
  577.  
  578.             arSelectBox: document.getElementById('ar-select-box'),
  579.             arOptionsCont: document.getElementById('ar-options-container'),
  580.             arSelectedIcon: document.getElementById('ar-selected-icon'),
  581.             arSelectedText: document.getElementById('ar-selected-text'),
  582.  
  583.             lightbox: document.getElementById('xai-lightbox'),
  584.             lightboxImg: document.getElementById('xai-lightbox-img'),
  585.             lightboxDl: document.getElementById('xai-lightbox-dl'),
  586.  
  587.             payloadModal: document.getElementById('xai-payload-modal'),
  588.             payloadEndpoint: document.getElementById('payload-endpoint'),
  589.             payloadCode: document.getElementById('payload-code'),
  590.             closePayloadBtn: document.getElementById('close-payload-btn'),
  591.             sendCustomBtn: document.getElementById('send-custom-payload-btn'),
  592.             customStatus: document.getElementById('custom-payload-status'),
  593.  
  594.             settingsBtn: document.getElementById('settings-btn'),
  595.             settingsModal: document.getElementById('xai-settings-modal'),
  596.             closeSettingsBtn: document.getElementById('close-settings-btn'),
  597.             saveSettingsBtn: document.getElementById('save-settings-btn'),
  598.  
  599.             favBtn: document.getElementById('fav-prompts-btn'),
  600.             favModal: document.getElementById('xai-fav-modal'),
  601.             closeFavBtn: document.getElementById('close-fav-btn'),
  602.             addFavBtn: document.getElementById('add-current-fav-btn'),
  603.             favList: document.getElementById('fav-list')
  604.         };
  605.  
  606.         // ─── LOAD PERSISTED SETTINGS & REFERENCES ──────────────────────────────────
  607.         if (localStorage.getItem('xai_api_prompt')) els.prompt.value = localStorage.getItem('xai_api_prompt');
  608.         els.prompt.addEventListener('input', () => localStorage.setItem('xai_api_prompt', els.prompt.value));
  609.  
  610.         try {
  611.             const storedGen = JSON.parse(localStorage.getItem('xai_api_gen_settings') || '{}');
  612.             if (storedGen.action) els.action.value = storedGen.action;
  613.             if (storedGen.resImg) els.resImg.value = storedGen.resImg;
  614.             if (storedGen.resVid) els.resVid.value = storedGen.resVid;
  615.             if (storedGen.n) els.n.value = storedGen.n;
  616.             if (storedGen.duration) els.duration.value = storedGen.duration;
  617.             if (storedGen.loops) els.loops.value = storedGen.loops;
  618.         } catch(e) {}
  619.  
  620.         const updateGenSettingsMemory = () => {
  621.             localStorage.setItem('xai_api_gen_settings', JSON.stringify({
  622.                 action: els.action.value, resImg: els.resImg.value, resVid: els.resVid.value,
  623.                 n: els.n.value, duration: els.duration.value, loops: els.loops.value
  624.             }));
  625.         };
  626.         [els.action, els.resImg, els.resVid, els.n, els.duration, els.loops].forEach(el => el.addEventListener('change', updateGenSettingsMemory));
  627.  
  628.         try {
  629.             const storedRefs = JSON.parse(localStorage.getItem('xai_api_refs'));
  630.             if (Array.isArray(storedRefs)) referenceMedia = storedRefs;
  631.         } catch(e) {}
  632.  
  633.         // ─── SETTINGS BINDINGS ───────────────────────────────────────────────────
  634.         els.settingsBtn.addEventListener('click', () => {
  635.             document.getElementById('set-retries').value = appSettings.retries;
  636.             document.getElementById('set-delay-min').value = appSettings.delayMin;
  637.             document.getElementById('set-delay-max').value = appSettings.delayMax;
  638.             document.getElementById('set-notifications').checked = appSettings.notifications;
  639.             document.getElementById('set-custom-css').value = appSettings.customCSS || '';
  640.             els.settingsModal.style.display = 'flex';
  641.         });
  642.  
  643.         els.saveSettingsBtn.addEventListener('click', () => {
  644.             appSettings.retries = parseInt(document.getElementById('set-retries').value) || 20;
  645.             appSettings.delayMin = parseInt(document.getElementById('set-delay-min').value) || 2000;
  646.             appSettings.delayMax = Math.max(appSettings.delayMin, parseInt(document.getElementById('set-delay-max').value) || 4000);
  647.             appSettings.notifications = document.getElementById('set-notifications').checked;
  648.             appSettings.customCSS = document.getElementById('set-custom-css').value;
  649.  
  650.             localStorage.setItem('xai_api_settings', JSON.stringify(appSettings));
  651.             document.getElementById('xai-custom-css-block').innerHTML = appSettings.customCSS; // Live update CSS
  652.  
  653.             els.settingsModal.style.display = 'none';
  654.         });
  655.  
  656.         els.closeSettingsBtn.addEventListener('click', () => els.settingsModal.style.display = 'none');
  657.  
  658.         // ─── FAVORITES BINDINGS ──────────────────────────────────────────────────
  659.         function renderFavList() {
  660.             els.favList.innerHTML = '';
  661.             if (favoritePrompts.length === 0) {
  662.                 els.favList.innerHTML = '<div style="color: #64748b; font-size: 12px; text-align: center; margin-top: 15px;">No favorite prompts yet.</div>';
  663.                 return;
  664.             }
  665.             favoritePrompts.forEach((promptText, idx) => {
  666.                 const div = document.createElement('div');
  667.                 div.className = 'fav-item';
  668.                 div.innerHTML = `
  669.                     <div class="fav-text" title="${promptText.replace(/"/g, '&quot;')}">${promptText}</div>
  670.                    <button class="btn-secondary" style="padding: 2px 6px; font-size: 10px; border-color: #ef4444; color: #ef4444;">Del</button>
  671.                `;
  672.                div.querySelector('.fav-text').addEventListener('click', () => {
  673.                    els.prompt.value = promptText;
  674.                    localStorage.setItem('xai_api_prompt', promptText);
  675.                    els.favModal.style.display = 'none';
  676.                });
  677.                div.querySelector('button').addEventListener('click', () => {
  678.                    favoritePrompts.splice(idx, 1);
  679.                    localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts));
  680.                    renderFavList();
  681.                });
  682.                els.favList.appendChild(div);
  683.            });
  684.        }
  685.  
  686.        els.favBtn.addEventListener('click', () => {
  687.            renderFavList();
  688.            els.favModal.style.display = 'flex';
  689.        });
  690.        els.closeFavBtn.addEventListener('click', () => els.favModal.style.display = 'none');
  691.        els.addFavBtn.addEventListener('click', () => {
  692.            const p = els.prompt.value.trim();
  693.            if (!p) return alert("Prompt is empty!");
  694.            if (favoritePrompts.includes(p)) return alert("Already in favorites!");
  695.            favoritePrompts.unshift(p);
  696.            localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts));
  697.            renderFavList();
  698.        });
  699.  
  700.        // ─── PROMPT BOX EXIF DRAG & DROP ──────────────────────────────────────────
  701.        els.prompt.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); els.prompt.classList.add('prompt-drag-over'); });
  702.        els.prompt.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); els.prompt.classList.remove('prompt-drag-over'); });
  703.        els.prompt.addEventListener('drop', async (e) => {
  704.            e.preventDefault(); e.stopPropagation();
  705.            els.prompt.classList.remove('prompt-drag-over');
  706.            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  707.                const file = e.dataTransfer.files[0];
  708.                const oldVal = els.prompt.value;
  709.                els.prompt.value = "Extracting prompt from EXIF...";
  710.                const extractedPrompt = await extractPromptFromImage(file);
  711.                if (extractedPrompt) {
  712.                    els.prompt.value = extractedPrompt;
  713.                    localStorage.setItem('xai_api_prompt', extractedPrompt);
  714.                } else {
  715.                    els.prompt.value = oldVal;
  716.                    alert("No prompt found in this image's EXIF data (or not a valid JPEG).");
  717.                }
  718.            }
  719.        });
  720.  
  721.        // ─── MASTER ACTION UI LOGIC ───────────────────────────────────────────────
  722.        function getMaxMedia() {
  723.            const val = els.action.value;
  724.            if (val === 'gen_image') return 5;
  725.            if (val === 'gen_video') return 7;
  726.            return 1;
  727.        }
  728.  
  729.        function updateActionUI() {
  730.            const val = els.action.value;
  731.  
  732.            if (val === 'gen_image') {
  733.                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';
  734.            } else if (val === 'gen_video') {
  735.                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';
  736.                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>`;
  737.                if (localStorage.getItem('xai_api_gen_settings') && JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration <= 15) {
  738.                    els.duration.value = JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration;
  739.                } else els.duration.value = "5";
  740.            } else if (val === 'edit_video') {
  741.                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';
  742.            } else if (val === 'extend_video') {
  743.                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';
  744.                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>`;
  745.                if (localStorage.getItem('xai_api_gen_settings') && JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration <= 10) {
  746.                    els.duration.value = JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration;
  747.                } else els.duration.value = "6";
  748.            }
  749.  
  750.            const max = getMaxMedia();
  751.            els.refTitle.innerText = `Reference Media (Max Active: ${max})`;
  752.  
  753.            // Soft deactivate incompatible items
  754.            let activeCount = 0;
  755.            referenceMedia.forEach(m => {
  756.                let valid = true;
  757.                if ((val === 'gen_image' || val === 'gen_video') && m.isVideo) valid = false;
  758.                if ((val === 'edit_video' || val === 'extend_video') && !m.isVideo) valid = false;
  759.  
  760.                if (!valid) m.active = false;
  761.                else if (m.active) {
  762.                    activeCount++;
  763.                    if (activeCount > max) m.active = false;
  764.                }
  765.            });
  766.            renderRefList();
  767.        }
  768.  
  769.        els.action.addEventListener('change', updateActionUI);
  770.        updateActionUI(); // Call once on load
  771.  
  772.        // ─── BUILD PAYLOAD LOGIC ──────────────────────────────────────────────────
  773.        function buildPayloadData() {
  774.            const action = els.action.value;
  775.            const payload = {
  776.                model: action === 'gen_image' ? "grok-imagine-image" : "grok-imagine-video",
  777.                prompt: els.prompt.value.trim()
  778.            };
  779.  
  780.            const ar = currentAr.toLowerCase();
  781.            const activeRefs = referenceMedia.filter(m => m.active);
  782.  
  783.            if (action === 'gen_image') {
  784.                payload.n = parseInt(els.n.value); payload.resolution = els.resImg.value; payload.response_format = "b64_json";
  785.                if (ar !== 'auto') payload.aspect_ratio = ar; else if (activeRefs.length > 0) payload.aspect_ratio = 'auto';
  786.  
  787.                if (activeRefs.length > 0) {
  788.                    if (activeRefs.length === 1) payload.image = { url: activeRefs[0].base64 };
  789.                    else payload.images = activeRefs.map(m => ({ type: "image_url", url: m.base64 }));
  790.                }
  791.            } else if (action === 'gen_video') {
  792.                payload.duration = parseInt(els.duration.value); payload.resolution = els.resVid.value;
  793.                if (ar !== 'auto') payload.aspect_ratio = ar;
  794.                if (activeRefs.length > 0) payload.reference_images = activeRefs.map(m => ({ url: m.base64 }));
  795.            } else if (action === 'edit_video') {
  796.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  797.            } else if (action === 'extend_video') {
  798.                payload.duration = parseInt(els.duration.value);
  799.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  800.            }
  801.            return payload;
  802.        }
  803.  
  804.        // ─── CUSTOM PAYLOAD DEBUGGER LOGIC ────────────────────────────────────────
  805.        els.previewBtn.addEventListener('click', () => {
  806.            fullPayloadMemory = buildPayloadData();
  807.            const displayP = JSON.parse(JSON.stringify(fullPayloadMemory));
  808.            const trunc = "[BASE64_TRUNCATED_FOR_PREVIEW]";
  809.  
  810.            if (displayP.image) { if (Array.isArray(displayP.image)) displayP.image.forEach(img => img.url = trunc); else displayP.image.url = trunc; }
  811.            if (displayP.images && Array.isArray(displayP.images)) displayP.images.forEach(img => img.url = trunc);
  812.            if (displayP.reference_images && Array.isArray(displayP.reference_images)) displayP.reference_images.forEach(img => img.url = trunc);
  813.            if (displayP.video) displayP.video.url = trunc;
  814.  
  815.            const activeRefs = referenceMedia.filter(m => m.active);
  816.            let endpoint = '/v1/images/generations';
  817.            if (els.action.value === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  818.            else if (els.action.value === 'gen_video') endpoint = '/v1/videos/generations';
  819.            else if (els.action.value === 'edit_video') endpoint = '/v1/videos/edits';
  820.            else if (els.action.value === 'extend_video') endpoint = '/v1/videos/extensions';
  821.  
  822.            els.payloadEndpoint.value = endpoint;
  823.            els.payloadCode.value = JSON.stringify(displayP, null, 2);
  824.            els.payloadModal.style.display = 'flex';
  825.        });
  826.  
  827.        els.closePayloadBtn.addEventListener('click', () => els.payloadModal.style.display = 'none');
  828.  
  829.        function injectBase64(editedObj, originalObj) {
  830.            if (!editedObj || typeof editedObj !== 'object') return;
  831.            for (let key in editedObj) {
  832.                if (typeof editedObj[key] === 'string' && editedObj[key] === '[BASE64_TRUNCATED_FOR_PREVIEW]') {
  833.                    if (originalObj && originalObj[key]) editedObj[key] = originalObj[key];
  834.                } else if (typeof editedObj[key] === 'object') { injectBase64(editedObj[key], originalObj ? originalObj[key] : null); }
  835.            }
  836.        }
  837.  
  838.        els.sendCustomBtn.addEventListener('click', async () => {
  839.            initAudio();
  840.            let customPayload;
  841.            try { customPayload = JSON.parse(els.payloadCode.value); }
  842.            catch(e) { return alert("Invalid JSON format in textarea!"); }
  843.  
  844.            injectBase64(customPayload, fullPayloadMemory);
  845.            const endpoint = els.payloadEndpoint.value.trim();
  846.            const isImage = customPayload.model === "grok-imagine-image";
  847.  
  848.            stealthIdentityReset();
  849.  
  850.            els.sendCustomBtn.disabled = true;
  851.            els.sendCustomBtn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Processing...</div>`;
  852.            isRequestCancelled = false;
  853.  
  854.            const ok = await executeGenerationSingle(endpoint, customPayload, isImage, els.customStatus, 1, 1);
  855.  
  856.            els.sendCustomBtn.disabled = false;
  857.            els.sendCustomBtn.innerHTML = `<div class="btn-content">🚀 Send Custom Payload</div>`;
  858.            if (ok) notifyUser(false); else notifyUser(true);
  859.        });
  860.  
  861.        // ─── CSP-SAFE DELEGATED LIGHTBOX LOGIC ────────────────────────────────────
  862.        els.app.addEventListener('click', (e) => {
  863.            if (e.target && e.target.classList.contains('zoomable') && e.target.tagName === 'IMG') {
  864.                els.lightboxImg.src = e.target.src; els.lightboxDl.href = e.target.src; els.lightboxDl.download = e.target.dataset.filename || 'Reference_Image.jpg';
  865.                els.lightbox.style.display = 'flex';
  866.            }
  867.        });
  868.        els.lightbox.addEventListener('click', (e) => {
  869.            if (e.target.closest('#xai-lightbox-dl')) return;
  870.            if (e.target.closest('.modal-box')) return;
  871.            els.lightbox.style.display = 'none';
  872.        });
  873.        document.addEventListener('keydown', (e) => { if(e.key === 'Escape') { Array.from(document.querySelectorAll('.modal-overlay')).forEach(m => m.style.display = 'none'); } });
  874.  
  875.        // ─── FIXED FLOATING AR DROPDOWN LOGIC ─────────────────────────────────────
  876.        function renderArOptions() {
  877.            els.arOptionsCont.innerHTML = '';
  878.            arData.forEach(ar => {
  879.                const opt = document.createElement('div'); opt.className = 'ar-option';
  880.                opt.innerHTML = `${createArIcon(ar.w, ar.h, ar.isAuto)} <span>${ar.label}</span>`;
  881.                opt.addEventListener('click', () => { setAr(ar); els.arOptionsCont.style.display = 'none'; });
  882.                els.arOptionsCont.appendChild(opt);
  883.            });
  884.        }
  885.        function setAr(arObj) {
  886.            currentAr = arObj.label; localStorage.setItem('xai_api_ar', currentAr);
  887.            els.arSelectedIcon.innerHTML = createArIcon(arObj.w, arObj.h, arObj.isAuto); els.arSelectedText.innerText = arObj.label;
  888.        }
  889.        renderArOptions();
  890.        const initialAr = arData.find(a => a.label === currentAr) || arData[0]; setAr(initialAr);
  891.  
  892.        els.arSelectBox.addEventListener('click', (e) => {
  893.            e.stopPropagation();
  894.            if (els.arOptionsCont.style.display === 'block') { els.arOptionsCont.style.display = 'none'; return; }
  895.            const rect = els.arSelectBox.getBoundingClientRect();
  896.            els.arOptionsCont.style.top = (rect.bottom + 5) + 'px'; els.arOptionsCont.style.left = rect.left + 'px'; els.arOptionsCont.style.width = rect.width + 'px';
  897.            els.arOptionsCont.style.display = 'block';
  898.        });
  899.        document.addEventListener('click', (e) => { if (!els.arOptionsCont.contains(e.target)) els.arOptionsCont.style.display = 'none'; });
  900.  
  901.        // ─── UNLIMITED MULTI-IMAGE DRAG/DROP ──────────────────────────────────────
  902.        function processFile(file) {
  903.            const isVid = file.type.startsWith('video/'); const isImg = file.type.startsWith('image/');
  904.            if (!isVid && !isImg) return;
  905.  
  906.            if (isVid && (els.action.value === 'gen_image' || els.action.value === 'gen_video')) { els.action.value = 'edit_video'; updateActionUI(); updateGenSettingsMemory(); }
  907.            else if (isImg && (els.action.value === 'edit_video' || els.action.value === 'extend_video')) { els.action.value = 'gen_image'; updateActionUI(); updateGenSettingsMemory(); }
  908.  
  909.            const max = getMaxMedia();
  910.            const activeCount = referenceMedia.filter(m => m.active).length;
  911.  
  912.            const reader = new FileReader();
  913.            reader.onload = (event) => {
  914.                referenceMedia.push({ id: Date.now() + Math.random(), base64: event.target.result, isVideo: isVid, active: activeCount < max });
  915.                renderRefList();
  916.                if (isImg) setAr(arData[0]);
  917.            };
  918.            reader.readAsDataURL(file);
  919.        }
  920.  
  921.        let draggedIndex = null;
  922.        function renderRefList() {
  923.            els.refList.innerHTML = '';
  924.            referenceMedia.forEach((media, index) => {
  925.                const item = document.createElement('div');
  926.                item.className = 'ref-item';
  927.                item.draggable = true;
  928.  
  929.                let thumbHtml = media.isVideo
  930.                    ? `<video src="${media.base64}" class="ref-thumb" muted autoplay loop playsinline preload="metadata" style="background: #000;"></video>`
  931.                    : `<img src="${media.base64}" class="ref-thumb zoomable" data-filename="Reference_${index+1}.jpg" title="Click to view fullscreen">`;
  932.  
  933.                item.innerHTML = `
  934.                    <div class="ref-handle">☰</div>
  935.                    ${thumbHtml}
  936.                    <div class="ref-info">
  937.                        <span style="font-size: 12px; color: #e2e8f0; font-weight: 600;">Ref ${index + 1} ${media.isVideo ? '(Video)' : ''}</span>
  938.                        <label class="ref-toggle-label">
  939.                            <input type="checkbox" class="ref-active-toggle" ${media.active ? 'checked' : ''}> Use in Payload
  940.                        </label>
  941.                        <button class="ref-del">Remove</button>
  942.                    </div>
  943.                `;
  944.  
  945.                if (!media.active) item.classList.add('inactive');
  946.  
  947.                item.querySelector('.ref-active-toggle').addEventListener('change', (e) => {
  948.                    const max = getMaxMedia();
  949.                    const currentlyActive = referenceMedia.filter(r => r.active).length;
  950.  
  951.                    if (e.target.checked && currentlyActive >= max) {
  952.                        alert(`You can only have up to ${max} active references for this mode.`);
  953.                        e.target.checked = false;
  954.                        return;
  955.                    }
  956.                    media.active = e.target.checked;
  957.                    if (media.active) item.classList.remove('inactive'); else item.classList.add('inactive');
  958.                    saveRefs();
  959.                });
  960.  
  961.                item.addEventListener('dragstart', (e) => { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; setTimeout(() => item.classList.add('dragging'), 0); });
  962.                item.addEventListener('dragend', () => { item.classList.remove('dragging'); draggedIndex = null; document.querySelectorAll('.ref-item').forEach(el => el.classList.remove('drag-over-top', 'drag-over-bottom')); });
  963.                item.addEventListener('dragover', (e) => {
  964.                    e.preventDefault(); if (draggedIndex === null || draggedIndex === index) return;
  965.                    const rect = item.getBoundingClientRect();
  966.                    if (e.clientY - rect.top < rect.height / 2) { item.classList.add('drag-over-top'); item.classList.remove('drag-over-bottom'); }
  967.                    else { item.classList.add('drag-over-bottom'); item.classList.remove('drag-over-top'); }
  968.                });
  969.                item.addEventListener('dragleave', () => item.classList.remove('drag-over-top', 'drag-over-bottom'));
  970.                item.addEventListener('drop', (e) => {
  971.                    e.preventDefault(); item.classList.remove('drag-over-top', 'drag-over-bottom');
  972.                    if (draggedIndex === null || draggedIndex === index) return;
  973.                    const rect = item.getBoundingClientRect();
  974.                    let insertIndex = (e.clientY - rect.top) < rect.height / 2 ? index : index + 1;
  975.                    if (draggedIndex < insertIndex) insertIndex--;
  976.                    const [movedImage] = referenceMedia.splice(draggedIndex, 1);
  977.                    referenceMedia.splice(insertIndex, 0, movedImage); renderRefList();
  978.                });
  979.  
  980.                item.querySelector('.ref-del').addEventListener('click', () => { referenceMedia.splice(index, 1); renderRefList(); });
  981.                els.refList.appendChild(item);
  982.            });
  983.            saveRefs();
  984.        }
  985.  
  986.        els.uploadPlaceholder.addEventListener('click', () => { els.fileInput.click(); });
  987.        els.fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(processFile); els.fileInput.value = ''; });
  988.        document.addEventListener('paste', (e) => {
  989.            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;
  990.            const items = e.clipboardData.items; for (let i = 0; i < items.length; i++) if (items[i].type.indexOf('image') !== -1) processFile(items[i].getAsFile());
  991.        });
  992.  
  993.        els.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); els.dropzone.classList.add('drag-over'); });
  994.        els.dropzone.addEventListener('dragleave', () => els.dropzone.classList.remove('drag-over'));
  995.        els.dropzone.addEventListener('drop', (e) => { e.preventDefault(); els.dropzone.classList.remove('drag-over'); if (e.dataTransfer.files) Array.from(e.dataTransfer.files).forEach(processFile); });
  996.  
  997.        // ─── CANCEL BUTTON LOGIC ─────────────────────────────────────────────────
  998.        els.cancelBtn.addEventListener('click', () => {
  999.            isRequestCancelled = true;
  1000.            if (currentAbortController) currentAbortController.abort();
  1001.            els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex';
  1002.            els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1003.            els.status.innerText = "Request Cancelled."; els.status.className = ""; els.status.style.color = "#ef4444";
  1004.        });
  1005.  
  1006.        // ─── MASTER GENERATION LOGIC ──────────────────────────────────────────────
  1007.        async function executeGenerationSingle(endpoint, payload, isImageAction, statusEl, currentLoop, totalLoops) {
  1008.            let loopPrefix = totalLoops > 1 ? `[Run ${currentLoop}/${totalLoops}] ` : '';
  1009.            statusEl.innerText = `${loopPrefix}Processing request...`;
  1010.            statusEl.className = "status-pulsing";
  1011.  
  1012.            currentAbortController = new AbortController();
  1013.  
  1014.            let attempts = 0; let success = false;
  1015.            while (attempts < appSettings.retries && !success && !isRequestCancelled) {
  1016.                try {
  1017.                    statusEl.innerText = `${loopPrefix}Sending request to xAI...`;
  1018.  
  1019.                    const response = await fetch(endpoint, {
  1020.                        method: 'POST',
  1021.                        headers: { 'Content-Type': 'application/json' },
  1022.                        body: JSON.stringify(payload),
  1023.                        signal: currentAbortController.signal
  1024.                    });
  1025.  
  1026.                    if (response.status === 429 || response.status === 503 || response.status === 500 || response.status === 502) {
  1027.                        attempts++;
  1028.                        statusEl.innerText = `${loopPrefix}Busy (Error ${response.status}). Retrying... [${attempts}/${appSettings.retries}]`;
  1029.                        const delay = Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin;
  1030.                        await sleep(delay);
  1031.                        continue;
  1032.                    }
  1033.  
  1034.                    if (!response.ok) {
  1035.                        let errMsg = `HTTP ${response.status}`;
  1036.                        try {
  1037.                            const errData = await response.json();
  1038.                            if (errData.error && errData.error.message) errMsg += `\n${errData.error.message}`;
  1039.                            else if (errData.detail) errMsg += `\n${JSON.stringify(errData.detail)}`;
  1040.                        } catch(e) {}
  1041.                        throw new Error(errMsg);
  1042.                    }
  1043.  
  1044.                    const data = await response.json();
  1045.  
  1046.                    if (isImageAction) {
  1047.                        if (data && data.data && Array.isArray(data.data)) {
  1048.                            success = true;
  1049.                            statusEl.innerText = `${loopPrefix}Processing final JPEGs...`;
  1050.                            statusEl.style.color = "#10b981";
  1051.                            statusEl.className = "";
  1052.  
  1053.                            await Promise.all(data.data.map((imgObj, index) =>
  1054.                                processAndRenderImage(imgObj, payload.prompt, index + 1, data.data.length, els.currentImages)
  1055.                            ));
  1056.  
  1057.                            statusEl.innerText = "Ready";
  1058.                            statusEl.style.color = "#64748b";
  1059.                        } else throw new Error("Invalid response format.");
  1060.                    } else {
  1061.                        const reqId = data.request_id;
  1062.                        if (!reqId) throw new Error("No Request ID returned.");
  1063.  
  1064.                        success = true;
  1065.                        let videoReady = false;
  1066.                        let pollCount = 0;
  1067.                        const MAX_POLLS = 60;
  1068.  
  1069.                        while (!videoReady && !isRequestCancelled) {
  1070.                            pollCount++;
  1071.                            if (pollCount > MAX_POLLS) throw new Error("Timeout: Video likely dropped by filters.");
  1072.                            await sleep(5000);
  1073.                            if (isRequestCancelled) break;
  1074.  
  1075.                            const pollRes = await fetch(`/v1/videos/${reqId}`, { signal: currentAbortController.signal });
  1076.                            if (!pollRes.ok) continue;
  1077.  
  1078.                            const pollData = await pollRes.json();
  1079.                            if (pollData.error) throw new Error(`API Error: ${pollData.error.message || JSON.stringify(pollData.error)}`);
  1080.  
  1081.                            const state = (pollData.status || pollData.state || 'processing').toLowerCase();
  1082.                            statusEl.innerText = `${loopPrefix}Polling video (Status: ${state})...[${pollCount}/${MAX_POLLS}]`;
  1083.  
  1084.                            if (state === 'done' || state === 'completed') {
  1085.                                videoReady = true;
  1086.                                statusEl.innerText = "Ready"; statusEl.className = ""; statusEl.style.color = "#94a3b8";
  1087.                                renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1088.                            } else if (['failed', 'expired', 'rejected', 'blocked', 'moderated', 'nsfw'].includes(state) || pollData.is_sensitive) {
  1089.                                if (pollData.video && pollData.video.url) {
  1090.                                    videoReady = true;
  1091.                                    statusEl.innerText = `${loopPrefix}Warning: Flagged as ${state}, but recovered!`;
  1092.                                    statusEl.className = ""; statusEl.style.color = "#d97706";
  1093.                                    renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1094.                                } else {
  1095.                                    throw new Error(`Generation halted. Reason: ${state}`);
  1096.                                }
  1097.                            }
  1098.                        }
  1099.                    }
  1100.  
  1101.                } catch (err) {
  1102.                    if (err.name === 'AbortError' || isRequestCancelled) {
  1103.                        statusEl.innerText = "Request Cancelled."; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1104.                        return false;
  1105.                    } else {
  1106.                        statusEl.innerText = `${loopPrefix}Error: ${err.message}`; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1107.                        break;
  1108.                    }
  1109.                }
  1110.            }
  1111.  
  1112.            if (!success && !isRequestCancelled && attempts >= appSettings.retries) {
  1113.                statusEl.innerText = `${loopPrefix}Failed. Server overloaded after ${attempts} retries.`;
  1114.                statusEl.className = ""; statusEl.style.color = "#ef4444";
  1115.                return false;
  1116.            }
  1117.  
  1118.            return success;
  1119.        }
  1120.  
  1121.        els.btn.addEventListener('click', async () => {
  1122.            initAudio();
  1123.            if (!els.prompt.value.trim()) return alert("Please enter a prompt.");
  1124.  
  1125.            const oldImages = Array.from(els.currentImages.children);
  1126.            if (oldImages.length > 0) {
  1127.                if (els.history.innerText.includes("No history")) els.history.innerHTML = '';
  1128.                oldImages.forEach(card => {
  1129.                    card.className = 'history-card';
  1130.                    const promptEl = card.querySelector('p');
  1131.                    promptEl.title = "Click to copy prompt";
  1132.                    promptEl.onclick = () => { els.prompt.value = promptEl.innerText; localStorage.setItem('xai_api_prompt', els.prompt.value); };
  1133.                    els.history.prepend(card);
  1134.                });
  1135.            }
  1136.  
  1137.            const action = els.action.value;
  1138.            const activeRefs = referenceMedia.filter(m => m.active);
  1139.            let endpoint = '/v1/images/generations';
  1140.            if (action === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1141.            else if (action === 'gen_video') endpoint = '/v1/videos/generations';
  1142.            else if (action === 'edit_video') endpoint = '/v1/videos/edits';
  1143.            else if (action === 'extend_video') endpoint = '/v1/videos/extensions';
  1144.  
  1145.            const payload = buildPayloadData();
  1146.            const isImage = action === 'gen_image';
  1147.            const totalLoops = parseInt(els.loops.value) || 1;
  1148.  
  1149.            stealthIdentityReset();
  1150.  
  1151.            els.btn.disabled = true;
  1152.            els.cancelBtn.style.display = 'flex';
  1153.            els.previewBtn.style.display = 'none';
  1154.            isRequestCancelled = false;
  1155.  
  1156.            let allSuccess = true;
  1157.            for (let i = 1; i <= totalLoops; i++) {
  1158.                if (isRequestCancelled) break;
  1159.  
  1160.                els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Gen ${i}/${totalLoops}...</div>`;
  1161.  
  1162.                const ok = await executeGenerationSingle(endpoint, payload, isImage, els.status, i, totalLoops);
  1163.                if (!ok) {
  1164.                    allSuccess = false;
  1165.                    break;
  1166.                }
  1167.            }
  1168.  
  1169.            if (!isRequestCancelled) {
  1170.                els.cancelBtn.style.display = 'none';
  1171.                els.previewBtn.style.display = 'flex';
  1172.                els.btn.disabled = false;
  1173.                els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1174.  
  1175.                if (allSuccess) {
  1176.                    els.status.innerText = "All runs complete.";
  1177.                    els.status.className = "";
  1178.                    els.status.style.color = "#64748b";
  1179.                    notifyUser(false);
  1180.                } else {
  1181.                    notifyUser(true);
  1182.                }
  1183.            }
  1184.        });
  1185.  
  1186.        // ─── SESSION RESETTER ─────────────────────────────────────────────────────
  1187.        els.reset.addEventListener('click', () => {
  1188.            if (!confirm("Wipe cache? (This forces a page reload to clear front-end tokens). Your prompt and settings will be saved.")) return;
  1189.            localStorage.setItem('xai_api_prompt', els.prompt.value);
  1190.            const patterns =[/flushAfter/i, /imagine/i, /generation/i, /grok/i, /mixpanel|mp_/i, /distinct_id/i, /_rst/i, /limit/i, /credit/i];
  1191.            for (let i = localStorage.length - 1; i >= 0; i--) {
  1192.                const k = localStorage.key(i);
  1193.                if (k && !k.startsWith('xai_api_') && patterns.some(p => p.test(k))) localStorage.removeItem(k);
  1194.            }
  1195.            document.cookie.split(';').forEach(c => {
  1196.                const name = c.split('=')[0]?.trim();
  1197.                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 : ''}`; });
  1198.                });
  1199.            });
  1200.            const u = new URL(location.href);
  1201.            ['_r', '_rst'].forEach(k => u.searchParams.set(k, Date.now()));
  1202.            location.replace(u.toString());
  1203.        });
  1204.    }
  1205.  
  1206.    // ─── ASYNC PROCESSORS & RENDERERS ─────────────────────────────────────────
  1207.    async function processAndRenderImage(imgObj, originalPrompt, num, total, galleryEl) {
  1208.        if (!imgObj.b64_json) return;
  1209.        const mime = imgObj.mime_type || "image/png";
  1210.        const b64 = imgObj.b64_json;
  1211.        const pngDataUri = `data:${mime};base64,${b64}`;
  1212.  
  1213.        const finalPrompt = imgObj.revised_prompt || originalPrompt;
  1214.        const jpegDataUri = await convertToJpegWithExif(pngDataUri, finalPrompt);
  1215.        const filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.jpg`;
  1216.  
  1217.        const card = document.createElement('div');
  1218.        card.className = 'current-card';
  1219.        card.innerHTML = `
  1220.            <div class="img-wrapper">
  1221.                <img src="${jpegDataUri}" class="zoomable" data-filename="${filename}" title="Click to view fullscreen">
  1222.                <a href="${jpegDataUri}" download="${filename}" class="overlay-dl-btn" title="Download Full JPG">${DOWNLOAD_ICON}</a>
  1223.            </div>
  1224.            <p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${finalPrompt}</p>
  1225.        `;
  1226.        galleryEl.prepend(card);
  1227.    }
  1228.  
  1229.    function renderVideoToGallery(videoUrl, originalPrompt, galleryEl) {
  1230.        const filename = `Grok Video - ${makeTimestamp()}.mp4`;
  1231.        const card = document.createElement('div');
  1232.        card.className = 'current-card';
  1233.        card.innerHTML = `
  1234.            <div class="img-wrapper">
  1235.                <video src="${videoUrl}" controls autoplay loop style="width: 100%; display: block; max-height: 50vh; object-fit: contain; background: #000;"></video>
  1236.                <a href="${videoUrl}" target="_blank" download="${filename}" class="overlay-dl-btn" style="z-index: 50;" title="Download MP4">${DOWNLOAD_ICON}</a>
  1237.            </div>
  1238.            <p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${originalPrompt}</p>
  1239.        `;
  1240.        galleryEl.prepend(card);
  1241.    }
  1242.  
  1243.    if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initApp); }
  1244.    else { initApp(); }
  1245.  
  1246. })();
Add Comment
Please, Sign In to add comment