Guest User

Untitled

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