Guest User

Untitled

a guest
Apr 3rd, 2026
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         xAI Pro Studio Frontend (v32a - >>79544 version)
  3. // @namespace    http://tampermonkey.net/
  4. // @version      32a
  5. // @description  Full-Screen UI, Exif Fix, Multi-Image, Auto-Retry, Export Settings, Video Warnings, Quick-Action Sliders, Adaptive AR
  6. // @match        https://console.x.ai/playground/imagine*
  7. // @match        https://console.x.ai/team/*/imagine*
  8. // @grant        GM_xmlhttpRequest
  9. // @connect      vidgen.x.ai
  10. // @run-at       document-start
  11. // ==/UserScript==
  12.  
  13. (function() {
  14.     'use strict';
  15.  
  16.     // ─── LOGGING & DEBUG ENGINE ───────────────────────────────────────────────
  17.     const appLogs = [];
  18.     const MAX_LOGS = 500;
  19.  
  20.     function stripHeavyData(val) {
  21.         if (val === null || val === undefined) return val;
  22.         if (typeof val === 'string') {
  23.             if (val.startsWith('data:image') || val.startsWith('data:video') || val.length > 2000) {
  24.                 return `[TRUNCATED_DATA_LEN_${val.length}]`;
  25.             }
  26.             return val;
  27.         }
  28.         if (typeof val !== 'object') return val;
  29.         if (Array.isArray(val)) return val.map(stripHeavyData);
  30.         const copy = {};
  31.         for (const k in val) {
  32.             if (Object.prototype.hasOwnProperty.call(val, k)) {
  33.                 copy[k] = stripHeavyData(val[k]);
  34.             }
  35.         }
  36.         return copy;
  37.     }
  38.  
  39.     function addLog(level, msg, data = null) {
  40.         try {
  41.             const ts = new Date().toISOString().replace('T', ' ').substring(0, 23);
  42.             const safeData = data ? stripHeavyData(data) : null;
  43.             appLogs.push({ ts, level, msg, data: safeData });
  44.             if (appLogs.length > MAX_LOGS) appLogs.shift();
  45.  
  46.             const consoleMsg = `[xAI Studio] [${level}] ${msg}`;
  47.             if (level === 'ERROR') console.error(consoleMsg, safeData || '');
  48.             else if (level === 'WARN') console.warn(consoleMsg, safeData || '');
  49.             else console.log(consoleMsg, safeData || '');
  50.         } catch(e) {}
  51.     }
  52.  
  53.     function formatLogsForExport() {
  54.         return appLogs.map(l => {
  55.             let text = `[${l.ts}] [${l.level}] ${l.msg}`;
  56.             if (l.data) {
  57.                 try { text += `\n${JSON.stringify(l.data, null, 2)}`; }
  58.                 catch(e) { text += `\n[Unserializable Data]`; }
  59.             }
  60.             return text;
  61.         }).join('\n\n----------------------------------------\n\n');
  62.     }
  63.  
  64.     addLog('INFO', 'Script started executing');
  65.  
  66.     // ─── UTILITIES & DATA STORAGE ─────────────────────────────────────────────
  67.     const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  68.     function pad2(n) { return String(n).padStart(2, '0'); }
  69.     function makeTimestamp() {
  70.         const d = new Date();
  71.         return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}-${pad2(d.getMinutes())}-${pad2(d.getSeconds())}`;
  72.     }
  73.     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>`;
  74.     const EDIT_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`;
  75.  
  76.     let appSettings = JSON.parse(localStorage.getItem('xai_api_settings') || '{}');
  77.     appSettings.retries = parseInt(appSettings.retries) || 20;
  78.     appSettings.delayMin = parseInt(appSettings.delayMin) || 2000;
  79.     appSettings.delayMax = parseInt(appSettings.delayMax) || 4000;
  80.     if (typeof appSettings.rateLimitDelay === 'undefined') appSettings.rateLimitDelay = 60;
  81.     if (typeof appSettings.notifications === 'undefined') appSettings.notifications = true;
  82.     if (typeof appSettings.customCSS === 'undefined') appSettings.customCSS = "";
  83.     if (typeof appSettings.saveAsPng === 'undefined') appSettings.saveAsPng = false;
  84.     if (typeof appSettings.apiBaseUrl === 'undefined') appSettings.apiBaseUrl = "";
  85.     if (typeof appSettings.videoPollTimeout === 'undefined') appSettings.videoPollTimeout = 300;
  86.     if (typeof appSettings.autoRetryStuckVideo === 'undefined') appSettings.autoRetryStuckVideo = false;
  87.     if (typeof appSettings.breakLoopOnFailure === 'undefined') appSettings.breakLoopOnFailure = true;
  88.  
  89.     if (typeof appSettings.suppressEditWarning === 'undefined') appSettings.suppressEditWarning = false;
  90.     if (typeof appSettings.videoAutoplay === 'undefined') appSettings.videoAutoplay = true;
  91.     if (typeof appSettings.videoMuted === 'undefined') appSettings.videoMuted = false;
  92.     if (typeof appSettings.uiFontSize === 'undefined') appSettings.uiFontSize = 13;
  93.  
  94.     let favoritePrompts = JSON.parse(localStorage.getItem('xai_api_favs') || '[]');
  95.  
  96.     function getApiUrl(path) {
  97.         let base = appSettings.apiBaseUrl || '';
  98.         if (base.endsWith('/')) base = base.slice(0, -1);
  99.         if (!path.startsWith('/') && base) path = '/' + path;
  100.         return base + path;
  101.     }
  102.  
  103.     function parseDynamicPrompt(text) {
  104.         if (!text) return text;
  105.         let parsed = text; let prev;
  106.         do {
  107.             prev = parsed;
  108.             parsed = parsed.replace(/\{([^{}]+)\}/g, (m, c) => { const o = c.split('|'); return o[Math.floor(Math.random() * o.length)]; });
  109.         } while (parsed !== prev);
  110.         parsed = parsed.replace(/@randomseed/gi, () => Math.floor(1000000000 + Math.random() * 9000000000).toString());
  111.         return parsed.trim();
  112.     }
  113.  
  114.     let sharedAudioCtx = null;
  115.     let titleBlinkInterval = null;
  116.     const originalTitle = document.title || "xAI Pro Studio";
  117.  
  118.     function initAudio() {
  119.         if (!sharedAudioCtx && appSettings.notifications) {
  120.             try { sharedAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch(e) {}
  121.         }
  122.         if (sharedAudioCtx && sharedAudioCtx.state === 'suspended') sharedAudioCtx.resume();
  123.     }
  124.  
  125.     function notifyUser(isError = false) {
  126.         if (!appSettings.notifications) return;
  127.         if (sharedAudioCtx) {
  128.             try {
  129.                 const osc = sharedAudioCtx.createOscillator(); const gain = sharedAudioCtx.createGain();
  130.                 osc.connect(gain); gain.connect(sharedAudioCtx.destination);
  131.                 if (isError) {
  132.                     osc.type = 'sawtooth'; osc.frequency.setValueAtTime(300, sharedAudioCtx.currentTime); osc.frequency.exponentialRampToValueAtTime(100, sharedAudioCtx.currentTime + 0.3);
  133.                 } else {
  134.                     osc.type = 'sine'; osc.frequency.setValueAtTime(500, sharedAudioCtx.currentTime); osc.frequency.exponentialRampToValueAtTime(1000, sharedAudioCtx.currentTime + 0.2);
  135.                 }
  136.                 gain.gain.setValueAtTime(0.1, sharedAudioCtx.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, sharedAudioCtx.currentTime + 0.5);
  137.                 osc.start(sharedAudioCtx.currentTime); osc.stop(sharedAudioCtx.currentTime + 0.5);
  138.             } catch(e) {}
  139.         }
  140.         if (!document.hasFocus()) {
  141.             if (titleBlinkInterval) clearInterval(titleBlinkInterval);
  142.             let toggle = true;
  143.             titleBlinkInterval = setInterval(() => { document.title = toggle ? (isError ? "❌ FAILED" : "✅ DONE") : originalTitle; toggle = !toggle; }, 1000);
  144.             const clearBlink = () => { clearInterval(titleBlinkInterval); document.title = originalTitle; window.removeEventListener('focus', clearBlink); };
  145.             window.addEventListener('focus', clearBlink);
  146.         }
  147.     }
  148.  
  149.     function stealthIdentityReset() {
  150.         const trackingCookies =['x-anonuserid', 'mixpanel', 'mp_', 'distinct_id'];
  151.         document.cookie.split(';').forEach(c => {
  152.             const name = c.split('=')[0].trim();
  153.             if (trackingCookies.some(tc => name.includes(tc))) {['.x.ai', 'console.x.ai', ''].forEach(d => {['/', '/playground/imagine', ''].forEach(p => {
  154.                 document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${p}${d ? ';domain=' + d : ''}`;
  155.             });});}
  156.         });
  157.         for (let i = localStorage.length - 1; i >= 0; i--) {
  158.             const k = localStorage.key(i);
  159.             if (k && !k.startsWith('xai_api_') && trackingCookies.some(tc => k.includes(tc))) localStorage.removeItem(k);
  160.         }
  161.     }
  162.  
  163.     let piexifLoaded = false;
  164.     function loadPiexif() {
  165.         if (piexifLoaded) return Promise.resolve(window.piexif);
  166.         return new Promise(resolve => {
  167.             const script = document.createElement('script'); script.src = 'https://cdn.jsdelivr.net/npm/piexifjs';
  168.             script.onload = () => { piexifLoaded = true; resolve(window.piexif); }; document.head.appendChild(script);
  169.         });
  170.     }
  171.  
  172.     function toUTF16LE(str) {
  173.         const arr =[];
  174.         for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i); arr.push(code & 0xFF); arr.push((code >> 8) & 0xFF); }
  175.         arr.push(0, 0); return arr;
  176.     }
  177.  
  178.     function convertToJpegWithExif(base64PngUri, prompt) {
  179.         return new Promise((resolve, reject) => {
  180.             const img = new Image();
  181.             img.onload = async () => {
  182.                 const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height;
  183.                 const ctx = canvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0);
  184.                 let jpegUri = canvas.toDataURL('image/jpeg', 0.95);
  185.                 if (prompt) {
  186.                     try {
  187.                         const piexif = await loadPiexif();
  188.                         const exifObj = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "Interop": {}};
  189.                         exifObj['0th'][piexif.ImageIFD.ImageDescription] = unescape(encodeURIComponent(prompt));
  190.                         const utf16Prompt = toUTF16LE(prompt); exifObj['0th'][40091] = utf16Prompt; exifObj['0th'][40092] = utf16Prompt; exifObj['0th'][40093] = utf16Prompt;
  191.                         jpegUri = piexif.insert(piexif.dump(exifObj), jpegUri);
  192.                     } catch (e) {}
  193.                 }
  194.                 resolve(jpegUri);
  195.             };
  196.             img.onerror = reject; img.src = base64PngUri;
  197.         });
  198.     }
  199.  
  200.     async function extractPromptFromImage(file) {
  201.         if (!file.type.includes('image')) return null;
  202.         try {
  203.             const piexif = await loadPiexif();
  204.             return new Promise((resolve) => {
  205.                 const reader = new FileReader();
  206.                 reader.onload = (e) => {
  207.                     try {
  208.                         const exifData = piexif.load(e.target.result);
  209.                         let prompt = exifData['0th'] && exifData['0th'][piexif.ImageIFD.ImageDescription];
  210.                         if (Array.isArray(prompt)) prompt = String.fromCharCode.apply(null, prompt).replace(/\0/g, '');
  211.                         if (prompt) { try { prompt = decodeURIComponent(escape(prompt)); } catch(e) {} }
  212.                         if (!prompt && exifData['0th'] && exifData['0th'][40091]) {
  213.                             const xpTitleArr = exifData['0th'][40091]; let str = '';
  214.                             for (let i = 0; i < xpTitleArr.length; i += 2) { const charCode = xpTitleArr[i] | (xpTitleArr[i+1] << 8); if (charCode === 0) break; str += String.fromCharCode(charCode); }
  215.                             prompt = str;
  216.                         }
  217.                         resolve(prompt ? prompt.trim() : null);
  218.                     } catch (err) { resolve(null); }
  219.                 };
  220.                 reader.readAsDataURL(file);
  221.             });
  222.         } catch (e) { return null; }
  223.     }
  224.  
  225.     function generateVideoThumbnail(file) {
  226.         return new Promise((resolve) => {
  227.             const video = document.createElement('video'); video.preload = 'metadata'; video.muted = true; video.playsInline = true;
  228.             const url = URL.createObjectURL(file); video.src = url; let isSeeked = false;
  229.             video.onloadeddata = () => { video.currentTime = Math.min(0.5, video.duration / 2 || 0); file._w = video.videoWidth; file._h = video.videoHeight; };
  230.             video.onseeked = () => {
  231.                 if (isSeeked) return; isSeeked = true;
  232.                 try {
  233.                     const canvas = document.createElement('canvas'); canvas.width = video.videoWidth || 140; canvas.height = video.videoHeight || 140;
  234.                     const ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, canvas.width, canvas.height); URL.revokeObjectURL(url); resolve(canvas.toDataURL('image/jpeg', 0.8));
  235.                 } catch(e) { URL.revokeObjectURL(url); resolve(null); }
  236.             };
  237.             video.onerror = () => { URL.revokeObjectURL(url); resolve(null); };
  238.             setTimeout(() => { if (!isSeeked) { URL.revokeObjectURL(url); resolve(null); } }, 2000);
  239.         });
  240.     }
  241.  
  242.     function updateFontSize(size) {
  243.         let el = document.getElementById('xai-custom-font-size');
  244.         if (!el) { el = document.createElement('style'); el.id = 'xai-custom-font-size'; document.head.appendChild(el); }
  245.         if (size === 13) { el.innerHTML = ''; return; } // Default size, no overrides needed
  246.  
  247.         el.innerHTML = `
  248.             #xai-pro-app textarea, #xai-pro-app #prompt-backdrop, #xai-pro-app select, #xai-pro-app input[type="text"], #xai-pro-app input[type="number"], #xai-pro-app .btn-primary, #xai-pro-app .btn-secondary, #xai-pro-app .ar-select-box, #xai-pro-app .action-select { font-size: ${size}px !important; }
  249.             #xai-pro-app .ar-option, #xai-pro-app .fav-text, #xai-pro-app #xai-api-status { font-size: ${size - 1}px !important; }
  250.             #xai-pro-app .panel-title, #xai-pro-app label, #xai-pro-app .toggle-btn, #xai-pro-app .slider-header, #xai-pro-app .history-card p, #xai-pro-app .warning-box, #xai-pro-app .ref-info span { font-size: ${size - 2}px !important; }
  251.             #xai-pro-app .slider-ticks, #xai-pro-app .slider-ticks span, #xai-pro-app .ref-action-btn, #xai-pro-app .ref-toggle-label, #xai-pro-app .ref-thumb span, #xai-pro-app button[style*="font-size: 10px"] { font-size: ${size - 3}px !important; }
  252.             #xai-pro-app .ref-handle { font-size: ${size + 1}px !important; }
  253.             #xai-pro-app h3 { font-size: ${size + 2}px !important; }
  254.         `;
  255.     }
  256.  
  257.     // ─── DATA MAPS FOR UI SLIDERS ─────────────────────────────────────────────
  258.     const MAPS = {
  259.         batch: [1, 2, 3, 4, 5, 8, 10],
  260.         /*resImg: [{v:'1k', l:'1K', t:'1K'}, {v:'2k', l:'2K (Pro)', t:'2K'}],*/
  261.         /*resVid: [{v:'480p', l:'480p (SD)', t:'480p'}, {v:'720p', l:'720p (HD)', t:'720p'}],*/
  262.         durGen: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
  263.         durExt: [1, 2, 3, 4, 6, 7, 8, 9, 10]
  264.     };
  265.  
  266.     const arData =[
  267.         { label: 'Auto', w: 1, h: 1, isAuto: true },
  268.         { label: 'By First Ref', w: 1, h: 1, isAuto: true, isRef: true },
  269.         { label: '1:1', w: 1, h: 1 }, { label: '3:4', w: 3, h: 4 }, { label: '4:3', w: 4, h: 3 },
  270.         { label: '9:16', w: 9, h: 16 }, { label: '16:9', w: 16, h: 9 }, { label: '2:3', w: 2, h: 3 },
  271.         { 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 },
  272.         { 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 }
  273.     ];
  274.  
  275.     function createArIcon(w, h, isAuto, isRef) {
  276.         if (isRef) return `<div style="width: 12px; height: 12px; border: 1px dashed #10b981; border-radius: 2px; display: flex; align-items: center; justify-content: center; font-size: 8px; color: #10b981; font-weight:bold;">R</div>`;
  277.         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>`;
  278.         const scale = 12 / Math.max(w, h);
  279.         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>`;
  280.     }
  281.  
  282.     // ─── UI INJECTION ─────────────────────────────────────────────────────────
  283.     const UI_CSS = `
  284.         ::-webkit-scrollbar { width: 6px; }
  285.         ::-webkit-scrollbar-track { background: #0f172a; }
  286.         ::-webkit-scrollbar-thumb { background: #475569; border-radius: 6px; }
  287.  
  288.         @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  289.         @keyframes pulse { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
  290.  
  291.         .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; }
  292.         .btn-content { display: flex; align-items: center; justify-content: center; gap: 6px; }
  293.         .status-pulsing { animation: pulse 2s ease-in-out infinite; color: #3b82f6 !important; font-weight: 600; }
  294.  
  295.         #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; }
  296.         #xai-pro-app * { box-sizing: border-box; }
  297.  
  298.         .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; }
  299.         .panel-title { font-size: 11px; font-weight: 700; color: #94a3b8; letter-spacing: 0.5px; padding: 10px; border-bottom: 1px solid #334155; text-transform: uppercase; }
  300.  
  301.         .col-left { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; }
  302.         .col-center { flex: 1; display: flex; flex-direction: column; gap: 10px; min-width: 0; min-height: 0; }
  303.         .col-right { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; transition: 0.2s; }
  304.         .col-right.drag-over { background: #064e3b; border-color: #10b981; box-shadow: 0 0 0 4px rgba(16,185,129,0.15); border-radius: 10px; }
  305.  
  306.         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; }
  307.         textarea, select, input[type="text"], input[type="number"] { width: 100%; }
  308.         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); }
  309.         label { font-size: 11px; font-weight: 600; color: #94a3b8; margin-bottom: 4px; display: block; }
  310.  
  311.         .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; }
  312.         .btn-primary:hover:not(:disabled) { background: linear-gradient(180deg, #4f46e5 0%, #4338ca 100%); transform: translateY(-1px); }
  313.         .btn-primary:disabled { opacity: 0.8; cursor: not-allowed; }
  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.         /* Sliders and Actions */
  318.         .action-select { width: 100%; font-weight: 600; font-size: 13px; color: #f8fafc; background: transparent; border: none; outline: none; overflow-y: hidden; }
  319.         .action-select option { padding: 8px 10px; margin-bottom: 4px; border-radius: 6px; cursor: pointer; transition: 0.1s; background: #0f172a; border: 1px solid #334155; }
  320.         .action-select option:checked { background: linear-gradient(180deg, #6366f1 0%, #4f46e5 100%); border-color: #4f46e5; color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
  321.         .action-select option:hover:not(:checked) { background: #334155; }
  322.  
  323.         .slider-block { display: flex; flex-direction: column; margin-bottom: 12px; }
  324.         .toggle-btn { background: #0f172a; border: 1px solid #334155; color: #94a3b8; padding: 6px 12px; border-radius: 6px; font-size: 11px; font-weight: 600; cursor: pointer; transition: 0.2s; box-shadow: inset 0 2px 4px rgba(0,0,0,0.2); }
  325.         .toggle-btn.active { background: linear-gradient(180deg, #10b981 0%, #059669 100%); color: #fff; border-color: #047857; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
  326.         .slider-header { display: flex; justify-content: space-between; font-size: 11px; margin-bottom: 6px; font-weight: 600; color: #94a3b8; }
  327.         .slider-header span { color: #f8fafc; }
  328.         .slider-ticks { position: relative; height: 14px; width: 100%; font-size: 10px; color: #64748b; margin-top: 4px; padding: 0; }
  329.         .slider-ticks span { position: absolute; transform: translateX(-50%); text-align: center; white-space: nowrap; line-height: 1; }
  330.  
  331.         input[type=range] { -webkit-appearance: none; width: 100%; background: transparent; margin: 4px 0; outline: none; }
  332.         input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 6px; cursor: pointer; background: #334155; border-radius: 3px; box-shadow: inset 0 1px 3px rgba(0,0,0,0.6); }
  333.         input[type=range]::-moz-range-track { width: 100%; height: 6px; cursor: pointer; background: #334155; border-radius: 3px; box-shadow: inset 0 1px 3px rgba(0,0,0,0.6); }
  334.         input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; height: 16px; width: 16px; border-radius: 50%; background: #10b981; cursor: pointer; margin-top: -5px; box-shadow: 0 2px 5px rgba(0,0,0,0.6); }
  335.         input[type=range]::-moz-range-thumb { height: 16px; width: 16px; border-radius: 50%; background: #10b981; cursor: pointer; border: none; box-shadow: 0 2px 5px rgba(0,0,0,0.6); }
  336.         input[type=range]:focus::-webkit-slider-thumb { box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4); }
  337.         input[type=range]:focus::-moz-range-thumb { box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4); }
  338.  
  339.         .ar-select-box { background: #1e293b; border: 1px solid #475569; border-radius: 6px; padding: 8px; display: flex; align-items: center; gap: 8px; cursor: pointer; color: #f8fafc; font-size: 13px; }
  340.         #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; }
  341.         .ar-option { display: flex; align-items: center; gap: 8px; padding: 6px 8px; cursor: pointer; font-size: 12px; color: #cbd5e1; }
  342.         .ar-option:hover { background: #334155; color: #f8fafc; }
  343.  
  344.         .img-wrapper { position: relative; display: block; }
  345.         .zoomable { cursor: zoom-in; transition: transform 0.2s; width: 100%; display: block; }
  346.         .overlay-btn { position: absolute; top: 6px; background: rgba(15, 23, 42, 0.6); color: white; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; text-decoration: none; backdrop-filter: blur(4px); transition: 0.2s; opacity: 0.75; z-index: 50; cursor: pointer; border: none; padding: 0; }
  347.         .overlay-btn:hover { background: rgba(15, 23, 42, 0.9); opacity: 1; transform: scale(1.05); }
  348.         .overlay-dl-btn { right: 6px; }
  349.         .overlay-edit-btn { right: 40px; color: #10b981; }
  350.  
  351.         .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; }
  352.         .ref-item.inactive { opacity: 0.6; filter: grayscale(0.8); }
  353.         .ref-item:active { cursor: grabbing; }
  354.         .ref-item.dragging { opacity: 0.4; }
  355.         .ref-handle { font-size: 14px; color: #475569; cursor: grab; padding: 0 4px; }
  356.         .ref-thumb { width: 90px; height: 90px; border-radius: 4px; object-fit: cover; border: 1px solid #334155; background: #0f172a; transition: 0.2s; }
  357.         .ref-info { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 6px; min-width: 0; }
  358.         .ref-toggle-label { font-size: 11px; color: #cbd5e1; display: flex; align-items: center; gap: 4px; cursor: pointer; user-select: none; }
  359.         .ref-toggle-label input { width: 12px; height: 12px; cursor: pointer; accent-color: #10b981; margin: 0; padding: 0; }
  360.         .ref-btn-group { display: flex; gap: 4px; width: 100%; margin-top: auto; }
  361.         .ref-action-btn { flex: 1; border-radius: 4px; padding: 4px 0; cursor: pointer; font-size: 10px; transition: 0.2s; font-weight: bold; text-align: center; }
  362.         .ref-insert { background: #0f766e; color: #ccfbf1; border: 1px solid #115e59; }
  363.         .ref-insert:hover { background: #115e59; color: #f0fdfa; }
  364.         .ref-del { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
  365.         .ref-del:hover { background: #7f1d1d; color: #fee2e2; }
  366.         .drag-over-top { border-top: 2px solid #22c55e !important; }
  367.         .drag-over-bottom { border-bottom: 2px solid #22c55e !important; }
  368.  
  369.         .history-card { background: #0f172a; border: 1px solid #334155; border-radius: 6px; overflow: hidden; margin-bottom: 10px; }
  370.         .history-card .overlay-btn { width: 24px; height: 24px; top: 4px; border-radius: 4px; }
  371.         .history-card .overlay-dl-btn { right: 4px; }
  372.         .history-card .overlay-edit-btn { right: 32px; }
  373.         .history-card p { padding: 8px; margin: 0; font-size: 11px; color: #94a3b8; cursor: pointer; transition: 0.2s; }
  374.         .history-card p:hover { background: #1e293b; color: #e2e8f0; }
  375.  
  376.         .current-card { border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.3); border: 1px solid #334155; background: #1e293b; }
  377.         .current-card img, .current-card video { max-height: 50vh; object-fit: contain; background: #0f172a; }
  378.  
  379.         .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); }
  380.         .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; }
  381.         .fav-item { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 8px; border-radius: 6px; border: 1px solid #334155; }
  382.         .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; }
  383.         .fav-text:hover { color: #10b981; }
  384.  
  385.         #settings-btn { position: fixed; top: 10px; right: 15px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
  386.         #settings-btn:hover { transform: rotate(45deg); opacity: 1; }
  387.         #logs-btn { position: fixed; top: 10px; right: 45px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
  388.         #logs-btn:hover { transform: scale(1.15); opacity: 1; }
  389.  
  390.         #xai-lightbox { cursor: zoom-out; }
  391.         #xai-lightbox-wrapper { position: relative; display: inline-block; max-width: 95vw; max-height: 95vh; }
  392.         #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); }
  393.  
  394.         .prompt-container { position: relative; width: 100%; height: 100px; min-height: 70px; margin-bottom: 10px; resize: vertical; overflow: hidden; border: 1px solid #334155; border-radius: 6px; background: #0f172a; transition: 0.2s; box-sizing: border-box; font-family: 'Inter', -apple-system, sans-serif; }
  395.         .prompt-container:focus-within { border-color: #64748b; background: #1e293b; box-shadow: 0 0 0 2px rgba(100,116,139,0.2); }
  396.         .prompt-container.prompt-drag-over { border-color: #10b981 !important; background: #064e3b !important; box-shadow: 0 0 0 2px rgba(16,185,129,0.15) !important; }
  397.         #prompt-backdrop { position: absolute; top: 0; left: 0; right: 0; bottom: 0; padding: 8px; font-size: 13px; font-family: inherit; white-space: pre-wrap; word-wrap: break-word; overflow-y: auto; color: transparent; z-index: 1; opacity: 0; box-sizing: border-box; pointer-events: none; }
  398.         .prompt-tag { pointer-events: auto; }
  399.         #xai-api-prompt { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; resize: none; background: transparent; border: none; box-shadow: none; outline: none; padding: 8px; font-size: 13px; font-family: inherit; color: #f8fafc; box-sizing: border-box; margin: 0; }
  400.         #xai-api-prompt:focus { background: transparent; border: none; box-shadow: none; }
  401.  
  402.         .warning-box { border-radius: 6px; padding: 6px 10px; font-size: 11px; margin-bottom: 8px; font-weight: 500; display: block; }
  403.         .warning-red { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
  404.         .warning-yellow { background: #422006; color: #fcd34d; border: 1px solid #78350f; }
  405.     `;
  406.  
  407.     const UI_HTML = `
  408.         <div id="xai-pro-app">
  409.             <div id="settings-btn" title="Studio Settings">⚙️</div>
  410.             <div id="logs-btn" title="Debug Logs">🐛</div>
  411.  
  412.             <!-- LEFT COLUMN -->
  413.             <div class="col-left">
  414.                 <div class="panel" style="flex-shrink: 0;">
  415.                     <div style="display: flex; background: transparent; border-radius: 0 0 6px 6px; margin-bottom: 6px; padding: 10px; padding-bottom: 0;">
  416.                         <select id="master-action" size="4" class="action-select">
  417.                             <option value="gen_image" selected>🖼️ Generate Image</option>
  418.                             <option value="gen_video">🎥 Generate Video</option>
  419.                             <option value="edit_video">✂️ Edit Video</option>
  420.                             <option value="extend_video">➡️ Extend Video</option>
  421.                         </select>
  422.                     </div>
  423.  
  424.                     <div style="padding: 10px; display: flex; flex-direction: column; overflow-y: auto;">
  425.                         <div id="setting-ar" class="slider-block">
  426.                             <div class="slider-header"><label style="margin:0;">Aspect Ratio</label></div>
  427.                             <div class="ar-select-box" id="ar-select-box">
  428.                                 <div id="ar-selected-icon"></div>
  429.                                 <span id="ar-selected-text">Auto</span>
  430.                             </div>
  431.                         </div>
  432.  
  433.                         <div id="setting-high-res" class="slider-block" style="flex-direction: row; justify-content: space-between; align-items: center;">
  434.                             <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;">High Resolution</label></div>
  435.                             <button id="high-res-btn" class="toggle-btn active">ON (2K / 720p)</button>
  436.                         </div>
  437.  
  438.                         <div id="setting-batch" class="slider-block">
  439.                             <div class="slider-header"><label style="margin:0;">Batch Size</label> <span id="val-batch">1 Image</span></div>
  440.                             <input type="range" id="xai-api-n" min="0" max="6" value="0">
  441.                             <div class="slider-ticks" id="ticks-batch"></div>
  442.                         </div>
  443.  
  444.                         <div id="setting-duration" class="slider-block" style="display: none;">
  445.                             <div class="slider-header"><label style="margin:0;">Duration</label> <span id="val-duration">5 Seconds</span></div>
  446.                             <input type="range" id="xai-api-duration" min="0" max="14" value="4">
  447.                             <div class="slider-ticks" id="ticks-duration"></div>
  448.                         </div>
  449.  
  450.                         <div id="setting-loops" class="slider-block">
  451.                             <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;" title="How many consecutive API calls to perform in a row">Loops</label></div>
  452.                             <div style="display: flex; gap: 10px; align-items: center; margin-top: 4px;">
  453.                                 <input type="range" id="slider-loops" min="1" max="20" value="1" style="flex: 1; margin:0;">
  454.                                 <input type="number" id="xai-api-loops" value="1" min="1" max="100" style="width: 50px; height: 26px; padding: 2px 4px; text-align: center; border-radius: 4px; border: 1px solid #334155; background: #1e293b; color: #f8fafc;">
  455.                             </div>
  456.                         </div>
  457.                     </div>
  458.                 </div>
  459.  
  460.                 <div class="panel" style="flex: 1; min-height: 0;">
  461.                     <div class="panel-title" style="display:flex; justify-content: space-between; align-items: center;">
  462.                         <span>Previous Results</span>
  463.                         <span id="xai-reset-btn" style="cursor: pointer; color: #ef4444; text-transform: none; text-decoration: underline;">Wipe Cache</span>
  464.                     </div>
  465.                     <div id="xai-history" style="flex: 1; overflow-y: auto; padding: 10px;">
  466.                         <div style="color: #94a3b8; font-size: 11px; text-align: center; margin-top: 20px;">No history yet.</div>
  467.                     </div>
  468.                 </div>
  469.             </div>
  470.  
  471.             <!-- CENTER COLUMN -->
  472.             <div class="col-center">
  473.                 <div class="panel" style="flex: 1; background: transparent; border: none; box-shadow: none; min-height: 0;">
  474.                     <div class="panel-title" style="background: #1e293b; border-radius: 8px; border: 1px solid #334155; margin-bottom: 10px; flex-shrink: 0;">Current Generation</div>
  475.                     <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>
  476.                 </div>
  477.  
  478.                 <div class="panel" style="flex-shrink: 0; padding: 12px;">
  479.                     <label style="font-size: 13px; color: #e2e8f0; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
  480.                         <span style="display: flex; align-items: center; gap: 8px;">
  481.                             <span>Prompt</span>
  482.                             <button id="fav-prompts-btn" class="btn-secondary" style="padding: 2px 8px; font-size: 10px; height: 22px;">⭐ Favorites</button>
  483.                         </span>
  484.                         <span style="font-size: 10px; font-weight: 400; color: #94a3b8;">(Drop image here for EXIF)</span>
  485.                     </label>
  486.                     <div id="warnings-container" style="display: flex; flex-direction: column; gap: 0px;"></div>
  487.                     <div class="prompt-container">
  488.                         <div id="prompt-backdrop"></div>
  489.                         <textarea id="xai-api-prompt" placeholder="Describe what you want to see... Supports Spintax {cat|dog} and @randomseed"></textarea>
  490.                     </div>
  491.                     <div style="display: flex; align-items: center; justify-content: space-between;">
  492.                         <div id="xai-api-status" style="font-size: 12px; color: #64748b; font-weight: 500;">Ready</div>
  493.                         <div style="display: flex; gap: 8px;">
  494.                             <button id="xai-preview-btn" class="btn-secondary">🔍 Payload</button>
  495.                             <button id="xai-cancel-btn" class="btn-secondary" style="display: none; color: #ef4444; border-color: #ef4444;">🛑 Cancel</button>
  496.                             <button id="xai-api-generate" class="btn-primary" style="width: 120px;"><div class="btn-content">Generate</div></button>
  497.                         </div>
  498.                     </div>
  499.                 </div>
  500.             </div>
  501.  
  502.             <!-- RIGHT COLUMN -->
  503.             <div class="col-right" id="col-right-dropzone">
  504.                 <div class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
  505.                     <div class="panel-title" id="ref-panel-title">Reference Media</div>
  506.                     <div style="padding: 10px; flex: 1; display: flex; flex-direction: column; overflow: hidden;">
  507.                         <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);">
  508.                             <div style="font-size: 20px; margin-bottom: 4px;">📥</div>
  509.                             <div style="font-size: 12px; font-weight: 600;">Drag & Drop / Ctrl+V</div>
  510.                         </div>
  511.                         <input type="file" id="xai-api-file" accept="image/*, video/mp4, video/webm" multiple style="display: none;">
  512.                         <div style="font-size: 10px; color: #94a3b8; margin-bottom: 4px; text-transform: uppercase; font-weight: bold; flex-shrink: 0;">Upload Order (Top = First)</div>
  513.                         <div id="xai-ref-list" style="flex: 1; overflow-y: auto; padding-right: 4px;"></div>
  514.                     </div>
  515.                 </div>
  516.             </div>
  517.  
  518.             <div id="ar-options-container"></div>
  519.  
  520.             <!-- MODALS -->
  521.             <div id="xai-lightbox" class="modal-overlay">
  522.                 <div id="xai-lightbox-wrapper">
  523.                     <img id="xai-lightbox-img" src="">
  524.                     <a id="xai-lightbox-dl" href="#" download="" target="_blank" class="overlay-btn overlay-dl-btn" style="top: 15px; right: 15px; width: 44px; height: 44px; border-radius: 50%; background: rgba(0,0,0,0.7);" title="Download File">${DOWNLOAD_ICON}</a>
  525.                 </div>
  526.             </div>
  527.  
  528.             <div id="tag-preview-box" style="position: fixed; display: none; z-index: 99999999; background: #1e293b; border: 1px solid #334155; border-radius: 6px; padding: 4px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); pointer-events: none;">
  529.                 <img id="tag-preview-img" style="max-width: 150px; max-height: 150px; border-radius: 4px; display: block; object-fit: cover;">
  530.             </div>
  531.  
  532.             <!-- LOGS MODAL -->
  533.             <div id="xai-logs-modal" class="modal-overlay">
  534.                 <div class="modal-box" style="width: 800px; max-width: 95vw; height: 80vh;">
  535.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  536.                         <h3 style="margin:0; font-size: 15px; color: #f8fafc;">🐛 Debug Logs</h3>
  537.                         <button id="close-logs-btn" style="background: #ef4444; color: #fff; border: none; border-radius: 6px; padding: 4px 8px; cursor: pointer; font-weight: bold; font-size: 11px;">Close</button>
  538.                     </div>
  539.                     <textarea id="logs-textarea" readonly style="flex: 1; width: 100%; background: #0f172a; color: #e2e8f0; font-family: monospace; font-size: 11px; border: 1px solid #334155; border-radius: 6px; padding: 10px; resize: none; white-space: pre;"></textarea>
  540.                     <div style="display: flex; gap: 8px;">
  541.                         <button id="copy-logs-btn" class="btn-primary" style="flex: 1;">📋 Copy Logs to Clipboard</button>
  542.                         <button id="clear-logs-btn" class="btn-secondary" style="flex: 1; color: #ef4444; border-color: #ef4444;">🗑️ Clear Logs</button>
  543.                     </div>
  544.                 </div>
  545.             </div>
  546.  
  547.             <!-- SETTINGS MODAL -->
  548.             <div id="xai-settings-modal" class="modal-overlay">
  549.                 <div class="modal-box" style="width: 500px;">
  550.                     <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⚙️ Studio Settings</h3>
  551.                     <div style="display:flex; gap:10px;">
  552.                         <div style="flex:1;"><label>Max Retries</label><input type="number" id="set-retries" min="1" max="100"></div>
  553.                         <div style="flex:1;"><label>Delay Min (ms)</label><input type="number" id="set-delay-min" min="500" step="500"></div>
  554.                         <div style="flex:1;"><label>Delay Max (ms)</label><input type="number" id="set-delay-max" min="1000" step="500"></div>
  555.                     </div>
  556.                     <div><label>API Base URL (Leave empty for default console.x.ai)</label><input type="text" id="set-api-base-url" placeholder="e.g., https://api.proxy.com"></div>
  557.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-notifications" style="width: 16px; height: 16px;"><label for="set-notifications" style="margin: 0; cursor: pointer;">Enable Notifications (Sound & Tab Blink)</label></div>
  558.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-save-png" style="width: 16px; height: 16px;"><label for="set-save-png" style="margin: 0; cursor: pointer;">Save as Original PNG (Disable JPEG / EXIF Prompt)</label></div>
  559.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-auto-retry-video" style="width: 16px; height: 16px;"><label for="set-auto-retry-video" style="margin: 0; cursor: pointer;">Auto-Retry Stuck Videos (Timeout / Moderated)</label></div>
  560.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-break-loop-on-failure" style="width: 16px; height: 16px;"><label for="set-break-loop-on-failure" style="margin: 0; cursor: pointer;">Break loops if one iteration fails entirely.</label></div>
  561.                     <div style="display:flex; gap:10px; margin-top: 4px;">
  562.                         <div style="flex:1;"><label>Video Poll Timeout (s)</label><input type="number" id="set-video-timeout" min="10" step="10"></div>
  563.                         <div style="flex:1;"><label title="When 'Rate limit exceeded' occurs">Rate Limit Delay (s)</label><input type="number" id="set-rate-limit-delay" min="1" step="1"></div>
  564.                         <div style="flex:1;"><label>Base Font Size (px)</label><input type="number" id="set-font-size" min="10" max="24"></div>
  565.                     </div>
  566.                     <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;"></div>
  567.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-suppress-warning" style="width: 16px; height: 16px;"><label for="set-suppress-warning" style="margin: 0; cursor: pointer; color: #fcd34d;">Suppress yellow ">8s video edit" warning</label></div>
  568.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-video-autoplay" style="width: 16px; height: 16px;"><label for="set-video-autoplay" style="margin: 0; cursor: pointer;">Autoplay generated videos in gallery</label></div>
  569.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-video-muted" style="width: 16px; height: 16px;"><label for="set-video-muted" style="margin: 0; cursor: pointer;">Start generated videos muted</label></div>
  570.                     <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;">
  571.                         <label>Custom CSS Overrides</label>
  572.                         <textarea id="set-custom-css" style="font-family: monospace; height: 60px; font-size: 11px;" placeholder="/* e.g., #xai-pro-app { background: red; } */"></textarea>
  573.                     </div>
  574.                     <div style="display: flex; gap: 8px; margin-top: 5px; border-top: 1px solid #334155; padding-top: 10px;">
  575.                         <button id="export-data-btn" class="btn-secondary" style="flex:1;">📤 Export Data</button>
  576.                         <button id="import-data-btn" class="btn-secondary" style="flex:1;">📥 Import Data</button>
  577.                         <input type="file" id="import-data-file" accept=".json" style="display: none;">
  578.                     </div>
  579.                     <div style="display: flex; gap: 8px; margin-top: 5px;">
  580.                         <button id="save-settings-btn" class="btn-primary" style="flex:1;">Save Settings</button>
  581.                         <button id="close-settings-btn" class="btn-secondary" style="flex:1;">Cancel</button>
  582.                     </div>
  583.                 </div>
  584.             </div>
  585.  
  586.             <!-- FAVORITES MODAL -->
  587.             <div id="xai-fav-modal" class="modal-overlay">
  588.                 <div class="modal-box" style="width: 550px;">
  589.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  590.                         <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⭐ Favorite Prompts</h3>
  591.                         <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>
  592.                     </div>
  593.                     <button id="add-current-fav-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);">➕ Save Current Prompt to Favorites</button>
  594.                     <div id="fav-list" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px;"></div>
  595.                 </div>
  596.             </div>
  597.  
  598.             <!-- PAYLOAD MODAL -->
  599.             <div id="xai-payload-modal" class="modal-overlay">
  600.                 <div class="modal-box" style="width: 550px;">
  601.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  602.                         <h3 style="margin:0; font-size: 15px; color: #f8fafc;">API Payload Debugger</h3>
  603.                         <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>
  604.                     </div>
  605.                     <div><label>Endpoint URL:</label><input type="text" id="payload-endpoint" style="font-family: monospace;" value="/v1/images/generations"></div>
  606.                     <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>
  607.                     <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>
  608.                     <div id="custom-payload-status" style="font-size: 11px; color: #64748b; text-align: center;">Ready</div>
  609.                 </div>
  610.             </div>
  611.         </div>
  612.     `;
  613.  
  614.     // ─── INITIALIZATION ───────────────────────────────────────────────────────
  615.     let updateUIForEditMedia = null;
  616.     let activeDurationMap = MAPS.durGen;
  617.  
  618.     const initApp = () => {
  619.         if (!document.body) return setTimeout(initApp, 50);
  620.         const hideNode = (node) => {
  621.             if (node.nodeType === 1 && node.id !== 'xai-pro-app' && !['SCRIPT', 'STYLE', 'LINK'].includes(node.tagName)) {
  622.                 node.style.display = 'none';
  623.             }
  624.         };
  625.         Array.from(document.body.children).forEach(hideNode);
  626.         new MutationObserver((mutations) => {
  627.             mutations.forEach(m => m.addedNodes.forEach(hideNode));
  628.         }).observe(document.body, { childList: true });
  629.  
  630.         if (!document.getElementById('xai-pro-app')) {
  631.             const style = document.createElement('style'); style.innerHTML = UI_CSS; document.head.appendChild(style);
  632.             const customStyle = document.createElement('style'); customStyle.id = 'xai-custom-css-block'; customStyle.innerHTML = appSettings.customCSS; document.head.appendChild(customStyle);
  633.             document.body.insertAdjacentHTML('beforeend', UI_HTML);
  634.             updateFontSize(appSettings.uiFontSize);
  635.             bindLogic();
  636.         }
  637.     };
  638.  
  639.     let referenceMedia =[];
  640.     let currentAr = localStorage.getItem('xai_api_ar') || 'Auto';
  641.     let fullPayloadMemory = {};
  642.     let currentAbortController = null;
  643.     let isRequestCancelled = false;
  644.  
  645.     function saveRefs() {
  646.         try { localStorage.setItem('xai_api_refs', JSON.stringify(referenceMedia)); } catch(e) {}
  647.     }
  648.  
  649.     function findMapIndex(arr, val) {
  650.         let idx = arr.findIndex(item => (item.v || item).toString() === val.toString());
  651.         return idx !== -1 ? idx : 0;
  652.     }
  653.  
  654.     function drawTicks(containerId, map, colorFn) {
  655.         const cont = document.getElementById(containerId);
  656.         if (!cont) return;
  657.         cont.innerHTML = map.map((item, index) => {
  658.             let val = item.v || item; let label = item.t || val;
  659.             let color = colorFn ? colorFn(val) : '#64748b';
  660.  
  661.             // Calculate exact position to match the center of the 16px slider thumb
  662.             let percent = map.length > 1 ? (index / (map.length - 1)) * 100 : 50;
  663.             let offset = 8 - (percent / 100) * 16;
  664.  
  665.             return `<span style="color:${color}; left:calc(${percent}% + ${offset}px);">${label}</span>`;
  666.         }).join('');
  667.     }
  668.  
  669.     function getDurationColor(val) {
  670.         const v = parseInt(val);
  671.         if (v <= 8) return '#f8fafc'; // White
  672.         if (v <= 10) return '#94a3b8'; // Grey
  673.         return '#ef4444'; // Red
  674.     }
  675.  
  676.     function syncSlider(sliderEl, textEl, mapArr, formatFn) {
  677.         const val = mapArr[sliderEl.value];
  678.         textEl.innerText = formatFn ? formatFn(val) : (val.l || val);
  679.     }
  680.  
  681.     function bindLogic() {
  682.         const els = {
  683.             app: document.getElementById('xai-pro-app'),
  684.             prompt: document.getElementById('xai-api-prompt'), promptBackdrop: document.getElementById('prompt-backdrop'), warningsContainer: document.getElementById('warnings-container'), promptContainer: document.querySelector('.prompt-container'),
  685.             action: document.getElementById('master-action'),
  686.             highResBtn: document.getElementById('high-res-btn'),
  687.             n: document.getElementById('xai-api-n'), duration: document.getElementById('xai-api-duration'),
  688.             loopsSlider: document.getElementById('slider-loops'), loopsNum: document.getElementById('xai-api-loops'),
  689.  
  690.             settingAr: document.getElementById('setting-ar'), settingHighRes: document.getElementById('setting-high-res'), settingBatch: document.getElementById('setting-batch'), settingDuration: document.getElementById('setting-duration'),
  691.  
  692.             fileInput: document.getElementById('xai-api-file'), dropzone: document.getElementById('col-right-dropzone'), uploadPlaceholder: document.getElementById('xai-upload-placeholder'), refList: document.getElementById('xai-ref-list'), refTitle: document.getElementById('ref-panel-title'),
  693.  
  694.             btn: document.getElementById('xai-api-generate'), previewBtn: document.getElementById('xai-preview-btn'), cancelBtn: document.getElementById('xai-cancel-btn'), status: document.getElementById('xai-api-status'), history: document.getElementById('xai-history'), currentImages: document.getElementById('xai-current-images'), reset: document.getElementById('xai-reset-btn'),
  695.  
  696.             arSelectBox: document.getElementById('ar-select-box'), arOptionsCont: document.getElementById('ar-options-container'), arSelectedIcon: document.getElementById('ar-selected-icon'), arSelectedText: document.getElementById('ar-selected-text'),
  697.  
  698.             lightbox: document.getElementById('xai-lightbox'), lightboxImg: document.getElementById('xai-lightbox-img'), lightboxDl: document.getElementById('xai-lightbox-dl'),
  699.             previewBox: document.getElementById('tag-preview-box'), previewImg: document.getElementById('tag-preview-img'),
  700.             payloadModal: document.getElementById('xai-payload-modal'), payloadEndpoint: document.getElementById('payload-endpoint'), payloadCode: document.getElementById('payload-code'), closePayloadBtn: document.getElementById('close-payload-btn'), sendCustomBtn: document.getElementById('send-custom-payload-btn'), customStatus: document.getElementById('custom-payload-status'),
  701.             settingsBtn: document.getElementById('settings-btn'), settingsModal: document.getElementById('xai-settings-modal'), closeSettingsBtn: document.getElementById('close-settings-btn'), saveSettingsBtn: document.getElementById('save-settings-btn'), exportDataBtn: document.getElementById('export-data-btn'), importDataBtn: document.getElementById('import-data-btn'), importDataFile: document.getElementById('import-data-file'),
  702.             favBtn: document.getElementById('fav-prompts-btn'), favModal: document.getElementById('xai-fav-modal'), closeFavBtn: document.getElementById('close-fav-btn'), addFavBtn: document.getElementById('add-current-fav-btn'), favList: document.getElementById('fav-list'),
  703.             logsBtn: document.getElementById('logs-btn'), logsModal: document.getElementById('xai-logs-modal'), closeLogsBtn: document.getElementById('close-logs-btn'), copyLogsBtn: document.getElementById('copy-logs-btn'), clearLogsBtn: document.getElementById('clear-logs-btn'), logsTextarea: document.getElementById('logs-textarea')
  704.         };
  705.  
  706.         // Draw initial Ticks for Sliders
  707.         drawTicks('ticks-batch', MAPS.batch);
  708.  
  709.         let isHighRes = true;
  710.  
  711.         // Settings Sync
  712.         const updateGenSettingsMemory = () => {
  713.             localStorage.setItem('xai_api_gen_settings', JSON.stringify({
  714.                 action: els.action.value, isHighRes: isHighRes,
  715.                 n: MAPS.batch[els.n.value], duration: activeDurationMap[els.duration.value], loops: els.loopsNum.value
  716.             }));
  717.         };
  718.  
  719.         els.highResBtn.addEventListener('click', () => {
  720.             isHighRes = !isHighRes;
  721.             els.highResBtn.className = isHighRes ? 'toggle-btn active' : 'toggle-btn';
  722.             els.highResBtn.innerText = isHighRes ? 'ON (2K / 720p)' : 'OFF (1K / 480p)';
  723.             updateGenSettingsMemory();
  724.         });
  725.         els.n.addEventListener('input', () => { syncSlider(els.n, document.getElementById('val-batch'), MAPS.batch, v => v + (v===1?' Image':' Images')); updateGenSettingsMemory(); });
  726.         els.duration.addEventListener('input', () => { syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds'); updateGenSettingsMemory(); updateWarnings(); });
  727.  
  728.         els.loopsSlider.addEventListener('input', e => { els.loopsNum.value = e.target.value; updateGenSettingsMemory(); });
  729.         els.loopsNum.addEventListener('input', e => { let v = parseInt(e.target.value) || 1; els.loopsSlider.value = Math.min(v, 20); updateGenSettingsMemory(); });
  730.  
  731.         els.logsBtn.addEventListener('click', () => { els.logsTextarea.value = formatLogsForExport(); els.logsModal.style.display = 'flex'; els.logsTextarea.scrollTop = els.logsTextarea.scrollHeight; });
  732.         els.closeLogsBtn.addEventListener('click', () => els.logsModal.style.display = 'none');
  733.         els.copyLogsBtn.addEventListener('click', () => { els.logsTextarea.select(); document.execCommand('copy'); alert('Logs copied to clipboard!'); });
  734.         els.clearLogsBtn.addEventListener('click', () => { if (confirm("Clear all logs?")) { appLogs.length = 0; els.logsTextarea.value = ''; } });
  735.  
  736.         function updateWarnings() {
  737.             els.warningsContainer.innerHTML = ''; let html = '';
  738.             if (/--[a-zA-Z0-9_-]+=/.test(els.prompt.value)) html += `<div class="warning-box warning-red">⚠️ A gentle reminder that --parameter=value has never been shown to do anything at all, including --seed and --sid, but you do you!</div>`;
  739.             const action = els.action.value; const duration = activeDurationMap[els.duration.value] || 0; const activeRefs = referenceMedia.filter(m => m.active).length;
  740.             if (action === 'gen_video') {
  741.                 if (activeRefs > 0 && duration > 10) html += `<div class="warning-box warning-red">⚠️ Grok seems to always refuse to generate videos by reference with length above 10s. Without references it works fine.</div>`;
  742.                 if (duration > 8 && !appSettings.suppressEditWarning) html += `<div class="warning-box warning-yellow">⚠️ Note: edit won't work on videos longer than 8s like the one you are about to generate. You can suppress this warning in options.</div>`;
  743.            }
  744.            els.warningsContainer.innerHTML = html;
  745.        }
  746.  
  747.        function syncPromptBackdrop() {
  748.            const val = els.prompt.value; updateWarnings();
  749.            let html = val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  750.            const activeRefs = referenceMedia.filter(m => m.active);
  751.            html = html.replace(/&lt;IMAGE_(\d+)&gt;/g, (match, idxStr) => { const idx = parseInt(idxStr); return activeRefs[idx] ? `<span class="prompt-tag" data-idx="${idx}">${match}</span>` : match; });
  752.            els.promptBackdrop.innerHTML = html.replace(/\n/g, '<br>') + '<br>';
  753.            els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft;
  754.        }
  755.  
  756.        function setPromptVal(val) { els.prompt.value = val; localStorage.setItem('xai_api_prompt', val); syncPromptBackdrop(); }
  757.        if (localStorage.getItem('xai_api_prompt')) setPromptVal(localStorage.getItem('xai_api_prompt'));
  758.        els.prompt.addEventListener('input', () => setPromptVal(els.prompt.value));
  759.        els.prompt.addEventListener('scroll', () => { els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft; });
  760.  
  761.        let hidePreviewTimeout;
  762.        /*els.prompt.addEventListener('mousemove', (e) => {
  763.            if (e.buttons !== 0) { els.previewBox.style.display = 'none'; return; }
  764.            els.prompt.style.pointerEvents = 'none'; const el = document.elementFromPoint(e.clientX, e.clientY); els.prompt.style.pointerEvents = 'auto';
  765.            if (el && el.classList.contains('prompt-tag')) {
  766.                const idx = el.getAttribute('data-idx'); const media = referenceMedia.filter(m => m.active)[parseInt(idx)];
  767.                if (media) {
  768.                    els.previewBox.style.display = 'block'; els.previewImg.src = media.thumb || media.base64;
  769.                    let tx = e.clientX + 15; let ty = e.clientY + 15;
  770.                    if (tx + 160 > window.innerWidth) tx = e.clientX - 165; if (ty + 160 > window.innerHeight) ty = e.clientY - 165;
  771.                    els.previewBox.style.left = tx + 'px'; els.previewBox.style.top = ty + 'px';
  772.                    clearTimeout(hidePreviewTimeout);
  773.                }
  774.            } else hidePreviewTimeout = setTimeout(() => els.previewBox.style.display = 'none', 50);
  775.        });*/
  776.        els.prompt.addEventListener('mouseleave', () => els.previewBox.style.display = 'none');
  777.  
  778.        try { const storedRefs = JSON.parse(localStorage.getItem('xai_api_refs')); if (Array.isArray(storedRefs)) referenceMedia = storedRefs; } catch(e) {}
  779.  
  780.        els.settingsBtn.addEventListener('click', () => {
  781.            document.getElementById('set-retries').value = appSettings.retries; document.getElementById('set-delay-min').value = appSettings.delayMin; document.getElementById('set-delay-max').value = appSettings.delayMax; document.getElementById('set-rate-limit-delay').value = appSettings.rateLimitDelay; document.getElementById('set-notifications').checked = appSettings.notifications; document.getElementById('set-save-png').checked = appSettings.saveAsPng; document.getElementById('set-auto-retry-video').checked = appSettings.autoRetryStuckVideo; document.getElementById('set-break-loop-on-failure').checked = appSettings.breakLoopOnFailure; document.getElementById('set-video-timeout').value = appSettings.videoPollTimeout; document.getElementById('set-suppress-warning').checked = appSettings.suppressEditWarning; document.getElementById('set-video-autoplay').checked = appSettings.videoAutoplay; document.getElementById('set-video-muted').checked = appSettings.videoMuted; document.getElementById('set-api-base-url').value = appSettings.apiBaseUrl || ''; document.getElementById('set-custom-css').value = appSettings.customCSS || ''; document.getElementById('set-font-size').value = appSettings.uiFontSize;
  782.            els.settingsModal.style.display = 'flex';
  783.        });
  784.        els.saveSettingsBtn.addEventListener('click', () => {
  785.            appSettings.retries = parseInt(document.getElementById('set-retries').value) || 20; appSettings.delayMin = parseInt(document.getElementById('set-delay-min').value) || 2000; appSettings.delayMax = Math.max(appSettings.delayMin, parseInt(document.getElementById('set-delay-max').value) || 4000); appSettings.rateLimitDelay = parseInt(document.getElementById('set-rate-limit-delay').value) || 60; appSettings.notifications = document.getElementById('set-notifications').checked; appSettings.saveAsPng = document.getElementById('set-save-png').checked; appSettings.autoRetryStuckVideo = document.getElementById('set-auto-retry-video').checked; appSettings.breakLoopOnFailure = document.getElementById('set-break-loop-on-failure').checked; appSettings.videoPollTimeout = parseInt(document.getElementById('set-video-timeout').value) || 300; appSettings.suppressEditWarning = document.getElementById('set-suppress-warning').checked; appSettings.videoAutoplay = document.getElementById('set-video-autoplay').checked; appSettings.videoMuted = document.getElementById('set-video-muted').checked; appSettings.apiBaseUrl = document.getElementById('set-api-base-url').value.trim(); appSettings.customCSS = document.getElementById('set-custom-css').value; appSettings.uiFontSize = parseInt(document.getElementById('set-font-size').value) || 13;
  786.            localStorage.setItem('xai_api_settings', JSON.stringify(appSettings)); document.getElementById('xai-custom-css-block').innerHTML = appSettings.customCSS; updateFontSize(appSettings.uiFontSize); updateWarnings(); els.settingsModal.style.display = 'none';
  787.        });
  788.        els.closeSettingsBtn.addEventListener('click', () => els.settingsModal.style.display = 'none');
  789.  
  790.        els.exportDataBtn.addEventListener('click', () => {
  791.            const blob = new Blob([JSON.stringify({settings: appSettings, refs: referenceMedia}, null, 2)], { type: 'application/json' });
  792.            const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `xAI_Pro_Studio_Backup_${makeTimestamp()}.json`; a.click(); URL.revokeObjectURL(url);
  793.        });
  794.        els.importDataBtn.addEventListener('click', () => els.importDataFile.click());
  795.        els.importDataFile.addEventListener('change', (e) => {
  796.            const file = e.target.files[0]; if (!file) return; const reader = new FileReader();
  797.            reader.onload = (evt) => {
  798.                try {
  799.                    const parsed = JSON.parse(evt.target.result);
  800.                    if (parsed.settings) { appSettings = { ...appSettings, ...parsed.settings }; localStorage.setItem('xai_api_settings', JSON.stringify(appSettings)); }
  801.                    if (parsed.refs && Array.isArray(parsed.refs)) { referenceMedia = parsed.refs; saveRefs(); }
  802.                    alert("Import successful! Page will reload."); location.reload();
  803.                } catch(err) { alert("Failed to parse the JSON file."); }
  804.            }; reader.readAsText(file); e.target.value = '';
  805.        });
  806.  
  807.        function renderFavList() {
  808.            els.favList.innerHTML = '';
  809.            if (favoritePrompts.length === 0) { els.favList.innerHTML = '<div style="color: #64748b; font-size: 12px; text-align: center; margin-top: 15px;">No favorite prompts yet.</div>'; return; }
  810.            favoritePrompts.forEach((promptText, idx) => {
  811.                const div = document.createElement('div'); div.className = 'fav-item'; div.innerHTML = `<div class="fav-text" title="${promptText.replace(/"/g, '&quot;')}">${promptText}</div><button class="btn-secondary" style="padding: 2px 6px; font-size: 10px; border-color: #ef4444; color: #ef4444;">Del</button>`;
  812.                div.querySelector('.fav-text').addEventListener('click', () => { setPromptVal(promptText); els.favModal.style.display = 'none'; });
  813.                div.querySelector('button').addEventListener('click', () => { favoritePrompts.splice(idx, 1); localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts)); renderFavList(); });
  814.                els.favList.appendChild(div);
  815.            });
  816.        }
  817.        els.favBtn.addEventListener('click', () => { renderFavList(); els.favModal.style.display = 'flex'; });
  818.        els.closeFavBtn.addEventListener('click', () => els.favModal.style.display = 'none');
  819.        els.addFavBtn.addEventListener('click', () => {
  820.            const p = els.prompt.value.trim(); if (!p) return alert("Prompt is empty!"); if (favoritePrompts.includes(p)) return alert("Already in favorites!");
  821.            favoritePrompts.unshift(p); localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts)); renderFavList();
  822.        });
  823.  
  824.        els.prompt.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.add('prompt-drag-over'); });
  825.        els.prompt.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over'); });
  826.        els.prompt.addEventListener('drop', async (e) => {
  827.            e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over');
  828.            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  829.                const file = e.dataTransfer.files[0]; const oldVal = els.prompt.value; setPromptVal("Extracting prompt from EXIF...");
  830.                const extractedPrompt = await extractPromptFromImage(file);
  831.                if (extractedPrompt) setPromptVal(extractedPrompt); else { setPromptVal(oldVal); alert("No prompt found in this image's EXIF data."); }
  832.            }
  833.        });
  834.  
  835.        function getMaxMedia() { const val = els.action.value; return val === 'gen_image' ? 5 : (val === 'gen_video' ? 7 : 1); }
  836.  
  837.        function updateActionUI() {
  838.            const val = els.action.value;
  839.  
  840.            if (val === 'gen_image') {
  841.                els.settingAr.style.display = 'flex'; els.settingHighRes.style.display = 'flex'; els.settingBatch.style.display = 'flex'; els.settingDuration.style.display = 'none';
  842.            } else if (val === 'gen_video') {
  843.                els.settingAr.style.display = 'flex'; els.settingHighRes.style.display = 'flex'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'flex';
  844.                activeDurationMap = MAPS.durGen; els.duration.max = activeDurationMap.length - 1;
  845.                drawTicks('ticks-duration', activeDurationMap, getDurationColor);
  846.                syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  847.            } else if (val === 'edit_video') {
  848.                els.settingAr.style.display = 'none'; els.settingHighRes.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'none';
  849.            } else if (val === 'extend_video') {
  850.                els.settingAr.style.display = 'none'; els.settingHighRes.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'flex';
  851.                activeDurationMap = MAPS.durExt; els.duration.max = activeDurationMap.length - 1;
  852.                drawTicks('ticks-duration', activeDurationMap, getDurationColor);
  853.                syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  854.            }
  855.  
  856.            const max = getMaxMedia(); els.refTitle.innerText = `Reference Media (Max Active: ${max})`;
  857.            let activeCount = 0;
  858.            referenceMedia.forEach(m => {
  859.                let valid = true;
  860.                if ((val === 'gen_image' || val === 'gen_video') && m.isVideo) valid = false;
  861.                if ((val === 'edit_video' || val === 'extend_video') && !m.isVideo) valid = false;
  862.                if (!valid) m.active = false; else if (m.active) { activeCount++; if (activeCount > max) m.active = false; }
  863.            });
  864.            renderRefList(); updateWarnings();
  865.        }
  866.  
  867.        els.action.addEventListener('change', () => { updateActionUI(); updateGenSettingsMemory(); });
  868.  
  869.        // Load specific saved settings
  870.        try {
  871.            const storedGen = JSON.parse(localStorage.getItem('xai_api_gen_settings') || '{}');
  872.            if (storedGen.action) els.action.value = storedGen.action;
  873.            updateActionUI();
  874.  
  875.            if (typeof storedGen.isHighRes !== 'undefined') isHighRes = storedGen.isHighRes;
  876.            else if (storedGen.resImg === '1k' || storedGen.resVid === '480p') isHighRes = false;
  877.  
  878.            els.highResBtn.className = isHighRes ? 'toggle-btn active' : 'toggle-btn';
  879.            els.highResBtn.innerText = isHighRes ? 'ON (2K / 720p)' : 'OFF (1K / 480p)';
  880.  
  881.            if (storedGen.n) els.n.value = findMapIndex(MAPS.batch, storedGen.n);
  882.  
  883.            if (storedGen.duration) {
  884.                let idx = activeDurationMap.indexOf(parseInt(storedGen.duration));
  885.                els.duration.value = idx !== -1 ? idx : 0;
  886.            }
  887.            if (storedGen.loops) {
  888.                els.loopsNum.value = storedGen.loops;
  889.                els.loopsSlider.value = Math.min(storedGen.loops, 20);
  890.            }
  891.  
  892.            // Sync visual labels with loaded data
  893.            syncSlider(els.n, document.getElementById('val-batch'), MAPS.batch, v => v + (v===1?' Image':' Images'));
  894.            syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  895.        } catch(e) {}
  896.  
  897.        updateUIForEditMedia = (mediaUrl, isVideo, fileName) => {
  898.            referenceMedia.forEach(m => m.active = false);
  899.            referenceMedia.unshift({ id: Date.now() + Math.random(), base64: mediaUrl, isVideo: isVideo, active: true, thumb: isVideo ? null : mediaUrl, fileName: fileName || (isVideo ? 'Edited_Video.mp4' : 'Edited_Image.png'), w:0, h:0 });
  900.            els.action.value = isVideo ? 'edit_video' : 'gen_image';
  901.            updateActionUI(); updateGenSettingsMemory(); renderRefList(); saveRefs();
  902.        };
  903.  
  904.        function getMediaDimensions(base64, isVideo) {
  905.            return new Promise(resolve => {
  906.                if (isVideo) {
  907.                    const vid = document.createElement('video');
  908.                    vid.onloadedmetadata = () => resolve({w: vid.videoWidth, h: vid.videoHeight});
  909.                    vid.onerror = () => resolve({w: 0, h: 0});
  910.                    vid.src = base64;
  911.                } else {
  912.                    const img = new Image();
  913.                    img.onload = () => resolve({w: img.width, h: img.height});
  914.                    img.onerror = () => resolve({w: 0, h: 0});
  915.                    img.src = base64;
  916.                }
  917.            });
  918.        }
  919.  
  920.        async function buildPayloadData(dynamicPromptText) {
  921.            const action = els.action.value; const payload = { model: action === 'gen_image' ? "grok-imagine-image" : "grok-imagine-video", prompt: dynamicPromptText };
  922.            let ar = currentAr.toLowerCase(); const activeRefs = referenceMedia.filter(m => m.active);
  923.  
  924.            // Adaptive Aspect Ratio logic
  925.            if (currentAr === 'By First Ref') {
  926.                if (activeRefs.length > 0) {
  927.                    let ref = activeRefs[0];
  928.                    if (!ref.w || !ref.h) {
  929.                        const dims = await getMediaDimensions(ref.base64, ref.isVideo);
  930.                        ref.w = dims.w; ref.h = dims.h;
  931.                        saveRefs(); // Update cache so we don't have to calculate next time
  932.                    }
  933.  
  934.                    if (ref.w && ref.h) {
  935.                        const targetRatio = ref.w / ref.h;
  936.                        let bestMatch = '1:1'; let minDiff = Infinity;
  937.                        arData.forEach(a => {
  938.                            if (a.isAuto || a.isRef) return;
  939.                            const r = a.w / a.h; const diff = Math.abs(r - targetRatio);
  940.                            if (diff < minDiff) { minDiff = diff; bestMatch = a.label; }
  941.                        });
  942.                        ar = bestMatch.toLowerCase();
  943.                        addLog('INFO', 'Calculated AR by First Ref', { targetRatio, selectedAr: ar });
  944.                    } else ar = 'auto'; // Fallback if format is utterly broken
  945.                } else ar = 'auto'; // Fallback if no reference is uploaded
  946.            }
  947.  
  948.            if (action === 'gen_image') {
  949.                payload.n = MAPS.batch[els.n.value]; payload.resolution = isHighRes ? "2k" : "1k"; payload.response_format = "b64_json";
  950.                if (ar !== 'auto') payload.aspect_ratio = ar; else if (activeRefs.length > 0) payload.aspect_ratio = 'auto';
  951.                if (activeRefs.length > 0) {
  952.                    if (activeRefs.length === 1) payload.image = { url: activeRefs[0].base64 };
  953.                    else payload.images = activeRefs.map(m => ({ type: "image_url", url: m.base64 }));
  954.                }
  955.            } else if (action === 'gen_video') {
  956.                payload.duration = activeDurationMap[els.duration.value]; payload.resolution = isHighRes ? "720p" : "480p";
  957.                if (ar !== 'auto') payload.aspect_ratio = ar;
  958.                if (activeRefs.length > 0) payload.reference_images = activeRefs.map(m => ({ url: m.base64 }));
  959.            } else if (action === 'edit_video') {
  960.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  961.            } else if (action === 'extend_video') {
  962.                payload.duration = activeDurationMap[els.duration.value];
  963.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  964.            }
  965.            return payload;
  966.        }
  967.  
  968.        els.previewBtn.addEventListener('click', async () => {
  969.            els.previewBtn.disabled = true;
  970.            els.previewBtn.innerHTML = `<div class="loading-spinner" style="border-top-color:#64748b; width:12px; height:12px;"></div>`;
  971.  
  972.            fullPayloadMemory = await buildPayloadData(parseDynamicPrompt(els.prompt.value.trim()));
  973.  
  974.            const displayP = JSON.parse(JSON.stringify(fullPayloadMemory)); const trunc = "[BASE64_TRUNCATED_FOR_PREVIEW]";
  975.            if (displayP.image) { if (Array.isArray(displayP.image)) displayP.image.forEach(img => img.url = trunc); else displayP.image.url = trunc; }
  976.            if (displayP.images && Array.isArray(displayP.images)) displayP.images.forEach(img => img.url = trunc);
  977.            if (displayP.reference_images && Array.isArray(displayP.reference_images)) displayP.reference_images.forEach(img => img.url = trunc);
  978.            if (displayP.video) displayP.video.url = trunc;
  979.            const activeRefs = referenceMedia.filter(m => m.active); let endpoint = '/v1/images/generations';
  980.            if (els.action.value === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  981.            else if (els.action.value === 'gen_video') endpoint = '/v1/videos/generations';
  982.            else if (els.action.value === 'edit_video') endpoint = '/v1/videos/edits';
  983.            else if (els.action.value === 'extend_video') endpoint = '/v1/videos/extensions';
  984.            els.payloadEndpoint.value = endpoint; els.payloadCode.value = JSON.stringify(displayP, null, 2); els.payloadModal.style.display = 'flex';
  985.  
  986.            els.previewBtn.innerHTML = `🔍 Payload`;
  987.            els.previewBtn.disabled = false;
  988.        });
  989.        els.closePayloadBtn.addEventListener('click', () => els.payloadModal.style.display = 'none');
  990.  
  991.        function injectBase64(editedObj, originalObj) {
  992.            if (!editedObj || typeof editedObj !== 'object') return;
  993.            for (let key in editedObj) {
  994.                if (typeof editedObj[key] === 'string' && editedObj[key] === '[BASE64_TRUNCATED_FOR_PREVIEW]') { if (originalObj && originalObj[key]) editedObj[key] = originalObj[key]; }
  995.                else if (typeof editedObj[key] === 'object') injectBase64(editedObj[key], originalObj ? originalObj[key] : null);
  996.            }
  997.        }
  998.  
  999.        els.sendCustomBtn.addEventListener('click', async () => {
  1000.            initAudio(); let customPayload; try { customPayload = JSON.parse(els.payloadCode.value); } catch(e) { return alert("Invalid JSON format in textarea!"); }
  1001.            injectBase64(customPayload, fullPayloadMemory);
  1002.            const endpoint = els.payloadEndpoint.value.trim(); const isImage = customPayload.model === "grok-imagine-image";
  1003.            stealthIdentityReset(); els.sendCustomBtn.disabled = true; els.sendCustomBtn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Processing...</div>`; isRequestCancelled = false;
  1004.            const ok = await executeGenerationSingle(endpoint, customPayload, isImage, els.customStatus, 1, 1);
  1005.            els.sendCustomBtn.disabled = false; els.sendCustomBtn.innerHTML = `<div class="btn-content">🚀 Send Custom Payload</div>`; if (ok) notifyUser(false); else notifyUser(true);
  1006.        });
  1007.  
  1008.        els.app.addEventListener('click', (e) => {
  1009.            if (e.target && e.target.classList.contains('zoomable') && e.target.tagName === 'IMG') {
  1010.                els.lightboxImg.src = e.target.src; els.lightboxDl.href = e.target.src; els.lightboxDl.download = e.target.dataset.filename || 'Reference_Image.jpg'; els.lightbox.style.display = 'flex';
  1011.            }
  1012.        });
  1013.        els.lightbox.addEventListener('click', (e) => { if (!e.target.closest('#xai-lightbox-dl') && !e.target.closest('.modal-box')) els.lightbox.style.display = 'none'; });
  1014.        document.addEventListener('keydown', (e) => { if(e.key === 'Escape') Array.from(document.querySelectorAll('.modal-overlay')).forEach(m => m.style.display = 'none'); });
  1015.  
  1016.        function renderArOptions() {
  1017.            els.arOptionsCont.innerHTML = '';
  1018.            arData.forEach(ar => {
  1019.                const opt = document.createElement('div'); opt.className = 'ar-option';
  1020.                opt.innerHTML = `${createArIcon(ar.w, ar.h, ar.isAuto, ar.isRef)} <span>${ar.label}</span>`;
  1021.                opt.addEventListener('click', () => { setAr(ar); els.arOptionsCont.style.display = 'none'; });
  1022.                els.arOptionsCont.appendChild(opt);
  1023.            });
  1024.        }
  1025.        function setAr(arObj) {
  1026.            currentAr = arObj.label; localStorage.setItem('xai_api_ar', currentAr);
  1027.            els.arSelectedIcon.innerHTML = createArIcon(arObj.w, arObj.h, arObj.isAuto, arObj.isRef); els.arSelectedText.innerText = arObj.label;
  1028.        }
  1029.        renderArOptions(); const initialAr = arData.find(a => a.label === currentAr) || arData[0]; setAr(initialAr);
  1030.  
  1031.        els.arSelectBox.addEventListener('click', (e) => {
  1032.            e.stopPropagation(); if (els.arOptionsCont.style.display === 'block') { els.arOptionsCont.style.display = 'none'; return; }
  1033.            const rect = els.arSelectBox.getBoundingClientRect(); els.arOptionsCont.style.top = (rect.bottom + 5) + 'px'; els.arOptionsCont.style.left = rect.left + 'px'; els.arOptionsCont.style.width = rect.width + 'px'; els.arOptionsCont.style.display = 'block';
  1034.        });
  1035.        document.addEventListener('click', (e) => { if (!els.arOptionsCont.contains(e.target)) els.arOptionsCont.style.display = 'none'; });
  1036.  
  1037.        async function processFile(file) {
  1038.            const isVid = file.type.startsWith('video/'); const isImg = file.type.startsWith('image/');
  1039.            if (!isVid && !isImg) return;
  1040.            if (isVid && (els.action.value === 'gen_image' || els.action.value === 'gen_video')) { els.action.value = 'edit_video'; updateActionUI(); updateGenSettingsMemory(); }
  1041.            else if (isImg && (els.action.value === 'edit_video' || els.action.value === 'extend_video')) { els.action.value = 'gen_image'; updateActionUI(); updateGenSettingsMemory(); }
  1042.  
  1043.            const max = getMaxMedia(); const activeCount = referenceMedia.filter(m => m.active).length;
  1044.            let thumbBase64 = null; if (isVid) thumbBase64 = await generateVideoThumbnail(file);
  1045.  
  1046.            const reader = new FileReader();
  1047.            reader.onload = async (event) => {
  1048.                const b64 = event.target.result;
  1049.                let w = 0, h = 0;
  1050.                if (isVid && file._w && file._h) { w = file._w; h = file._h; }
  1051.                else if (isImg) {
  1052.                    try {
  1053.                        const dims = await new Promise(r => { const i = new Image(); i.onload = () => r({w: i.width, h: i.height}); i.onerror = () => r({w: 0, h: 0}); i.src = b64; });
  1054.                        w = dims.w; h = dims.h;
  1055.                    } catch(e) {}
  1056.                }
  1057.                referenceMedia.push({ id: Date.now() + Math.random(), base64: b64, isVideo: isVid, active: activeCount < max, thumb: thumbBase64, fileName: file.name, w, h });
  1058.                renderRefList();
  1059.            };
  1060.            reader.readAsDataURL(file);
  1061.        }
  1062.  
  1063.        let draggedIndex = null;
  1064.        function renderRefList() {
  1065.            els.refList.innerHTML = '';
  1066.            referenceMedia.forEach((media, index) => {
  1067.                const item = document.createElement('div'); item.className = 'ref-item'; item.draggable = true;
  1068.                const activeRefs = referenceMedia.filter(m => m.active); const dynamicIndex = media.active ? activeRefs.indexOf(media) : '?';
  1069.                const actionVal = els.action.value; const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
  1070.  
  1071.                let thumbHtml = '';
  1072.                if (media.isVideo) {
  1073.                    if (media.thumb) thumbHtml = `<div style="position: relative; width: 90px; height: 90px; flex-shrink: 0;"><img src="${media.thumb}" class="ref-thumb" style="width: 100%; height: 100%;" title="${media.fileName || 'Video'}"><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></div>`;
  1074.                    else 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>`;
  1075.                } else thumbHtml = `<img src="${media.base64}" class="ref-thumb zoomable" data-filename="${media.fileName || 'Reference_'+(index+1)+'.jpg'}" title="${media.fileName || 'Click to view'}">`;
  1076.  
  1077.                let insertBtnHtml = '';
  1078.                if (!media.isVideo) {
  1079.                    if (disableInsert) insertBtnHtml = `<button class="ref-action-btn ref-insert" disabled style="opacity: 0.4; filter: grayscale(1); cursor: not-allowed;" title="Not available in this mode">➕ &lt;IMAGE_X&gt;</button>`;
  1080.                    else if (!media.active) insertBtnHtml = `<button class="ref-action-btn ref-insert" disabled style="opacity: 0.4; cursor: not-allowed;" title="Check 'Use in Payload' first">➕ &lt;IMAGE_?&gt;</button>`;
  1081.                    else insertBtnHtml = `<button class="ref-action-btn ref-insert" title="Insert into prompt">➕ &lt;IMAGE_${dynamicIndex}&gt;</button>`;
  1082.                }
  1083.  
  1084.                item.innerHTML = `<div class="ref-handle">☰</div>${thumbHtml}<div class="ref-info"><span style="font-size: 12px; color: #e2e8f0; font-weight: 600;">Ref ${index + 1} ${media.isVideo ? '(Video)' : ''}</span><label class="ref-toggle-label"><input type="checkbox" class="ref-active-toggle" ${media.active ? 'checked' : ''}> Use in Payload</label><div class="ref-btn-group">${insertBtnHtml}<button class="ref-action-btn ref-del">Remove</button></div></div>`;
  1085.  
  1086.                const insertBtn = item.querySelector('.ref-insert');
  1087.                if (insertBtn && media.active) {
  1088.                    insertBtn.addEventListener('click', (e) => {
  1089.                        const currentAction = els.action.value; if (currentAction === 'edit_video' || currentAction === 'extend_video') { e.preventDefault(); return alert("<IMAGE_X> tags not supported here."); }
  1090.                        const promptEl = els.prompt; const tag = `<IMAGE_${dynamicIndex}>`; const startPos = promptEl.selectionStart; const endPos = promptEl.selectionEnd;
  1091.                        setPromptVal(promptEl.value.substring(0, startPos) + tag + promptEl.value.substring(endPos, promptEl.value.length));
  1092.                        promptEl.selectionStart = promptEl.selectionEnd = startPos + tag.length; promptEl.focus();
  1093.                    });
  1094.                }
  1095.                if (!media.active) item.classList.add('inactive');
  1096.  
  1097.                item.querySelector('.ref-active-toggle').addEventListener('change', (e) => {
  1098.                    const max = getMaxMedia(); const currentlyActive = referenceMedia.filter(r => r.active).length;
  1099.                    if (e.target.checked && currentlyActive >= max) { alert(`Up to ${max} active references allowed.`); e.target.checked = false; return; }
  1100.                    media.active = e.target.checked; saveRefs(); renderRefList(); syncPromptBackdrop(); updateWarnings();
  1101.                });
  1102.  
  1103.                item.addEventListener('dragstart', (e) => { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; setTimeout(() => item.classList.add('dragging'), 0); });
  1104.                item.addEventListener('dragend', () => { item.classList.remove('dragging'); draggedIndex = null; document.querySelectorAll('.ref-item').forEach(el => el.classList.remove('drag-over-top', 'drag-over-bottom')); });
  1105.                item.addEventListener('dragover', (e) => { e.preventDefault(); if (draggedIndex === null || draggedIndex === index) return; const rect = item.getBoundingClientRect(); if (e.clientY - rect.top < rect.height / 2) { item.classList.add('drag-over-top'); item.classList.remove('drag-over-bottom'); } else { item.classList.add('drag-over-bottom'); item.classList.remove('drag-over-top'); } });
  1106.                item.addEventListener('dragleave', () => item.classList.remove('drag-over-top', 'drag-over-bottom'));
  1107.                item.addEventListener('drop', (e) => { e.preventDefault(); item.classList.remove('drag-over-top', 'drag-over-bottom'); if (draggedIndex === null || draggedIndex === index) return; const rect = item.getBoundingClientRect(); let insertIndex = (e.clientY - rect.top) < rect.height / 2 ? index : index + 1; if (draggedIndex < insertIndex) insertIndex--; const [movedImage] = referenceMedia.splice(draggedIndex, 1); referenceMedia.splice(insertIndex, 0, movedImage); renderRefList(); syncPromptBackdrop(); });
  1108.                item.querySelector('.ref-del').addEventListener('click', () => { referenceMedia.splice(index, 1); renderRefList(); syncPromptBackdrop(); updateWarnings(); });
  1109.                els.refList.appendChild(item);
  1110.            });
  1111.            saveRefs();
  1112.        }
  1113.  
  1114.        els.uploadPlaceholder.addEventListener('click', () => { els.fileInput.click(); });
  1115.        els.fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(processFile); els.fileInput.value = ''; });
  1116.        document.addEventListener('paste', (e) => { if (e.target && (e.target.id === 'payload-code' || e.target.id === 'xai-api-prompt' || e.target.id === 'set-custom-css' || e.target.tagName === 'INPUT' && e.target.type !== 'range')) return; const items = e.clipboardData.items; for (let i = 0; i < items.length; i++) if (items[i].type.indexOf('image') !== -1) processFile(items[i].getAsFile()); });
  1117.        els.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); els.dropzone.classList.add('drag-over'); });
  1118.        els.dropzone.addEventListener('dragleave', () => els.dropzone.classList.remove('drag-over'));
  1119.        els.dropzone.addEventListener('drop', (e) => { e.preventDefault(); els.dropzone.classList.remove('drag-over'); if (e.dataTransfer.files) Array.from(e.dataTransfer.files).forEach(processFile); });
  1120.  
  1121.        els.cancelBtn.addEventListener('click', () => {
  1122.            isRequestCancelled = true; if (currentAbortController) currentAbortController.abort();
  1123.            els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex';
  1124.            els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1125.            els.status.innerText = "Request Cancelled."; els.status.className = ""; els.status.style.color = "#ef4444";
  1126.        });
  1127.  
  1128.        async function executeGenerationSingle(endpoint, payload, isImageAction, statusEl, currentLoop, totalLoops) {
  1129.            let loopPrefix = totalLoops > 1 ? `[Run ${currentLoop}/${totalLoops}] ` : ''; statusEl.innerText = `${loopPrefix}Processing request...`; statusEl.className = "status-pulsing";
  1130.            addLog('INFO', `Starting generation loop ${currentLoop}/${totalLoops}`, { endpoint, isImageAction });
  1131.            currentAbortController = new AbortController(); let rateLimitFails = 0; let attempts = 0; let success = false;
  1132.  
  1133.            while (attempts < appSettings.retries && !success && !isRequestCancelled) {
  1134.                try {
  1135.                    statusEl.innerText = `${loopPrefix}Sending request to xAI...`;
  1136.                    const fullEndpoint = getApiUrl(endpoint);
  1137.                    addLog('NETWORK_REQ', `POST ${fullEndpoint}`, payload);
  1138.                    const response = await fetch(fullEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal: currentAbortController.signal });
  1139.  
  1140.                    if (response.status === 503 || response.status === 500 || response.status === 502) { attempts++; statusEl.innerText = `${loopPrefix}Busy (Error ${response.status}). Retrying... [${attempts}/${appSettings.retries}]`; addLog('WARN', `Gateway error ${response.status}. Retrying.`); await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin); continue; }
  1141.                    if (!response.ok) {
  1142.                        let errMsg = `HTTP ${response.status}`; let errData = null;
  1143.                        try {
  1144.                            errData = await response.json();
  1145.                            addLog('NETWORK_ERR', `Response error JSON`, { status: response.status, data: errData });
  1146.                            if (errData.error && errData.error.message) errMsg += `\n${errData.error.message}`; else if (errData.error && typeof errData.error === 'string') errMsg += `\n${errData.error}`;
  1147.                            if (errData.code) errMsg += `\nCode: ${errData.code}`; if (errData.detail) errMsg += `\n${typeof errData.detail === 'string' ? errData.detail : JSON.stringify(errData.detail)}`;
  1148.                        } catch(e) { addLog('NETWORK_ERR', `Failed to parse error response`, { status: response.status }); }
  1149.                        throw new Error(errMsg);
  1150.                    }
  1151.  
  1152.                    const data = await response.json();
  1153.                    addLog('NETWORK_RES', `Successful response`, data);
  1154.  
  1155.                    if (isImageAction) {
  1156.                        if (data && data.data && Array.isArray(data.data)) {
  1157.                            success = true; statusEl.innerText = `${loopPrefix}Processing final images...`; statusEl.style.color = "#10b981"; statusEl.className = "";
  1158.                            await Promise.all(data.data.map((imgObj, index) => processAndRenderImage(imgObj, payload.prompt, index + 1, data.data.length, els.currentImages)));
  1159.                            statusEl.innerText = "Ready"; statusEl.style.color = "#64748b";
  1160.                        } else throw new Error("Invalid response format.");
  1161.                    } else {
  1162.                        const reqId = data.request_id; if (!reqId) throw new Error(data.error ? (data.error.message || JSON.stringify(data.error)) : "No Request ID returned.");
  1163.                        let videoReady = false; let pollCount = 0; const MAX_POLLS = Math.max(1, Math.ceil(appSettings.videoPollTimeout / 5));
  1164.                        while (!videoReady && !isRequestCancelled) {
  1165.                            pollCount++; if (pollCount > MAX_POLLS) throw new Error("Timeout: Video likely dropped by filters or stuck in queue."); await sleep(5000); if (isRequestCancelled) break;
  1166.                            addLog('POLL_REQ', `Polling video ID: ${reqId}`, { pollCount, MAX_POLLS });
  1167.                            const pollRes = await fetch(getApiUrl(`/v1/videos/${reqId}`), { signal: currentAbortController.signal });
  1168.                            if (!pollRes.ok) { if (pollRes.status >= 400 && pollRes.status < 500) { let errData; try { errData = await pollRes.json(); } catch(e) {} addLog('POLL_ERR', `Poll failed HTTP ${pollRes.status}`, errData); if (errData && errData.error) throw new Error(typeof errData.error.message === 'string' ? errData.error.message : JSON.stringify(errData.error)); } continue; }
  1169.                            const pollData = await pollRes.json(); addLog('POLL_RES', `Poll Result`, pollData);
  1170.                            if (pollData.error) throw new Error(`API Error: ${pollData.error.message || JSON.stringify(pollData.error)}`);
  1171.                            const state = (pollData.status || pollData.state || 'processing').toLowerCase(); let progressText = typeof pollData.progress === 'number' ? ` ${pollData.progress}%` : "";
  1172.                            statusEl.innerText = `${loopPrefix}Polling video (Status: ${state}${progressText})...[${pollCount}/${MAX_POLLS}]`;
  1173.  
  1174.                            if (state === 'done' || state === 'completed') {
  1175.                                videoReady = true; success = true; statusEl.innerText = "Ready"; statusEl.className = ""; statusEl.style.color = "#94a3b8"; renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1176.                            } else if (['failed', 'expired', 'rejected', 'blocked', 'moderated', 'nsfw'].includes(state) || pollData.is_sensitive) {
  1177.                                if (pollData.video && pollData.video.url) {
  1178.                                    videoReady = true; success = true; statusEl.innerText = `${loopPrefix}Warning: Flagged as ${state}, but recovered!`; statusEl.className = ""; statusEl.style.color = "#d97706"; renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1179.                                    addLog('WARN', `Video flagged but recovered`, pollData);
  1180.                                } else throw new Error(`Generation halted. Reason: ${state}`);
  1181.                            }
  1182.                        }
  1183.                    }
  1184.               } catch (err) {
  1185.                    const errStr = err.message.toLowerCase();
  1186.                    addLog('ERROR', `Generation logic exception`, { message: err.message });
  1187.                    if (err.name === 'AbortError' || isRequestCancelled) { statusEl.innerText = "Request Cancelled."; statusEl.className = ""; statusEl.style.color = "#ef4444"; return false; }
  1188.                    let isLongRateLimit = false; let isShortRateLimit = false;
  1189.                    if (errStr.includes("requests per second (actual/limit)")) {
  1190.                        const secMatch = errStr.match(/requests per second \(actual\/limit\):\s*(\d+)\s*\/\s*(\d+)/); const minMatch = errStr.match(/requests per minute \(actual\/limit\):\s*(\d+)\s*\/\s*(\d+)/);
  1191.                        if (minMatch && minMatch[1] === minMatch[2]) isLongRateLimit = true; else if (secMatch && secMatch[1] === secMatch[2]) isShortRateLimit = true; else isLongRateLimit = true;
  1192.                    } else if (errStr.includes("rate limit") || errStr.includes("resource has been exhausted") || errStr.includes("http 429")) isLongRateLimit = true;
  1193.  
  1194.                    if (isShortRateLimit) {
  1195.                        attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached after per-second rate limits.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
  1196.                        statusEl.innerText = `${loopPrefix}Per-Second Limit Hit. Retrying... [${attempts}/${appSettings.retries}]`; await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin); continue;
  1197.                    } else if (isLongRateLimit) {
  1198.                        attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached after rate limits.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
  1199.                        let delaySeconds = parseInt(appSettings.rateLimitDelay) || 60; let countdown = delaySeconds;
  1200.                        if ((rateLimitFails++) < 1) { await sleep(1000); continue; }
  1201.                        rateLimitFails = 0;
  1202.                        while(countdown > 0 && !isRequestCancelled) { statusEl.innerText = `${loopPrefix}Rate Limit Hit. Retrying in ${countdown}s... [${attempts}/${appSettings.retries}]`; await sleep(1000); countdown--; }
  1203.                        if (isRequestCancelled) return false; continue;
  1204.                    } else if ((errStr.includes("timeout: video") || errStr.includes("generation halted.") || errStr.includes("video rejected by content moderation")) && appSettings.autoRetryStuckVideo) {
  1205.                        attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached for stuck video.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
  1206.                        statusEl.innerText = `${loopPrefix}Video Stuck/Failed. Auto-retrying... [${attempts}/${appSettings.retries}]`; await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin);
  1207.                        if (payload.prompt) payload.prompt += "\u200B"; continue;
  1208.                    } else { statusEl.innerText = `${loopPrefix}Error: ${err.message}`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
  1209.                }
  1210.            }
  1211.            if (!success && !isRequestCancelled) {
  1212.                if (!statusEl.innerText.includes("Failed:") && !statusEl.innerText.includes("Error:")) statusEl.innerText = `${loopPrefix}Failed after ${attempts} retries.`;
  1213.                statusEl.className = ""; statusEl.style.color = "#ef4444";
  1214.                addLog('ERROR', 'Generation loop failed completely');
  1215.                return false;
  1216.            }
  1217.            return success;
  1218.        }
  1219.  
  1220.        els.btn.addEventListener('click', async () => {
  1221.            initAudio(); const basePrompt = els.prompt.value.trim(); if (!basePrompt) return alert("Please enter a prompt.");
  1222.            addLog('UI', 'Generate button clicked', { basePrompt });
  1223.            const oldImages = Array.from(els.currentImages.children);
  1224.            if (oldImages.length > 0) {
  1225.                if (els.history.innerText.includes("No history")) els.history.innerHTML = '';
  1226.                oldImages.forEach(card => { card.className = 'history-card'; const promptEl = card.querySelector('p'); promptEl.title = "Click to copy prompt"; promptEl.onclick = () => setPromptVal(promptEl.innerText); els.history.prepend(card); });
  1227.            }
  1228.  
  1229.            const action = els.action.value; const activeRefs = referenceMedia.filter(m => m.active);
  1230.            let endpoint = '/v1/images/generations';
  1231.            if (action === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1232.            else if (action === 'gen_video') endpoint = '/v1/videos/generations';
  1233.            else if (action === 'edit_video') endpoint = '/v1/videos/edits';
  1234.            else if (action === 'extend_video') endpoint = '/v1/videos/extensions';
  1235.  
  1236.            const isImage = action === 'gen_image'; const totalLoops = parseInt(els.loopsNum.value) || 1;
  1237.            stealthIdentityReset(); els.btn.disabled = true; els.cancelBtn.style.display = 'flex'; els.previewBtn.style.display = 'none'; isRequestCancelled = false;
  1238.  
  1239.            let allSuccess = true;
  1240.            for (let i = 1; i <= totalLoops; i++) {
  1241.                if (isRequestCancelled) break;
  1242.                const dynamicPrompt = parseDynamicPrompt(basePrompt);
  1243.                els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Building...</div>`;
  1244.                const payload = await buildPayloadData(dynamicPrompt);
  1245.  
  1246.                els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Gen ${i}/${totalLoops}...</div>`;
  1247.                const ok = await executeGenerationSingle(endpoint, payload, isImage, els.status, i, totalLoops);
  1248.                if (!ok) { allSuccess = false; if (appSettings.breakLoopOnFailure) break; }
  1249.            }
  1250.  
  1251.            if (!isRequestCancelled) {
  1252.                els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex'; els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1253.                if (allSuccess) { els.status.innerText = "All runs complete."; els.status.className = ""; els.status.style.color = "#64748b"; notifyUser(false); addLog('INFO', 'All generation loops completed successfully'); }
  1254.                else { notifyUser(true); addLog('ERROR', 'Generation sequence ended with errors'); }
  1255.            }
  1256.        });
  1257.  
  1258.        els.reset.addEventListener('click', () => {
  1259.            if (!confirm("Wipe cache? Your prompt and settings will be saved.")) return;
  1260.            localStorage.setItem('xai_api_prompt', els.prompt.value);
  1261.            const patterns =[/flushAfter/i, /imagine/i, /generation/i, /grok/i, /mixpanel|mp_/i, /distinct_id/i, /_rst/i, /limit/i, /credit/i];
  1262.            for (let i = localStorage.length - 1; i >= 0; i--) { const k = localStorage.key(i); if (k && !k.startsWith('xai_api_') && patterns.some(p => p.test(k))) localStorage.removeItem(k); }
  1263.            document.cookie.split(';').forEach(c => { const name = c.split('=')[0]?.trim(); 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 : ''}`; }); }); });
  1264.            const u = new URL(location.href); ['_r', '_rst'].forEach(k => u.searchParams.set(k, Date.now())); location.replace(u.toString());
  1265.        });
  1266.    }
  1267.  
  1268.    async function processAndRenderImage(imgObj, originalPrompt, num, total, galleryEl) {
  1269.        if (!imgObj.b64_json) return;
  1270.        const mime = imgObj.mime_type || "image/png"; const b64 = imgObj.b64_json; const pngDataUri = `data:${mime};base64,${b64}`;
  1271.        const finalPrompt = imgObj.revised_prompt || originalPrompt; let finalDataUri = pngDataUri; let filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.png`;
  1272.        if (!appSettings.saveAsPng) { finalDataUri = await convertToJpegWithExif(pngDataUri, finalPrompt); filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.jpg`; }
  1273.        const card = document.createElement('div'); card.className = 'current-card';
  1274.        card.innerHTML = `<div class="img-wrapper"><img src="${finalDataUri}" class="zoomable" data-filename="${filename}" title="Click to view fullscreen"><a href="${finalDataUri}" download="${filename}" class="overlay-btn overlay-dl-btn" title="Download Full File">${DOWNLOAD_ICON}</a><button class="overlay-btn overlay-edit-btn" title="Edit this Image">${EDIT_ICON}</button></div><p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${finalPrompt}</p>`;
  1275.        card.querySelector('.overlay-edit-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(finalDataUri, false, filename); });
  1276.        galleryEl.prepend(card);
  1277.    }
  1278.  
  1279.    function renderVideoToGallery(videoUrl, originalPrompt, galleryEl) {
  1280.        const filename = `Grok Video - ${makeTimestamp()}.mp4`; const auto = appSettings.videoAutoplay ? "autoplay" : ""; const muted = appSettings.videoMuted ? "muted" : "";
  1281.        const card = document.createElement('div'); card.className = 'current-card';
  1282.        card.innerHTML = `<div class="img-wrapper"><video src="${videoUrl}" controls ${auto} ${muted} loop style="width: 100%; display: block; max-height: 50vh; object-fit: contain; background: #000;"></video><button class="overlay-btn overlay-dl-btn force-dl" data-url="${videoUrl}" data-filename="${filename}" style="z-index: 50; right: 6px;" title="Download MP4">${DOWNLOAD_ICON}</button><button class="overlay-btn overlay-edit-btn" style="z-index: 50; right: 40px;" title="Edit this Video">${EDIT_ICON}</button></div><p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${originalPrompt}</p>`;
  1283.        card.querySelector('.overlay-edit-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename); });
  1284.        const dlBtn = card.querySelector('.overlay-dl-btn');
  1285.        dlBtn.addEventListener('click', (e) => {
  1286.            e.preventDefault(); const url = dlBtn.getAttribute('data-url'); const fname = dlBtn.getAttribute('data-filename'); const originalIcon = dlBtn.innerHTML;
  1287.            dlBtn.innerHTML = '<div class="loading-spinner" style="border-top-color: #10b981;"></div>'; dlBtn.style.pointerEvents = 'none';
  1288.            if (typeof GM_xmlhttpRequest !== "undefined") {
  1289.                GM_xmlhttpRequest({ method: 'GET', url: url, responseType: 'blob', onload: function(response) {
  1290.                        if (response.status >= 200 && response.status < 300) {
  1291.                            const blobUrl = URL.createObjectURL(response.response); const a = document.createElement('a'); a.style.display = 'none'; a.href = blobUrl; a.download = fname; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
  1292.                        } else window.open(url, '_blank');
  1293.                        dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto';
  1294.                    }, onerror: function() { window.open(url, '_blank'); dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto'; } });
  1295.            } else { window.open(url, '_blank'); dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto'; }
  1296.        });
  1297.        galleryEl.prepend(card);
  1298.    }
  1299.  
  1300.    if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initApp); } else { initApp(); }
  1301. })();
Add Comment
Please, Sign In to add comment