Guest User

Untitled

a guest
Apr 11th, 2026
654
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         xAI Pro Studio Frontend (v39.2 - New UI Experiment)
  3. // @namespace    http://tampermonkey.net/
  4. // @version      39.2
  5. // @description  Full-Screen UI, Exif Fix, Multi-Image, Auto-Retry, Export Settings, Video Warnings, Quick-Action Sliders, Adaptive AR, Auto-Download, Extend Support, Anti-Throttling, Auto-Resume Session Wipe
  6. // @match        https://console.x.ai/playground/imagine*
  7. // @match        https://console.x.ai/team/*/imagine*
  8. // @grant        GM_xmlhttpRequest
  9. // @grant        GM_cookie
  10. // @grant        GM_download
  11. // @grant        GM_info
  12. // @connect      vidgen.x.ai
  13. // @run-at       document-start
  14. // ==/UserScript==
  15.  
  16. (function() {
  17.     'use strict';
  18.  
  19.     // ─── LOGGING & DEBUG ENGINE ───────────────────────────────────────────────
  20.     const appLogs = [];
  21.     const MAX_LOGS = 500;
  22.  
  23.     function stripHeavyData(val) {
  24.         if (val === null || val === undefined) return val;
  25.         if (typeof val === 'string') {
  26.             if (val.startsWith('data:image') || val.startsWith('data:video') || val.length > 2000) {
  27.                 return `[TRUNCATED_DATA_LEN_${val.length}]`;
  28.             }
  29.             return val;
  30.         }
  31.         if (typeof val !== 'object') return val;
  32.         if (Array.isArray(val)) return val.map(stripHeavyData);
  33.         const copy = {};
  34.         for (const k in val) {
  35.             if (Object.prototype.hasOwnProperty.call(val, k)) {
  36.                 copy[k] = stripHeavyData(val[k]);
  37.             }
  38.         }
  39.         return copy;
  40.     }
  41.  
  42.     function addLog(level, msg, data = null) {
  43.         try {
  44.             const ts = new Date().toISOString().replace('T', ' ').substring(0, 23);
  45.             const safeData = data ? stripHeavyData(data) : null;
  46.             appLogs.push({ ts, level, msg, data: safeData });
  47.             if (appLogs.length > MAX_LOGS) appLogs.shift();
  48.  
  49.             const consoleMsg = `[xAI Studio] [${level}] ${msg}`;
  50.             if (level === 'ERROR') console.error(consoleMsg, safeData || '');
  51.             else if (level === 'WARN') console.warn(consoleMsg, safeData || '');
  52.             else console.log(consoleMsg, safeData || '');
  53.         } catch(e) {}
  54.     }
  55.  
  56.     function formatLogsForExport() {
  57.         return appLogs.map(l => {
  58.             let text = `[${l.ts}] [${l.level}] ${l.msg}`;
  59.             if (l.data) {
  60.                 try { text += `\n${JSON.stringify(l.data, null, 2)}`; }
  61.                 catch(e) { text += `\n[Unserializable Data]`; }
  62.             }
  63.             return text;
  64.         }).join('\n\n----------------------------------------\n\n');
  65.     }
  66.  
  67.     addLog('INFO', 'Script started executing');
  68.  
  69.     // ─── UTILITIES & DATA STORAGE ─────────────────────────────────────────────
  70.     const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  71.     function pad2(n) { return String(n).padStart(2, '0'); }
  72.     function makeTimestamp() {
  73.         const d = new Date();
  74.         // Return friendly format: YYYY-MM-DD HH:MM:SS
  75.         return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
  76.     }
  77.     function base64ToBlobUrl(b64) {
  78.         if (!b64 || !b64.startsWith('data:')) return b64;
  79.         try {
  80.             const parts = b64.split(',');
  81.             const mime = parts[0].match(/:(.*?);/)[1];
  82.             const bstr = atob(parts[1]);
  83.             let n = bstr.length;
  84.             const u8arr = new Uint8Array(n);
  85.             while (n--) u8arr[n] = bstr.charCodeAt(n);
  86.             return URL.createObjectURL(new Blob([u8arr], { type: mime }));
  87.         } catch(e) { return b64; }
  88.     }
  89.     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>`;
  90.     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>`;
  91.     const EXTEND_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="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>`;
  92.     const VIDEO_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="m22 8-6 4 6 4V8Z"/><rect width="14" height="12" x="2" y="6" rx="2" ry="2"/></svg>`;
  93.  
  94.     // ─── SETTINGS SCHEMA & MANAGER ───────────────────────────────────────────
  95.     const SETTINGS_SCHEMA = {
  96.         retries:             { id: 'set-retries',               type: 'number',   default: 20 },
  97.         delayMin:            { id: 'set-delay-min',             type: 'number',   default: 2000 },
  98.         delayMax:            { id: 'set-delay-max',             type: 'number',   default: 4000 },
  99.         rateLimitDelay:      { id: 'set-rate-limit-delay',      type: 'number',   default: 20 },
  100.         notifications:       { id: 'set-notifications',         type: 'checkbox', default: true },
  101.         customCSS:           { id: 'set-custom-css',            type: 'text',     default: "" },
  102.         saveAsPng:           { id: 'set-save-png',              type: 'checkbox', default: false },
  103.         apiBaseUrl:          { id: 'set-api-base-url',          type: 'text',     default: "" },
  104.         videoPollTimeout:    { id: 'set-video-timeout',         type: 'number',   default: 300 },
  105.         autoRetryStuckVideo: { id: 'set-auto-retry-video',      type: 'checkbox', default: false },
  106.         breakLoopOnFailure:  { id: 'set-break-loop-on-failure', type:'checkbox', default: true },
  107.         referenceARTrick:    { id: 'set-reference-ar-trick',    type: 'checkbox', default: true },
  108.         maximumGreedMode:    { id: 'set-maximum-greed-mode',    type: 'checkbox', default: false },
  109.         suppressEditWarning: { id: 'set-suppress-warning',      type: 'checkbox', default: false },
  110.         videoAutoplay:       { id: 'set-video-autoplay',        type: 'checkbox', default: true },
  111.         videoMuted:          { id: 'set-video-muted',           type: 'checkbox', default: false },
  112.         uiFontSize:          { id: 'set-font-size',             type: 'number',   default: 13 },
  113.         autoDownload:        { id: 'set-auto-download',         type: 'checkbox', default: false },
  114.         antiThrottling:      { id: 'set-anti-throttling',       type: 'checkbox', default: true }
  115.     };
  116.  
  117.     const SettingsManager = {
  118.         load: function() {
  119.             let stored = JSON.parse(localStorage.getItem('xai_api_settings') || '{}');
  120.             let parsed = {};
  121.             for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
  122.                 let val = stored[key] !== undefined ? stored[key] : config.default;
  123.                 if (config.type === 'number') val = parseInt(val) || config.default;
  124.                 parsed[key] = val;
  125.             }
  126.             parsed.delayMax = Math.max(parsed.delayMin, parsed.delayMax);
  127.             return parsed;
  128.         },
  129.         populateUI: function(currentSettings) {
  130.             for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
  131.                 const el = document.getElementById(config.id);
  132.                 if (!el) continue;
  133.                 if (config.type === 'checkbox') el.checked = currentSettings[key];
  134.                 else el.value = currentSettings[key];
  135.             }
  136.         },
  137.         saveFromUI: function() {
  138.             let newSettings = {};
  139.             for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
  140.                 const el = document.getElementById(config.id);
  141.                 if (!el) { newSettings[key] = config.default; continue; }
  142.  
  143.                 if (config.type === 'checkbox') {
  144.                     newSettings[key] = el.checked;
  145.                 } else if (config.type === 'number') {
  146.                     newSettings[key] = parseInt(el.value) || config.default;
  147.                 } else {
  148.                     newSettings[key] = el.value.trim();
  149.                 }
  150.             }
  151.             newSettings.delayMax = Math.max(newSettings.delayMin, newSettings.delayMax);
  152.             localStorage.setItem('xai_api_settings', JSON.stringify(newSettings));
  153.             return newSettings;
  154.         }
  155.     };
  156.  
  157.     let appSettings = SettingsManager.load();
  158.     let favoritePrompts = JSON.parse(localStorage.getItem('xai_api_favs') || '[]');
  159.  
  160.     function getApiUrl(path) {
  161.         let base = appSettings.apiBaseUrl || '';
  162.         if (base.endsWith('/')) base = base.slice(0, -1);
  163.         if (!path.startsWith('/') && base) path = '/' + path;
  164.         return base + path;
  165.     }
  166.  
  167.     function parseDynamicPrompt(text) {
  168.         if (!text) return text;
  169.         let parsed = text; let prev;
  170.         do {
  171.             prev = parsed;
  172.             parsed = parsed.replace(/\{([^{}]+)\}/g, (m, c) => { const o = c.split('|'); return o[Math.floor(Math.random() * o.length)]; });
  173.         } while (parsed !== prev);
  174.         parsed = parsed.replace(/@randomseed/gi, () => Math.floor(1000000000 + Math.random() * 9000000000).toString());
  175.         return parsed.trim();
  176.     }
  177.  
  178.     let sharedAudioCtx = null;
  179.     let awakeOsc = null;
  180.     let titleBlinkInterval = null;
  181.     const originalTitle = document.title || "xAI Pro Studio";
  182.  
  183.     function initAudio() {
  184.         if (!sharedAudioCtx) {
  185.             try { sharedAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch(e) {}
  186.         }
  187.         if (sharedAudioCtx && sharedAudioCtx.state === 'suspended') sharedAudioCtx.resume();
  188.     }
  189.  
  190.     function toggleKeepAwake(enable) {
  191.         if (enable && !appSettings.antiThrottling) return;
  192.         if (enable) {
  193.             initAudio();
  194.             if (sharedAudioCtx) {
  195.                 if (!awakeOsc) {
  196.                     try {
  197.                         //Сделай звук активности вкладки типа 21 кГц -90 дБ.
  198.                         awakeOsc = sharedAudioCtx.createOscillator();
  199.                         awakeOsc.frequency.value = 21000;
  200.                         awakeOsc.type = 'sine';
  201.                         const gain = sharedAudioCtx.createGain();
  202.                         //gain.gain.value = 0.001;
  203.                         gain.gain.value = 0.000031622776601683795; //Сделай звук активности вкладки типа 21 кГц -90 дБ.
  204.                         awakeOsc.connect(gain);
  205.                         gain.connect(sharedAudioCtx.destination);
  206.                         awakeOsc.start();
  207.                     } catch(e) {}
  208.                 }
  209.             }
  210.         } else {
  211.             if (awakeOsc) {
  212.                 try { awakeOsc.stop(); awakeOsc.disconnect(); } catch(e) {}
  213.                 awakeOsc = null;
  214.             }
  215.         }
  216.     }
  217.  
  218.     function notifyUser(isError = false) {
  219.         if (!appSettings.notifications) return;
  220.         initAudio();
  221.         if (sharedAudioCtx) {
  222.             try {
  223.                 const osc = sharedAudioCtx.createOscillator(); const gain = sharedAudioCtx.createGain();
  224.                 osc.connect(gain); gain.connect(sharedAudioCtx.destination);
  225.                 if (isError) {
  226.                     osc.type = 'sawtooth'; osc.frequency.setValueAtTime(300, sharedAudioCtx.currentTime); osc.frequency.exponentialRampToValueAtTime(100, sharedAudioCtx.currentTime + 0.3);
  227.                 } else {
  228.                     osc.type = 'sine'; osc.frequency.setValueAtTime(500, sharedAudioCtx.currentTime); osc.frequency.exponentialRampToValueAtTime(1000, sharedAudioCtx.currentTime + 0.2);
  229.                 }
  230.                 gain.gain.setValueAtTime(0.1, sharedAudioCtx.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, sharedAudioCtx.currentTime + 0.5);
  231.                 osc.start(sharedAudioCtx.currentTime); osc.stop(sharedAudioCtx.currentTime + 0.5);
  232.             } catch(e) {}
  233.         }
  234.         if (!document.hasFocus()) {
  235.             if (titleBlinkInterval) clearInterval(titleBlinkInterval);
  236.             let toggle = true;
  237.             titleBlinkInterval = setInterval(() => { document.title = toggle ? (isError ? "❌ FAILED" : "✅ DONE") : originalTitle; toggle = !toggle; }, 1000);
  238.             const clearBlink = () => { clearInterval(titleBlinkInterval); document.title = originalTitle; window.removeEventListener('focus', clearBlink); };
  239.             window.addEventListener('focus', clearBlink);
  240.         }
  241.     }
  242.  
  243.     async function nuclearSessionReset(remainingLoops = 0) {
  244.         addLog('INFO', `Nuclear Reset triggered.`);
  245.  
  246.         if (typeof GM_cookie !== 'undefined') {
  247.             await new Promise(resolve => {
  248.                 GM_cookie.list({ url: window.location.href }, (cookies, error) => {
  249.                     if (!error && cookies && cookies.length > 0) {
  250.                         let deletedCount = 0;
  251.                         cookies.forEach(c => {
  252.                             GM_cookie.delete({ url: window.location.href, name: c.name }, () => {
  253.                                 deletedCount++;
  254.                                 if (deletedCount === cookies.length) resolve();
  255.                             });
  256.                         });
  257.                     } else resolve();
  258.                 });
  259.             });
  260.             await new Promise(resolve => {
  261.                 GM_cookie.list({ url: 'https://x.ai' }, (cookies, error) => {
  262.                     if (!error && cookies && cookies.length > 0) {
  263.                         let deletedCount = 0;
  264.                         cookies.forEach(c => {
  265.                             GM_cookie.delete({ url: 'https://x.ai', name: c.name }, () => {
  266.                                 deletedCount++;
  267.                                 if (deletedCount === cookies.length) resolve();
  268.                             });
  269.                         });
  270.                     } else resolve();
  271.                 });
  272.             });
  273.         }
  274.  
  275.         for (let i = localStorage.length - 1; i >= 0; i--) {
  276.             const k = localStorage.key(i);
  277.             if (k && !k.startsWith('xai_api_')) localStorage.removeItem(k);
  278.         }
  279.         sessionStorage.clear();
  280.  
  281.         if ( appSettings.maximumGreedMode && remainingLoops > 0) {
  282.             sessionStorage.setItem('xai_resume_loops', remainingLoops.toString());
  283.         } else {
  284.             await fetch('https://console.x.ai/playground/imagine');
  285.         }
  286.     }
  287.  
  288.     let piexifPromise = null;
  289.     function loadPiexif() {
  290.         if (piexifPromise) return piexifPromise;
  291.         piexifPromise = new Promise((resolve, reject) => {
  292.             const getPiexif = () => window.piexif || (typeof unsafeWindow !== 'undefined' ? unsafeWindow.piexif : null);
  293.             let px = getPiexif();
  294.             if (px) { resolve(px); return; }
  295.             const script = document.createElement('script');
  296.             script.src = 'https://cdnjs.cloudflare.com/ajax/libs/piexifjs/1.0.6/piexif.min.js';
  297.             script.onload = () => { px = getPiexif(); if (px) resolve(px); else { piexifPromise = null; reject(new Error("piexif missing")); } };
  298.             script.onerror = () => { piexifPromise = null; reject(new Error('Failed to load piexifjs')); };
  299.             document.head.appendChild(script);
  300.         });
  301.         return piexifPromise;
  302.     }
  303.  
  304.     function convertToJpegWithExif(base64PngUri, prompt) {
  305.         return new Promise((resolve, reject) => {
  306.             const img = new Image();
  307.             img.onload = async () => {
  308.                 const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height;
  309.                 const ctx = canvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0);
  310.                 let jpegUri = canvas.toDataURL('image/jpeg', 0.95);
  311.                 if (prompt) {
  312.                     try {
  313.                         const piexif = await loadPiexif();
  314.                         const exifObj = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "Interop": {}};
  315.                         exifObj['0th'][piexif.ImageIFD.ImageDescription] = unescape(encodeURIComponent(prompt));
  316.                         jpegUri = piexif.insert(piexif.dump(exifObj), jpegUri);
  317.                     } catch (e) { addLog('ERROR', 'EXIF Injection Failed', e); }
  318.                 }
  319.                 resolve(jpegUri);
  320.             };
  321.             img.onerror = reject; img.src = base64PngUri;
  322.         });
  323.     }
  324.  
  325.     async function extractPromptFromImage(file) {
  326.         if (!file || !file.type.includes('image')) return null;
  327.         try {
  328.             const piexif = await loadPiexif();
  329.             return new Promise((resolve) => {
  330.                 const reader = new FileReader();
  331.                 reader.onload = (e) => {
  332.                     try {
  333.                         const exifData = piexif.load(e.target.result);
  334.                         let prompt = exifData['0th'] && exifData['0th'][piexif.ImageIFD.ImageDescription];
  335.                         if (Array.isArray(prompt)) prompt = String.fromCharCode.apply(null, prompt).replace(/\0/g, '');
  336.                         if (prompt) { try { prompt = decodeURIComponent(escape(prompt)); } catch(err) {} }
  337.                         if (!prompt && exifData['0th'] && exifData['0th'][40091]) {
  338.                             const xpTitleArr = exifData['0th'][40091]; let str = '';
  339.                             for (let i = 0; i < xpTitleArr.length; i += 2) {
  340.                                 const charCode = xpTitleArr[i] | (xpTitleArr[i+1] << 8);
  341.                                 if (charCode === 0) break;
  342.                                 str += String.fromCharCode(charCode);
  343.                             }
  344.                             prompt = str;
  345.                         }
  346.                         resolve(prompt ? prompt.trim() : null);
  347.                     } catch (err) { resolve(null); }
  348.                 };
  349.                 reader.onerror = () => resolve(null);
  350.                 reader.readAsDataURL(file);
  351.             });
  352.         } catch (e) { return null; }
  353.     }
  354.  
  355.     function generateVideoThumbnail(file) {
  356.         return new Promise((resolve) => {
  357.             const video = document.createElement('video'); video.preload = 'metadata'; video.muted = true; video.playsInline = true;
  358.             const url = URL.createObjectURL(file); video.src = url; let isSeeked = false;
  359.             video.onloadeddata = () => { video.currentTime = Math.min(0.5, video.duration / 2 || 0); file._w = video.videoWidth; file._h = video.videoHeight; };
  360.             video.onseeked = () => {
  361.                 if (isSeeked) return; isSeeked = true;
  362.                 try {
  363.                     const canvas = document.createElement('canvas'); canvas.width = video.videoWidth || 140; canvas.height = video.videoHeight || 140;
  364.                     const ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, canvas.width, canvas.height); URL.revokeObjectURL(url); resolve(canvas.toDataURL('image/jpeg', 0.8));
  365.                 } catch(e) { URL.revokeObjectURL(url); resolve(null); }
  366.             };
  367.             video.onerror = () => { URL.revokeObjectURL(url); resolve(null); };
  368.             setTimeout(() => { if (!isSeeked) { URL.revokeObjectURL(url); resolve(null); } }, 2000);
  369.         });
  370.     }
  371.  
  372.     function updateFontSize(size) {
  373.         let el = document.getElementById('xai-custom-font-size');
  374.         if (!el) { el = document.createElement('style'); el.id = 'xai-custom-font-size'; document.head.appendChild(el); }
  375.         if (size === 13) { el.innerHTML = ''; return; }
  376.  
  377.         el.innerHTML = `
  378.             #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; }
  379.             #xai-pro-app .ar-option, #xai-pro-app .fav-text, #xai-pro-app #xai-api-status { font-size: ${size - 1}px !important; }
  380.             #xai-pro-app .panel-title, #xai-pro-app label, #xai-pro-app .toggle-btn, #xai-pro-app .slider-header, #xai-pro-app .warning-box, #xai-pro-app .ref-info span { font-size: ${size - 2}px !important; }
  381.             #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; }
  382.             #xai-pro-app .ref-handle { font-size: ${size + 1}px !important; }
  383.             #xai-pro-app h3 { font-size: ${size + 2}px !important; }
  384.         `;
  385.     }
  386.  
  387.     const MAPS = {
  388.         batch: [1, 2, 3, 4, 5, 8, 10],
  389.         durGen: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
  390.         durExt: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  391.     };
  392.  
  393.     const arData =[
  394.         { label: 'Auto', w: 1, h: 1, isAuto: true }, { label: 'By First Ref', w: 1, h: 1, isAuto: true, isRef: true },
  395.         { label: '1:1', w: 1, h: 1, imageOnly: true }, { label: '1:1', w: 1, h: 1, imageOnly: true },
  396.         { label: '3:4', w: 3, h: 4 }, { label: '4:3', w: 4, h: 3 },
  397.         { label: '9:16', w: 9, h: 16 }, { label: '16:9', w: 16, h: 9 },
  398.         { label: '2:3', w: 2, h: 3 }, { label: '3:2', w: 3, h: 2 },
  399.         { label: '9:19.5', w: 9, h: 19.5, imageOnly: true }, { label: '19.5:9', w: 19.5, h: 9, imageOnly: true },
  400.         { label: '9:20', w: 9, h: 20, imageOnly: true }, { label: '20:9', w: 20, h: 9, imageOnly: true },
  401.         { label: '1:2', w: 1, h: 2, imageOnly: true }, { label: '2:1', w: 2, h: 1, imageOnly: true }
  402.     ];
  403.  
  404.     function createArIcon(w, h, isAuto, isRef) {
  405.         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>`;
  406.         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>`;
  407.         const scale = 12 / Math.max(w, h);
  408.         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>`;
  409.     }
  410.  
  411.     // ─── UI INJECTION ─────────────────────────────────────────────────────────
  412.     const UI_CSS = `
  413.         ::-webkit-scrollbar { width: 6px; }
  414.         ::-webkit-scrollbar-track { background: transparent; }
  415.         ::-webkit-scrollbar-thumb { background: #475569; border-radius: 6px; }
  416.  
  417.         @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  418.         @keyframes pulse { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
  419.  
  420.         .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; }
  421.         .btn-content { display: flex; align-items: center; justify-content: center; gap: 6px; }
  422.         .status-pulsing { animation: pulse 2s ease-in-out infinite; color: #3b82f6 !important; font-weight: 600; }
  423.  
  424.         #xai-pro-app { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 9999999; background: #0f172a; font-family: 'Inter', -apple-system, sans-serif; color: #e2e8f0; display: flex; box-sizing: border-box; overflow: hidden; }
  425.         #xai-pro-app * { box-sizing: border-box; }
  426.  
  427.         .panel {
  428.             background: #1e293b;
  429.             border-radius: 8px;
  430.             border: 1px solid rgba(255, 255, 255, 0.08);
  431.             box-shadow: none; /* Removed shadow */
  432.             display: flex; flex-direction: column; overflow: hidden;
  433.         }
  434.         .panel-title { font-size: 11px; font-weight: 700; color: #94a3b8; letter-spacing: 0.5px; padding: 10px; border-bottom: 1px solid rgba(255, 255, 255, 0.05);  text-transform: uppercase; flex-shrink: 0; }
  435.  
  436.         .col-left {
  437.             width: 310px; min-width: 320px; display: flex; flex-direction: column; flex-shrink: 0;
  438.             transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1), min-width 0.3s, opacity 0.2s;
  439.             overflow: hidden; opacity: 1;
  440.             padding: 10px 0 10px 10px;
  441.         }
  442.         .col-left.collapsed { width: 0; min-width: 0; opacity: 0; pointer-events: none; padding: 10px 0; }
  443.         .sidebar-inner { width: 310px; display: flex; flex-direction: column; gap: 10px; height: 100%; overflow-y: hidden; }
  444.  
  445.         #toggle-sidebar-btn {
  446.             display: flex; align-items: center; justify-content: center; width: 22px; height: 50px;
  447.             background: #1e293b; border: 1px solid #334155; border-left: none; border-radius: 0 6px 6px 0;
  448.             cursor: pointer; z-index: 101; color: #94a3b8; font-size: 10px; transition: 0.2s; margin-top: 15px; box-shadow: 2px 0 5px rgba(0,0,0,0.2);
  449.         }
  450.         #toggle-sidebar-btn:hover { background: #334155; color: #f8fafc; }
  451.  
  452.         .col-center { position: relative; flex: 1; display: flex; flex-direction: column; overflow: hidden; padding: 10px; gap: 10px; }
  453.  
  454.         .scrollable-main { flex: 1; overflow-y: auto; padding-bottom: 220px; display: flex; flex-direction: column; gap: 20px; }
  455.  
  456.         .frosted-panel {
  457.             position: absolute; bottom: 10px; left: 10px; right: 10px; z-index: 100;
  458.             margin: 0 auto; max-width: 1024px; border-radius: 10px;
  459.             background: rgba(15, 23, 42, 0.6) !important;
  460.             backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
  461.             border: 1px solid rgba(255, 255, 255, 0.05);
  462.             padding: 12px; flex-shrink: 0;
  463.             box-shadow: 0 20px 40px rgba(0,0,0,0.3);
  464.         }
  465.  
  466.          textarea, select, input[type="text"], input[type="number"], input[type="checkbox"] {
  467.             background: rgba(0, 0, 0, 0.2);
  468.             border: 1px solid transparent;
  469.             border-radius: 6px;
  470.             padding: 8px; color: #f8fafc; font-size: 13px; outline: none; transition: 0.2s;
  471.         }
  472.         textarea, select, input[type="text"], input[type="number"] {
  473.             width: 100%; /* Restores full width in modals */
  474.             box-sizing: border-box;
  475.         }
  476.         textarea:focus, select:focus, input[type="text"]:focus, input[type="number"]:focus {
  477.             border-color: rgba(99, 102, 241, 0.5);
  478.             background: rgba(0, 0, 0, 0.3);
  479.             box-shadow: none;
  480.         }
  481.         label { font-size: 11px; font-weight: 600; color: #94a3b8; margin-bottom: 4px; display: block; }
  482.  
  483.         .btn-primary { background: #4f46e5; 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; }
  484.         .btn-primary:hover:not(:disabled) { background: #4338ca; }
  485.         .btn-primary:disabled { opacity: 0.8; cursor: not-allowed; }
  486.         .btn-secondary { background: transparent; color: #94a3b8; border: 1px solid transparent; 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; }
  487.         .btn-secondary:hover:not(:disabled) { background: rgba(255, 255, 255, 0.05);  }
  488.  
  489.         .action-select { width: 100%; font-weight: 600; font-size: 13px; color: #f8fafc; background: transparent; border: none; outline: none; overflow-y: hidden; }
  490.         .action-select option { padding: 8px 10px; margin-bottom: cursor: pointer; transition: 0.1s; background: #0f172a; }
  491.         .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); }
  492.         .action-select option:hover:not(:checked) { background: #334155; color: #f8fafc; }
  493.  
  494.         .slider-block { display: flex; flex-direction: column; margin-bottom: 12px; }
  495.         .toggle-btn {
  496.             background: rgba(0, 0, 0, 0.2);
  497.             border: 1px solid transparent;
  498.             color: #94a3b8;
  499.             box-shadow: none;
  500.         }
  501.         .toggle-btn.active {
  502.             background: #10b981; /* Solid flat green */
  503.             color: #fff; border-color: transparent;
  504.             box-shadow: none;
  505.         }
  506.         .slider-header { display: flex; justify-content: space-between; font-size: 11px; margin-bottom: 6px; font-weight: 600; color: #94a3b8; }
  507.         .slider-header span { color: #f8fafc; }
  508.         .slider-ticks { position: relative; height: 14px; width: 100%; font-size: 10px; color: #64748b; margin-top: 4px; padding: 0; }
  509.         .slider-ticks span { position: absolute; transform: translateX(-50%); text-align: center; white-space: nowrap; line-height: 1; }
  510.  
  511.         input[type=range] { -webkit-appearance: none; width: 100%; background: transparent; margin: 4px 0; outline: none; transform: scaleY(1.6); }
  512.         input[type=range]::-webkit-slider-runnable-track {
  513.             background: rgba(255, 255, 255, 0.1);
  514.             box-shadow: none; /* Remove inset shadow */
  515.         }
  516.         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); }
  517.         input[type=range]::-webkit-slider-thumb {
  518.             background: #10b981;
  519.             box-shadow: none; /* Remove drop shadow */
  520.         }
  521.         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); }
  522.         input[type=range]:focus::-webkit-slider-thumb { box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4); }
  523.         input[type=range]:focus::-moz-range-thumb { box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4); }
  524.  
  525.         .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; }
  526.         #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: 265px; overflow-y: auto; display: none; z-index: 99999999; grid-template-columns: 1fr 1fr; }
  527.         .ar-option { display: flex; align-items: center; gap: 8px; padding: 6px 8px; cursor: pointer; font-size: 12px; color: #cbd5e1; }
  528.         .ar-option:hover { background: #334155; color: #f8fafc; }
  529.  
  530.         .img-wrapper { position: relative; display: block; width: 100%; background: #0f172a; border-radius: 7px; overflow: hidden; }
  531.         .zoomable { cursor: zoom-in; transition: transform 0.2s; width: 100%; display: block; }
  532.         .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: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); opacity: 0.75; z-index: 50; cursor: pointer; border: none; padding: 0; }
  533.         .overlay-btn:hover { background: rgba(15, 23, 42, 0.9); opacity: 1; transform: scale(1.05); }
  534.         .overlay-dl-btn { right: 6px; }
  535.         .overlay-edit-btn { right: 40px; color: #10b981; }
  536.         .overlay-extend-btn { right: 74px; color: #3b82f6; }
  537.         .overlay-video-btn { right: 74px; color: #3b82f6; }
  538.         .current-card .overlay-btn { opacity: 0; visibility: hidden; transform: translateY(-5px); pointer-events: none; }
  539.         .current-card:hover .overlay-btn { opacity: 0.75; visibility: visible; transform: translateY(0); pointer-events: auto; }
  540.         .current-card .overlay-btn:hover { opacity: 1; transform: scale(1.1); background: rgba(15, 23, 42, 0.95); }
  541.  
  542.         .ref-item { position: relative; display: flex; align-items: center; gap: 10px; padding: 2px; background: #1e293b; border: 1px solid rgba(255,255,255,0.05); border-radius: 6px; margin-bottom: 6px; cursor: grab; transition: 0.1s; }
  543.         .ref-item.inactive { opacity: 0.6; filter: grayscale(0.8); }
  544.         .ref-item:active { cursor: grabbing; }
  545.         .ref-item.dragging { opacity: 0.4; }
  546.         .ref-close-btn { position: absolute; top: 6px; right: 6px; background: transparent; border: none; color: #94a3b8; font-size: 16px; width: 22px; height: 22px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 4px; transition: 0.2s; line-height: 1; padding: 0; z-index: 10; }
  547.         .ref-close-btn:hover { background: rgba(239, 68, 68, 0.15); color: #ef4444; }
  548.         .ref-handle { font-size: 14px; color: #475569; cursor: grab; padding: 0 4px; }
  549.         .ref-thumb { width: 90px; height: 90px; border-radius: 4px; object-fit: cover; border: 1px solid #334155; background: #0f172a; transition: 0.2s; }
  550.         .ref-info { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 6px; min-width: 0; }
  551.         .ref-toggle-label { font-size: 11px; color: #cbd5e1; display: flex; align-items: center; gap: 4px; cursor: pointer; user-select: none; }
  552.         .ref-toggle-label input { width: 12px; height: 12px; cursor: pointer; accent-color: #10b981; margin: 0; padding: 0; }
  553.         .ref-btn-group { display: flex; gap: 4px; width: 100%; margin-top: auto; }
  554.         .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; }
  555.         .ref-insert { background: #0f766e; color: #ccfbf1; border: 1px solid #115e59; }
  556.         .ref-insert:hover { background: #115e59; color: #f0fdfa; }
  557.         .ref-del { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
  558.         .ref-del:hover { background: #7f1d1d; color: #fee2e2; }
  559.         .drag-over-top { border-top: 2px solid #22c55e !important; }
  560.         .drag-over-bottom { border-bottom: 2px solid #22c55e !important; }
  561.         .drop-panel.drag-over { background: #064e3b; border-color: #10b981; box-shadow: 0 0 0 4px rgba(16,185,129,0.15); }
  562.  
  563.         .batch-container { display: flex; flex-direction: column; background: rgba(15, 23, 42, 0.4); border: 1px solid #334155; border-radius: 10px; padding: 10px; }
  564.         .batch-header { font-size: 12px; color: #cbd5e1; font-weight: 600; padding-bottom: 8px; border-bottom: 1px solid #334155; margin-bottom: 10px; gap: 20px; display: flex;  align-items: center; cursor: pointer; transition: 0.2s;}
  565.         .batch-header:hover { color: #f8fafc; border-bottom-color: #64748b; }
  566.         .batch-grid { display: flex; flex-wrap: wrap; gap: 12px; align-content: start; justify-content: flex-start; }
  567.  
  568.         .current-card { flex: 0 1 380px; max-width: 100%; position: relative; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.05); background: #1e293b; transition: all 0.3s ease; z-index: 1; }
  569.         .current-card:hover { z-index: 10; }
  570.         .current-card.downloaded { border-color: #10b981 !important; box-shadow: 0 0 10px rgba(16,185,129,0.3) !important; }
  571.         .current-card img, .current-card video { display: block; width: 100%; max-height: 50vh; object-fit: contain; background: #0f172a; }
  572.  
  573.         .prompt-dropdown { position: absolute; top: calc(100% + 6px); left: 0; right: 0; background: rgba(30, 41, 59, 0.95); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; box-shadow: 0 15px 35px rgba(0,0,0,0.5); padding: 12px; font-size: 11px; color: #94a3b8; cursor: pointer; opacity: 0; visibility: hidden; transform: translateY(-10px); transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); max-height: 250px; overflow-y: auto; line-height: 1.4; word-wrap: break-word; }
  574.         .current-card:hover .prompt-dropdown { opacity: 1; visibility: visible; transform: translateY(0); }
  575.         .prompt-dropdown:hover { color: #f8fafc; background: rgba(40, 53, 72, 0.95); }
  576.  
  577.         .prompt-drawer { display: grid; grid-template-rows: 0fr; transition: grid-template-rows 0.3s cubic-bezier(0.4, 0, 0.2, 1); background: rgba(0, 0, 0, 0.2); }
  578.         .current-card:hover .prompt-drawer { grid-template-rows: 1fr; }
  579.         .prompt-drawer-inner { overflow: hidden; }
  580.         .prompt-drawer-text { padding: 12px; font-size: 11px; color: #94a3b8; cursor: pointer; border-top: 1px solid rgba(255,255,255,0.05); transition: background 0.2s, color 0.2s; margin: 0; line-height: 1.4; word-wrap: break-word; }
  581.         .prompt-drawer-text:hover { color: #f8fafc; background: rgba(255,255,255,0.05); }
  582.         .prompt-overlay:hover { background: rgba(30, 41, 59, 0.95); }
  583.         .prompt-ref-thumb { width: 32px; height: 32px; border-radius: 4px; object-fit: cover; border: 1px solid rgba(255,255,255,0.1); opacity: 0.5; transition: all 0.2s; user-select: none; }
  584.         .prompt-ref-thumb.glow { opacity: 1; border-color: #10b981; box-shadow: 0 0 10px rgba(16,185,129,0.8); transform: scale(1.15) translateY(-2px); z-index: 10; }
  585.  
  586.         .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); }
  587.         .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; overflow-y: auto; }
  588.         .fav-item { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 8px; border-radius: 6px; border: 1px solid #334155; }
  589.         .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; }
  590.         .fav-text:hover { color: #10b981; }
  591.  
  592.         .top-shortcuts { position: fixed; top: 10px; right: 15px; z-index: 100; display: flex; gap: 10px; background: rgba(0,0,0,0.5); padding: 5px; corner-radius: 5px; }
  593.         .shortcut-btn { font-size: 20px; cursor: pointer; transition: transform 0.2s; opacity: 0.8; }
  594.         .shortcut-btn:hover { transform: scale(1.15); opacity: 1; }
  595.  
  596.         .faq-item { background: #0f172a; border: 1px solid #334155; border-radius: 6px; overflow: hidden; margin-bottom: 8px; flex-shrink: 0; }
  597.         .faq-question { width: 100%; background: #1e293b; color: #f8fafc; border: none; padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; cursor: pointer; display: flex; justify-content: space-between; align-items: center; transition: background 0.2s; outline: none; }
  598.         .faq-question:hover { background: #334155; }
  599.         .faq-question::after { content: '▼'; font-size: 10px; color: #94a3b8; transition: transform 0.2s; }
  600.         .faq-question.active::after { transform: rotate(180deg); }
  601.         .faq-answer { max-height: 0; overflow: hidden; transition: max-height 0.3s ease-out; background: #0f172a; }
  602.         .faq-answer p { margin: 0; padding: 12px 15px; font-size: 12px; color: #cbd5e1; line-height: 1.5; border-top: 1px solid #334155; }
  603.  
  604.         #xai-lightbox { cursor: zoom-out; }
  605.         #xai-lightbox-wrapper { position: relative; display: inline-block; max-width: 95vw; max-height: 95vh; }
  606.         #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); }
  607.  
  608.         .prompt-container { position: relative; width: 100%; height: 100px; min-height: 70px; margin-bottom: 10px; resize: vertical; overflow: hidden; border: 1px solid transparent; border-radius: 6px; background: rgba(0, 0, 0, 0.15); transition: 0.2s; box-sizing: border-box; font-family: 'Inter', -apple-system, sans-serif; }
  609.         .prompt-container:focus-within { border-color: rgba(255,255,255,0.1); background: rgba(0,0,0,0.25); box-shadow: none; }
  610.         .prompt-container.prompt-drag-over { border-color: #10b981 !important; background: rgba(6,78,59,0.9) !important; box-shadow: 0 0 0 2px rgba(16,185,129,0.15) !important; }
  611.         #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; }
  612.         .prompt-tag { pointer-events: auto; }
  613.         #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; }
  614.         #xai-api-prompt:focus { background: transparent; border: none; box-shadow: none; }
  615.  
  616.         .warning-box { border-radius: 6px; padding: 6px 10px; font-size: 11px; margin-bottom: 8px; font-weight: 500; display: block; }
  617.         .warning-red { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
  618.         .warning-yellow { background: #422006; color: #fcd34d; border: 1px solid #78350f; }
  619.  
  620.         #xai-version-tag { position: fixed; bottom: 12px; left: 14px; font-size: 10px; font-weight: 600; color: #475569; z-index: 100; pointer-events: none; user-select: none; background: rgba(0, 0, 0, 0.2); padding: 2px }
  621.     `;
  622.  
  623.     const UI_HTML = `
  624.         <div id="xai-pro-app">
  625.             <div class="top-shortcuts">
  626.                 <div id="xai-reset-btn" class="shortcut-btn" title="Wipe Cache & Reset Session">🗑️</div>
  627.                 <div id="help-btn" class="shortcut-btn" title="Help / FAQ">❓</div>
  628.                 <div id="logs-btn" class="shortcut-btn" title="Debug Logs">🐛</div>
  629.                 <div id="settings-btn" class="shortcut-btn" title="Studio Settings" style="transition: transform 0.2s;">⚙️</div>
  630.             </div>
  631.  
  632.             <div id="xai-version-tag">v${typeof GM_info != 'undefined' ? GM_info.script.version : "???"}</div>
  633.  
  634.             <!-- LEFT COLUMN (Collapsible) -->
  635.             <div class="col-left" id="sidebar-left">
  636.                 <div class="sidebar-inner">
  637.                     <div class="panel" style="flex-shrink: 0;">
  638.                         <div style="display: flex; background: transparent; border-radius: 0 0 6px 6px; margin-bottom: 6px; padding: 10px; padding-bottom: 0;">
  639.                             <select id="master-action" size="4" class="action-select">
  640.                                 <option value="gen_image" selected>🖼️ Generate Image</option>
  641.                                 <option value="gen_video">🎥 Generate Video</option>
  642.                                 <option value="edit_video">✂️ Edit Video</option>
  643.                                 <option value="extend_video">➡️ Extend Video</option>
  644.                             </select>
  645.                         </div>
  646.  
  647.                         <div style="padding: 10px; display: flex; flex-direction: column;">
  648.                             <div id="setting-ar" class="slider-block">
  649.                                 <div class="slider-header"><label style="margin:0;">Aspect Ratio</label></div>
  650.                                 <div class="ar-select-box" id="ar-select-box">
  651.                                     <div id="ar-selected-icon"></div>
  652.                                     <span id="ar-selected-text">Auto</span>
  653.                                 </div>
  654.                             </div>
  655.  
  656.                             <div id="setting-high-res" class="slider-block" style="flex-direction: row; justify-content: space-between; align-items: center;">
  657.                                 <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;">High Resolution</label></div>
  658.                                 <button id="high-res-btn" class="toggle-btn active">ON (2K / 720p)</button>
  659.                             </div>
  660.  
  661.                             <div id="setting-batch" class="slider-block">
  662.                                 <div class="slider-header"><label style="margin:0;">Batch Size</label> <span id="val-batch">1 Image</span></div>
  663.                                 <input type="range" id="xai-api-n" min="0" max="6" value="0">
  664.                                 <div class="slider-ticks" id="ticks-batch"></div>
  665.                             </div>
  666.  
  667.                             <div id="setting-duration" class="slider-block" style="display: none;">
  668.                                 <div class="slider-header"><label style="margin:0;">Duration</label> <span id="val-duration">5 Seconds</span></div>
  669.                                 <input type="range" id="xai-api-duration" min="0" max="14" value="4">
  670.                                 <div class="slider-ticks" id="ticks-duration"></div>
  671.                             </div>
  672.  
  673.                             <div id="setting-loops" class="slider-block" style="margin-bottom:0;">
  674.                                 <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>
  675.                                 <div style="display: flex; gap: 10px; align-items: center; margin-top: 4px;">
  676.                                     <input type="range" id="slider-loops" min="1" max="20" value="1" style="flex: 1; margin:0;">
  677.                                     <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;">
  678.                                 </div>
  679.                             </div>
  680.                         </div>
  681.                     </div>
  682.  
  683.                     <div class="panel drop-panel" id="ref-dropzone" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
  684.                         <div class="panel-title" id="ref-panel-title">Reference Media</div>
  685.                         <div style="padding: 10px; flex: 1; display: flex; flex-direction: column; overflow: hidden;">
  686.                             <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);">
  687.                                 <div style="font-size: 20px; margin-bottom: 4px;">📥</div>
  688.                                 <div style="font-size: 12px; font-weight: 600;">Drag & Drop / Ctrl+V</div>
  689.                             </div>
  690.                             <input type="file" id="xai-api-file" accept="image/*, video/mp4, video/webm" multiple style="display: none;">
  691.                             <div style="font-size: 10px; color: #94a3b8; margin-bottom: 4px; text-transform: uppercase; font-weight: bold; flex-shrink: 0;">Upload Order (Top = First)</div>
  692.                             <div id="xai-ref-list" style="flex: 1; overflow-y: auto; padding-right: 4px;"></div>
  693.                         </div>
  694.                     </div>
  695.                 </div>
  696.             </div>
  697.  
  698.             <!-- SIDEBAR TOGGLE -->
  699.             <div id="toggle-sidebar-btn" title="Toggle Sidebar">◀</div>
  700.  
  701.             <!-- CENTER COLUMN (Scrollable outputs + Floating Prompt) -->
  702.             <div class="col-center">
  703.  
  704.                 <div id="xai-current-images" class="scrollable-main">
  705.                     <div class="ready-placeholder" style="color: #94a3b8; font-size: 13px; text-align: center; margin-top: 40px; font-weight: 500;">Ready to generate. Results will appear here.</div>
  706.                 </div>
  707.  
  708.                 <div id="floating-prompt-panel" class="panel frosted-panel">
  709.                     <label style="font-size: 13px; color: #e2e8f0; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
  710.                         <span style="display: flex; align-items: center; gap: 8px;">
  711.                             <span>Prompt</span>
  712.                             <button id="fav-prompts-btn" class="btn-secondary" style="padding: 2px 8px; font-size: 10px; height: 22px; background: rgba(30,41,59,0.8);">⭐ Favorites</button>
  713.                         </span>
  714.                         <span style="font-size: 10px; font-weight: 400; color: #94a3b8;">(Drop image here for EXIF)</span>
  715.                     </label>
  716.                     <div id="warnings-container" style="display: flex; flex-direction: column; gap: 0px;"></div>
  717.                     <div id="prompt-ref-previews" style="display: flex; gap: 8px; margin-bottom: 8px; min-height: 32px; display: none;"></div>
  718.                     <div class="prompt-container">
  719.                         <div id="prompt-backdrop"></div>
  720.                         <textarea id="xai-api-prompt" placeholder="Describe what you want to see... Supports Spintax {cat|dog} and @randomseed"></textarea>
  721.                     </div>
  722.                     <div style="display: flex; align-items: center; justify-content: space-between;">
  723.                         <div id="xai-api-status" style="font-size: 12px; color: #cbd5e1; font-weight: 500;">Ready</div>
  724.                         <div style="display: flex; gap: 8px;">
  725.                             <button id="xai-preview-btn" class="btn-secondary" style="background: rgba(30,41,59,0.8);">🔍 Payload</button>
  726.                             <button id="xai-cancel-btn" class="btn-secondary" style="display: none; color: #ef4444; border-color: #ef4444; background: rgba(30,41,59,0.8);">🛑 Cancel</button>
  727.                             <button id="xai-api-generate" class="btn-primary" style="width: 120px;"><div class="btn-content">Generate</div></button>
  728.                         </div>
  729.                     </div>
  730.                 </div>
  731.             </div>
  732.  
  733.             <div id="ar-options-container"></div>
  734.  
  735.             <!-- MODALS -->
  736.             <div id="xai-lightbox" class="modal-overlay">
  737.                 <div id="xai-lightbox-wrapper">
  738.                     <img id="xai-lightbox-img" src="">
  739.                     <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>
  740.                 </div>
  741.             </div>
  742.  
  743.             <!-- LOGS MODAL -->
  744.             <div id="xai-logs-modal" class="modal-overlay">
  745.                 <div class="modal-box" style="width: 800px; max-width: 95vw; height: 80vh;">
  746.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  747.                         <h3 style="margin:0; font-size: 15px; color: #f8fafc;">🐛 Debug Logs</h3>
  748.                         <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>
  749.                     </div>
  750.                     <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>
  751.                     <div style="display: flex; gap: 8px;">
  752.                         <button id="copy-logs-btn" class="btn-primary" style="flex: 1;">📋 Copy Logs to Clipboard</button>
  753.                         <button id="clear-logs-btn" class="btn-secondary" style="flex: 1; color: #ef4444; border-color: #ef4444;">🗑️ Clear Logs</button>
  754.                     </div>
  755.                 </div>
  756.             </div>
  757.  
  758.             <!-- SETTINGS MODAL -->
  759.             <div id="xai-settings-modal" class="modal-overlay">
  760.                 <div class="modal-box" style="width: 500px;">
  761.                     <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⚙️ Studio Settings</h3>
  762.                     <div style="display:flex; gap:10px;">
  763.                         <div style="flex:1;"><label>Max Retries</label><input type="number" id="set-retries" min="1" max="100"></div>
  764.                         <div style="flex:1;"><label>Delay Min (ms)</label><input type="number" id="set-delay-min" min="500" step="500"></div>
  765.                         <div style="flex:1;"><label>Delay Max (ms)</label><input type="number" id="set-delay-max" min="1000" step="500"></div>
  766.                     </div>
  767.                     <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>
  768.                     <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>
  769.                     <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>
  770.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-auto-download" style="width: 16px; height: 16px;"><label for="set-auto-download" style="margin: 0; cursor: pointer;">Auto-Download Generated Media</label></div>
  771.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-anti-throttling" style="width: 16px; height: 16px;"><label for="set-anti-throttling" style="margin: 0; cursor: pointer;">Prevent Background Throttling (Plays silent audio)</label></div>
  772.                     <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>
  773.                     <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>
  774.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-reference-ar-trick" style="width: 16px; height: 16px;"><label for="set-reference-ar-trick" style="margin: 0; cursor: pointer;">Single reference aspect ratio fix hack.</label></div>
  775.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-maximum-greed-mode" style="width: 16px; height: 16px;"><label for="set-maximum-greed-mode" style="margin: 0; cursor: pointer;">MAXIUMUM GREED mode: reload tab on rate limit instead of waiting</label></div>
  776.                     <div style="display:flex; gap:10px; margin-top: 4px;">
  777.                         <div style="flex:1;"><label>Video Poll Timeout (s)</label><input type="number" id="set-video-timeout" min="10" step="10"></div>
  778.                         <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>
  779.                         <div style="flex:1;"><label>Base Font Size (px)</label><input type="number" id="set-font-size" min="10" max="24"></div>
  780.                     </div>
  781.                     <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;"></div>
  782.                     <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>
  783.                     <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>
  784.                     <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>
  785.                     <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;">
  786.                         <label>Custom CSS Overrides</label>
  787.                         <textarea id="set-custom-css" style="font-family: monospace; height: 60px; font-size: 11px;" placeholder="/* e.g., #xai-pro-app { background: red; } */"></textarea>
  788.                     </div>
  789.                     <div style="display: flex; gap: 8px; margin-top: 5px; border-top: 1px solid #334155; padding-top: 10px;">
  790.                         <button id="export-data-btn" class="btn-secondary" style="flex:1;">📤 Export Data</button>
  791.                         <button id="import-data-btn" class="btn-secondary" style="flex:1;">📥 Import Data</button>
  792.                         <input type="file" id="import-data-file" accept=".json" style="display: none;">
  793.                     </div>
  794.                     <div style="display: flex; gap: 8px; margin-top: 5px;">
  795.                         <button id="save-settings-btn" class="btn-primary" style="flex:1;">Save Settings</button>
  796.                         <button id="close-settings-btn" class="btn-secondary" style="flex:1;">Cancel</button>
  797.                     </div>
  798.                 </div>
  799.             </div>
  800.  
  801.             <!-- FAVORITES MODAL -->
  802.             <div id="xai-fav-modal" class="modal-overlay">
  803.                 <div class="modal-box" style="width: 550px;">
  804.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  805.                         <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⭐ Favorite Prompts</h3>
  806.                         <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>
  807.                     </div>
  808.                     <button id="add-current-fav-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);">➕ Save Current Prompt to Favorites</button>
  809.                     <div id="fav-list" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px;"></div>
  810.                 </div>
  811.             </div>
  812.  
  813.             <!-- PAYLOAD MODAL -->
  814.             <div id="xai-payload-modal" class="modal-overlay">
  815.                 <div class="modal-box" style="width: 550px;">
  816.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  817.                         <h3 style="margin:0; font-size: 15px; color: #f8fafc;">API Payload Debugger</h3>
  818.                         <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>
  819.                     </div>
  820.                     <div><label>Endpoint URL:</label><input type="text" id="payload-endpoint" style="font-family: monospace;" value="/v1/images/generations"></div>
  821.                     <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>
  822.                     <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>
  823.                     <div id="custom-payload-status" style="font-size: 11px; color: #64748b; text-align: center;">Ready</div>
  824.                 </div>
  825.             </div>
  826.             <!-- FAQ MODAL -->
  827.             <div id="xai-help-modal" class="modal-overlay">
  828.             <div class="modal-box" style="width: 600px; max-height: 85vh;">
  829.                 <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
  830.                     <h3 style="margin:0; font-size: 15px; color: #f8fafc;">❓ Help & FAQ</h3>
  831.                     <button id="close-help-btn" style="background: #ef4444; color: #fff; border: none; border-radius: 6px; padding: 4px 8px; cursor: pointer; font-weight: bold; font-size: 11px;">Close</button>
  832.                 </div>
  833.                 <div id="faq-container" style="display: flex; flex-direction: column; overflow-y: auto; padding-right: 4px;">
  834.                     <div class="faq-item">
  835.                         <button class="faq-question">I am stuck in a loop refreshing cookies. How do I fix this?</button>
  836.                         <div class="faq-answer">
  837.                             <p>This usually happens if Tampermonkey lacks permission to access and modify protected HttpOnly cookies. Without this permission, the script cannot properly wipe your session cookies.</p>
  838.                             <p>Or maybe you are in the future and the exploits are fixed.</p>
  839.                         </div>
  840.                     </div>
  841.  
  842.                     <div class="faq-item">
  843.                         <button class="faq-question">How do I use specific reference images in my prompt?</button>
  844.                             <div class="faq-answer">
  845.                             <p>First, check the "Use in Payload" box on your desired reference. A green button (e.g., <code>➕ &lt;IMAGE_0&gt;</code>) will become active next to the "Use in Payload" toggle. You can click this green button to instantly insert the correct tag into your prompt.</p>
  846.                             <p>Do note that numbering can change if more references are enabled or disabled. To verify which image a tag belongs to, look at the small preview thumbnails just above the prompt text box. Hovering your mouse over the <code>&lt;IMAGE_X&gt;</code> tag inside the prompt will highlight the matching thumbnail!</p>
  847.                         </div>
  848.                     </div>
  849.  
  850.                     <div class="faq-item">
  851.                         <button class="faq-question">Why do my generation loops stop if a single result fails?</button>
  852.                         <div class="faq-answer">
  853.                             <p>This is an intentional safeguard. If a prompt triggers a filter or is otherwise blocked, the script assumes you don't want to keep doing API calls on a prompt that will continually fail.</p>
  854.                            <p>You can disable it by unchecking the "Break loops if one iteration fails entirely" option in the settings.</p>
  855.                        </div>
  856.                    </div>
  857.                    </div>
  858.                </div>
  859.            </div>
  860.        </div>
  861.    `;
  862.  
  863.    // ─── DOM ELEMENT CACHE ───────────────────────────────────────────────────
  864.    const els = {};
  865.  
  866.    function initializeDOM() {
  867.        Object.assign(els, {
  868.            app: document.getElementById('xai-pro-app'),
  869.            prompt: document.getElementById('xai-api-prompt'),
  870.            promptBackdrop: document.getElementById('prompt-backdrop'),
  871.            warningsContainer: document.getElementById('warnings-container'),
  872.            promptContainer: document.querySelector('.prompt-container'),
  873.            action: document.getElementById('master-action'),
  874.            highResBtn: document.getElementById('high-res-btn'),
  875.            n: document.getElementById('xai-api-n'),
  876.            duration: document.getElementById('xai-api-duration'),
  877.            loopsSlider: document.getElementById('slider-loops'),
  878.            loopsNum: document.getElementById('xai-api-loops'),
  879.            settingAr: document.getElementById('setting-ar'),
  880.            settingHighRes: document.getElementById('setting-high-res'),
  881.            settingBatch: document.getElementById('setting-batch'),
  882.            settingDuration: document.getElementById('setting-duration'),
  883.            fileInput: document.getElementById('xai-api-file'),
  884.            dropzone: document.getElementById('ref-dropzone'),
  885.            uploadPlaceholder: document.getElementById('xai-upload-placeholder'),
  886.            refList: document.getElementById('xai-ref-list'),
  887.            refTitle: document.getElementById('ref-panel-title'),
  888.            btn: document.getElementById('xai-api-generate'),
  889.            previewBtn: document.getElementById('xai-preview-btn'),
  890.            cancelBtn: document.getElementById('xai-cancel-btn'),
  891.            status: document.getElementById('xai-api-status'),
  892.            currentImages: document.getElementById('xai-current-images'), // Main scroll area
  893.            reset: document.getElementById('xai-reset-btn'),
  894.            sidebar: document.getElementById('sidebar-left'),
  895.            toggleSidebarBtn: document.getElementById('toggle-sidebar-btn'),
  896.            arSelectBox: document.getElementById('ar-select-box'),
  897.            arOptionsCont: document.getElementById('ar-options-container'),
  898.            arSelectedIcon: document.getElementById('ar-selected-icon'),
  899.            arSelectedText: document.getElementById('ar-selected-text'),
  900.            lightbox: document.getElementById('xai-lightbox'),
  901.            lightboxImg: document.getElementById('xai-lightbox-img'),
  902.            lightboxDl: document.getElementById('xai-lightbox-dl'),
  903.            promptRefPreviews: document.getElementById('prompt-ref-previews'),
  904.            payloadModal: document.getElementById('xai-payload-modal'),
  905.            payloadEndpoint: document.getElementById('payload-endpoint'),
  906.            payloadCode: document.getElementById('payload-code'),
  907.            closePayloadBtn: document.getElementById('close-payload-btn'),
  908.            sendCustomBtn: document.getElementById('send-custom-payload-btn'),
  909.            customStatus: document.getElementById('custom-payload-status'),
  910.            settingsBtn: document.getElementById('settings-btn'),
  911.            settingsModal: document.getElementById('xai-settings-modal'),
  912.            closeSettingsBtn: document.getElementById('close-settings-btn'),
  913.            saveSettingsBtn: document.getElementById('save-settings-btn'),
  914.            exportDataBtn: document.getElementById('export-data-btn'),
  915.            importDataBtn: document.getElementById('import-data-btn'),
  916.            importDataFile: document.getElementById('import-data-file'),
  917.            favBtn: document.getElementById('fav-prompts-btn'),
  918.            favModal: document.getElementById('xai-fav-modal'),
  919.            closeFavBtn: document.getElementById('close-fav-btn'),
  920.            addFavBtn: document.getElementById('add-current-fav-btn'),
  921.            favList: document.getElementById('fav-list'),
  922.            logsBtn: document.getElementById('logs-btn'),
  923.            logsModal: document.getElementById('xai-logs-modal'),
  924.            closeLogsBtn: document.getElementById('close-logs-btn'),
  925.            copyLogsBtn: document.getElementById('copy-logs-btn'),
  926.            clearLogsBtn: document.getElementById('clear-logs-btn'),
  927.            logsTextarea: document.getElementById('logs-textarea'),
  928.            helpBtn: document.getElementById('help-btn'),
  929.            helpModal: document.getElementById('xai-help-modal'),
  930.            closeHelpBtn: document.getElementById('close-help-btn')
  931.        });
  932.    }
  933.  
  934.    // ─── INITIALIZATION ───────────────────────────────────────────────────────
  935.    let updateUIForEditMedia = null;
  936.    let activeDurationMap = MAPS.durGen;
  937.  
  938.    const initApp = () => {
  939.        if (!document.body) return setTimeout(initApp, 50);
  940.        const hideNode = (node) => {
  941.            if (node.nodeType === 1 && node.id !== 'xai-pro-app' && !['SCRIPT', 'STYLE', 'LINK'].includes(node.tagName)) {
  942.                node.style.display = 'none';
  943.            }
  944.        };
  945.        Array.from(document.body.children).forEach(hideNode);
  946.        new MutationObserver((mutations) => {
  947.            mutations.forEach(m => m.addedNodes.forEach(hideNode));
  948.        }).observe(document.body, { childList: true });
  949.  
  950.        if (!document.getElementById('xai-pro-app')) {
  951.            const style = document.createElement('style'); style.innerHTML = UI_CSS; document.head.appendChild(style);
  952.            const customStyle = document.createElement('style'); customStyle.id = 'xai-custom-css-block'; customStyle.innerHTML = appSettings.customCSS; document.head.appendChild(customStyle);
  953.            document.body.insertAdjacentHTML('beforeend', UI_HTML);
  954.            updateFontSize(appSettings.uiFontSize);
  955.            initializeDOM();
  956.            bindLogic();
  957.        }
  958.    };
  959.  
  960.    let referenceMedia =[];
  961.    let currentAr = localStorage.getItem('xai_api_ar') || 'Auto';
  962.    let fullPayloadMemory = {};
  963.    let currentAbortController = null;
  964.    let isRequestCancelled = false;
  965.  
  966.    // ─── INDEXEDDB MANAGER ───────────────────────────────────────────────────
  967.    const DB_NAME = 'xAIProStudioDB';
  968.    const STORE_NAME = 'refsStore';
  969.  
  970.    const DBManager = {
  971.        init: function() {
  972.            return new Promise((resolve, reject) => {
  973.                const request = indexedDB.open(DB_NAME, 1);
  974.                request.onupgradeneeded = (e) => {
  975.                    const db = e.target.result;
  976.                    if (!db.objectStoreNames.contains(STORE_NAME)) db.createObjectStore(STORE_NAME);
  977.                };
  978.                request.onsuccess = () => resolve(request.result);
  979.                request.onerror = () => reject(request.error);
  980.            });
  981.        },
  982.        setRefs: async function(data) {
  983.            const db = await this.init();
  984.            return new Promise((resolve, reject) => {
  985.                const transaction = db.transaction([STORE_NAME], 'readwrite');
  986.                const store = transaction.objectStore(STORE_NAME);
  987.                const request = store.put(data, 'refs');
  988.                request.onsuccess = () => resolve();
  989.                request.onerror = () => reject(request.error);
  990.            });
  991.        },
  992.        getRefs: async function() {
  993.            const db = await this.init();
  994.            return new Promise((resolve, reject) => {
  995.                const transaction = db.transaction([STORE_NAME], 'readonly');
  996.                const store = transaction.objectStore(STORE_NAME);
  997.                const request = store.get('refs');
  998.                request.onsuccess = () => resolve(request.result || null);
  999.                request.onerror = () => reject(request.error);
  1000.            });
  1001.        }
  1002.    };
  1003.  
  1004.    let saveRefsTimeout = null;
  1005.    function saveRefs(immediate = false) {
  1006.        const executeSave = async () => {
  1007.            try {
  1008.                const cleanRefs = referenceMedia.map(m => {
  1009.                    const copy = { ...m };
  1010.                    delete copy.blobUrl;
  1011.                    return copy;
  1012.                });
  1013.                await DBManager.setRefs(cleanRefs);
  1014.            } catch(e) { addLog('ERROR', 'Failed to save refs to IDB', e); }
  1015.        };
  1016.  
  1017.        if (saveRefsTimeout) clearTimeout(saveRefsTimeout);
  1018.        if (immediate) return executeSave();
  1019.        else saveRefsTimeout = setTimeout(executeSave, 400);
  1020.    }
  1021.  
  1022.    function findMapIndex(arr, val) {
  1023.        let idx = arr.findIndex(item => (item.v || item).toString() === val.toString());
  1024.        return idx !== -1 ? idx : 0;
  1025.    }
  1026.  
  1027.    function drawTicks(containerId, map, colorFn) {
  1028.        const cont = document.getElementById(containerId);
  1029.        if (!cont) return;
  1030.        cont.innerHTML = map.map((item, index) => {
  1031.            let val = item.v || item; let label = item.t || val;
  1032.            let color = colorFn ? colorFn(val) : '#64748b';
  1033.            let percent = map.length > 1 ? (index / (map.length - 1)) * 100 : 50;
  1034.            let offset = 8 - (percent / 100) * 16;
  1035.            return `<span style="color:${color}; left:calc(${percent}% + ${offset}px);">${label}</span>`;
  1036.        }).join('');
  1037.    }
  1038.  
  1039.    function getDurationColor(val) {
  1040.        const v = parseInt(val);
  1041.        if (v <= 8) return '#f8fafc';
  1042.        if (v <= 10) return '#94a3b8';
  1043.        return '#ef4444';
  1044.    }
  1045.  
  1046.    function syncSlider(sliderEl, textEl, mapArr, formatFn) {
  1047.        const val = mapArr[sliderEl.value];
  1048.        textEl.innerText = formatFn ? formatFn(val) : (val.l || val);
  1049.    }
  1050.  
  1051.    let isHighRes = true;
  1052.    let genSettingsTimeout = null;
  1053.    function updateGenSettingsMemory() {
  1054.        if (genSettingsTimeout) clearTimeout(genSettingsTimeout);
  1055.        genSettingsTimeout = setTimeout(() => {
  1056.            localStorage.setItem('xai_api_gen_settings', JSON.stringify({
  1057.                action: els.action.value, isHighRes: isHighRes,
  1058.                n: MAPS.batch[els.n.value], duration: activeDurationMap[els.duration.value], loops: els.loopsNum.value
  1059.            }));
  1060.        }, 300);
  1061.    }
  1062.  
  1063.    function updateWarnings() {
  1064.        els.warningsContainer.innerHTML = ''; let html = '';
  1065.        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>`;
  1066.        const action = els.action.value; const duration = activeDurationMap[els.duration.value] || 0; const activeRefs = referenceMedia.filter(m => m.active).length;
  1067.        if (action === 'gen_video') {
  1068.            if (activeRefs > 0 && duration > 10) {
  1069.                const currentAr = localStorage.getItem('xai_api_ar');
  1070.                if ( currentAr != 'Auto' && currentAr != 'By First Ref' ) {
  1071.                    html += `<div class="warning-box warning-red">⚠️ Warning: videos longer than 10 seconds seem to stretch the reference to the desired aspect ratio instead of properly resizing them. You might get better results with auto.</div>`;
  1072.                }
  1073.                if ( activeRefs > 1 ) {
  1074.                    html += `<div class="warning-box warning-red">⚠️ Warning: only the first reference is going to be used for videos longer than 10 seconds.</div>`;
  1075.                }
  1076.            }
  1077.            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>`;
  1078.         }
  1079.         els.warningsContainer.innerHTML = html;
  1080.     }
  1081.  
  1082.     function syncPromptBackdrop() {
  1083.         const val = els.prompt.value; updateWarnings();
  1084.         let html = val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  1085.         const activeRefs = referenceMedia.filter(m => m.active);
  1086.         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; });
  1087.         els.promptBackdrop.innerHTML = html.replace(/\n/g, '<br>') + '<br>';
  1088.         els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft;
  1089.     }
  1090.  
  1091.     function setPromptVal(val) {
  1092.         els.prompt.focus();
  1093.         els.prompt.setSelectionRange(0, els.prompt.value.length);
  1094.         document.execCommand('insertText', false, val);
  1095.         localStorage.setItem('xai_api_prompt', val);
  1096.         syncPromptBackdrop();
  1097.     }
  1098.  
  1099.     // ─── MODALS & AUXILIARY UI SETUP ─────────────────────────────────────────
  1100.     function renderFavList() {
  1101.         els.favList.innerHTML = '';
  1102.         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; }
  1103.         favoritePrompts.forEach((promptText, idx) => {
  1104.             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>`;
  1105.            div.querySelector('.fav-text').addEventListener('click', () => { setPromptVal(promptText); els.favModal.style.display = 'none'; });
  1106.            div.querySelector('button').addEventListener('click', () => { favoritePrompts.splice(idx, 1); localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts)); renderFavList(); });
  1107.            els.favList.appendChild(div);
  1108.        });
  1109.    }
  1110.  
  1111.    function setupModalsAndAuxUI() {
  1112.        els.logsBtn.addEventListener('click', () => { els.logsTextarea.value = formatLogsForExport(); els.logsModal.style.display = 'flex'; els.logsTextarea.scrollTop = els.logsTextarea.scrollHeight; });
  1113.        els.closeLogsBtn.addEventListener('click', () => els.logsModal.style.display = 'none');
  1114.        els.copyLogsBtn.addEventListener('click', () => { els.logsTextarea.select(); document.execCommand('copy'); alert('Logs copied to clipboard!'); });
  1115.        els.clearLogsBtn.addEventListener('click', () => { if (confirm("Clear all logs?")) { appLogs.length = 0; els.logsTextarea.value = ''; } });
  1116.  
  1117.        els.settingsBtn.addEventListener('click', () => { SettingsManager.populateUI(appSettings); els.settingsModal.style.display = 'flex'; });
  1118.        els.saveSettingsBtn.addEventListener('click', () => { appSettings = SettingsManager.saveFromUI(); document.getElementById('xai-custom-css-block').innerHTML = appSettings.customCSS; updateFontSize(appSettings.uiFontSize); updateWarnings(); els.settingsModal.style.display = 'none'; });
  1119.        els.closeSettingsBtn.addEventListener('click', () => els.settingsModal.style.display = 'none');
  1120.  
  1121.        els.exportDataBtn.addEventListener('click', () => {
  1122.            const blob = new Blob([JSON.stringify({settings: appSettings, refs: referenceMedia}, null, 2)], { type: 'application/json' });
  1123.            const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `xAI_Pro_Studio_Backup_${makeTimestamp().replace(/:/g, '-')}.json`; a.click(); URL.revokeObjectURL(url);
  1124.        });
  1125.        els.importDataBtn.addEventListener('click', () => els.importDataFile.click());
  1126.        els.importDataFile.addEventListener('change', (e) => {
  1127.            const file = e.target.files[0]; if (!file) return; const reader = new FileReader();
  1128.            reader.onload = async (evt) => {
  1129.                try {
  1130.                    const parsed = JSON.parse(evt.target.result);
  1131.                    if (parsed.settings) { appSettings = { ...appSettings, ...parsed.settings }; localStorage.setItem('xai_api_settings', JSON.stringify(appSettings)); }
  1132.                    if (parsed.refs && Array.isArray(parsed.refs)) {
  1133.                        referenceMedia = parsed.refs;
  1134.                        await saveRefs(true);
  1135.                    }
  1136.                    alert("Import successful! Page will reload."); location.reload();
  1137.                } catch(err) { alert("Failed to parse the JSON file."); }
  1138.            }; reader.readAsText(file); e.target.value = '';
  1139.        });
  1140.  
  1141.        els.favBtn.addEventListener('click', () => { renderFavList(); els.favModal.style.display = 'flex'; });
  1142.        els.closeFavBtn.addEventListener('click', () => els.favModal.style.display = 'none');
  1143.        els.addFavBtn.addEventListener('click', () => {
  1144.            const p = els.prompt.value.trim(); if (!p) return alert("Prompt is empty!"); if (favoritePrompts.includes(p)) return alert("Already in favorites!");
  1145.            favoritePrompts.unshift(p); localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts)); renderFavList();
  1146.        });
  1147.  
  1148.        els.app.addEventListener('click', (e) => {
  1149.            if (e.target && e.target.classList.contains('zoomable') && e.target.tagName === 'IMG') {
  1150.                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';
  1151.                els.lightboxDl.onclick = () => { if(e.target.closest('.current-card')) e.target.closest('.current-card').classList.add('downloaded'); };
  1152.            }
  1153.        });
  1154.        els.lightbox.addEventListener('click', (e) => { if (!e.target.closest('#xai-lightbox-dl') && !e.target.closest('.modal-box')) els.lightbox.style.display = 'none'; });
  1155.        document.addEventListener('keydown', (e) => { if(e.key === 'Escape') Array.from(document.querySelectorAll('.modal-overlay')).forEach(m => m.style.display = 'none'); });
  1156.  
  1157.        els.helpBtn.addEventListener('click', () => { els.helpModal.style.display = 'flex'; });
  1158.        els.closeHelpBtn.addEventListener('click', () => els.helpModal.style.display = 'none');
  1159.        document.querySelectorAll('.faq-question').forEach(button => {
  1160.            button.addEventListener('click', () => {
  1161.                const isActive = button.classList.contains('active');
  1162.                if (!isActive) {
  1163.                    button.classList.add('active');
  1164.                    button.nextElementSibling.style.maxHeight = button.nextElementSibling.scrollHeight + "px";
  1165.                } else {
  1166.                    button.classList.remove('active');
  1167.                    button.nextElementSibling.style.maxHeight = null;
  1168.                }
  1169.            });
  1170.        });
  1171.  
  1172.        els.toggleSidebarBtn.addEventListener('click', () => {
  1173.            els.sidebar.classList.toggle('collapsed');
  1174.            els.toggleSidebarBtn.innerText = els.sidebar.classList.contains('collapsed') ? '▶' : '◀';
  1175.        });
  1176.  
  1177.        els.reset.addEventListener('click', () => {
  1178.            if (!confirm("Wipe cache? Your prompt and settings will be saved.")) return;
  1179.            localStorage.setItem('xai_api_prompt', els.prompt.value); nuclearSessionReset();
  1180.        });
  1181.    }
  1182.  
  1183.    function renderPromptRefPreviews() {
  1184.        if (!els.promptRefPreviews) return;
  1185.        els.promptRefPreviews.innerHTML = '';
  1186.        const activeRefs = referenceMedia.filter(m => m.active);
  1187.        if (activeRefs.length === 0) {
  1188.            els.promptRefPreviews.style.display = 'none';
  1189.            return;
  1190.        }
  1191.        els.promptRefPreviews.style.display = 'flex';
  1192.        activeRefs.forEach((media, idx) => {
  1193.            const thumbSrc = media.thumb || media.blobUrl || media.base64;
  1194.            let el;
  1195.            if (thumbSrc) {
  1196.                el = document.createElement('img');
  1197.                el.src = thumbSrc;
  1198.                if (!media.isVideo) {
  1199.                    el.style.cursor = 'zoom-in';
  1200.                    el.addEventListener('click', () => {
  1201.                        els.lightboxImg.src = media.blobUrl || media.base64;
  1202.                        els.lightboxDl.href = media.blobUrl || media.base64;
  1203.                        els.lightboxDl.download = media.fileName || `Reference_${idx+1}.jpg`;
  1204.                        els.lightbox.style.display = 'flex';
  1205.                    });
  1206.                }
  1207.            } else {
  1208.                el = document.createElement('div');
  1209.                el.innerText = '🎥';
  1210.                el.style.display = 'flex'; el.style.alignItems = 'center'; el.style.justifyContent = 'center'; el.style.background = 'rgba(0,0,0,0.3)';
  1211.            }
  1212.            el.classList.add('prompt-ref-thumb');
  1213.            el.setAttribute('data-idx', idx);
  1214.            el.title = media.isVideo ? `Video (Matches <IMAGE_${idx}>)` : `Click to view (Matches <IMAGE_${idx}>)`;
  1215.            els.promptRefPreviews.appendChild(el);
  1216.        });
  1217.    }
  1218.  
  1219.    function setupPromptListeners() {
  1220.        if (localStorage.getItem('xai_api_prompt')) setPromptVal(localStorage.getItem('xai_api_prompt'));
  1221.        let promptSaveTimeout = null;
  1222.        els.prompt.addEventListener('input', () => {
  1223.            if (promptSaveTimeout) clearTimeout(promptSaveTimeout);
  1224.            promptSaveTimeout = setTimeout(() => localStorage.setItem('xai_api_prompt', els.prompt.value), 400);
  1225.            syncPromptBackdrop();
  1226.        });
  1227.        els.prompt.addEventListener('scroll', () => { els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft; });
  1228.  
  1229.        els.prompt.addEventListener('mousemove', (e) => {
  1230.            if (e.buttons !== 0) return;
  1231.            els.prompt.style.pointerEvents = 'none'; const el = document.elementFromPoint(e.clientX, e.clientY); els.prompt.style.pointerEvents = 'auto';
  1232.  
  1233.            document.querySelectorAll('.prompt-ref-thumb').forEach(t => t.classList.remove('glow'));
  1234.  
  1235.            if (el && el.classList.contains('prompt-tag')) {
  1236.                const idx = el.getAttribute('data-idx');
  1237.                const thumb = els.promptRefPreviews.querySelector(`.prompt-ref-thumb[data-idx="${idx}"]`);
  1238.                if (thumb) thumb.classList.add('glow');
  1239.            }
  1240.        });
  1241.        els.prompt.addEventListener('mouseleave', () => {
  1242.            document.querySelectorAll('.prompt-ref-thumb').forEach(t => t.classList.remove('glow'));
  1243.        });
  1244.        els.prompt.addEventListener('keydown', (e) => {
  1245.            if (e.key === 'Enter' && !e.shiftKey) {
  1246.                e.preventDefault();
  1247.                if (!els.btn.disabled) {
  1248.                    els.btn.click();
  1249.                }
  1250.            }
  1251.        });
  1252.  
  1253.        els.prompt.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.add('prompt-drag-over'); });
  1254.        els.prompt.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over'); });
  1255.        els.prompt.addEventListener('drop', async (e) => {
  1256.            e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over');
  1257.            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  1258.                const file = e.dataTransfer.files[0]; const oldVal = els.prompt.value; setPromptVal("Extracting prompt from EXIF...");
  1259.                const extractedPrompt = await extractPromptFromImage(file);
  1260.                if (extractedPrompt) setPromptVal(extractedPrompt); else { setPromptVal(oldVal); alert("No prompt found in this image's EXIF data."); }
  1261.            }
  1262.        });
  1263.    }
  1264.  
  1265.    function setupAspectRatioUI() {
  1266.        function renderArOptions() {
  1267.            els.arOptionsCont.innerHTML = '';
  1268.            arData.forEach(ar => {
  1269.                const opt = document.createElement('div'); opt.className = `ar-option${ar.imageOnly ? ' image-only-ar' : ''}`;
  1270.                opt.innerHTML = `${createArIcon(ar.w, ar.h, ar.isAuto, ar.isRef)} <span>${ar.label}</span>`;
  1271.                opt.addEventListener('click', () => { setAr(ar); els.arOptionsCont.style.display = 'none'; });
  1272.                els.arOptionsCont.appendChild(opt);
  1273.            });
  1274.        }
  1275.        function setAr(arObj) {
  1276.            currentAr = arObj.label; localStorage.setItem('xai_api_ar', currentAr);
  1277.            els.arSelectedIcon.innerHTML = createArIcon(arObj.w, arObj.h, arObj.isAuto, arObj.isRef); els.arSelectedText.innerText = arObj.label;
  1278.            updateWarnings();
  1279.        }
  1280.        renderArOptions();
  1281.        const initialAr = arData.find(a => a.label === currentAr) || arData[0];
  1282.        setAr(initialAr);
  1283.  
  1284.        els.arSelectBox.addEventListener('click', (e) => {
  1285.            e.stopPropagation(); if (els.arOptionsCont.style.display === 'grid') { els.arOptionsCont.style.display = 'none'; return; }
  1286.            const rect = els.arSelectBox.getBoundingClientRect(); els.arOptionsCont.style.top = (rect.bottom + 5) + 'px';
  1287.            els.arOptionsCont.style.left = rect.left + 'px'; els.arOptionsCont.style.width = rect.width + 'px'; els.arOptionsCont.style.display = 'grid';
  1288.            const currentAction = els.action.value;
  1289.            for ( const el of els.arOptionsCont.getElementsByClassName('image-only-ar') ) { el.style.display = currentAction === 'gen_image' ? 'flex' : 'none' }
  1290.        });
  1291.        document.addEventListener('click', (e) => { if (!els.arOptionsCont.contains(e.target)) els.arOptionsCont.style.display = 'none'; });
  1292.    }
  1293.  
  1294.    function getMaxMedia() {
  1295.        const val = els.action.value;
  1296.        return val === 'gen_image' ? 5 : (val === 'gen_video' ? 7 : 1);
  1297.    }
  1298.  
  1299.    function updateActionUI() {
  1300.        const val = els.action.value;
  1301.        if (val === 'gen_image') {
  1302.            els.settingAr.style.display = 'flex'; els.settingHighRes.style.display = 'flex'; els.settingBatch.style.display = 'flex'; els.settingDuration.style.display = 'none';
  1303.        } else if (val === 'gen_video') {
  1304.            els.settingAr.style.display = 'flex'; els.settingHighRes.style.display = 'flex'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'flex';
  1305.            activeDurationMap = MAPS.durGen; els.duration.max = activeDurationMap.length - 1;
  1306.            drawTicks('ticks-duration', activeDurationMap, getDurationColor);
  1307.            syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  1308.        } else if (val === 'edit_video') {
  1309.            els.settingAr.style.display = 'none'; els.settingHighRes.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'none';
  1310.        } else if (val === 'extend_video') {
  1311.            els.settingAr.style.display = 'none'; els.settingHighRes.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'flex';
  1312.            activeDurationMap = MAPS.durExt; els.duration.max = activeDurationMap.length - 1;
  1313.            drawTicks('ticks-duration', activeDurationMap, getDurationColor);
  1314.            syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  1315.        }
  1316.  
  1317.        const max = getMaxMedia(); els.refTitle.innerText = `Reference Media (Max Active: ${max})`;
  1318.        let activeCount = 0;
  1319.        referenceMedia.forEach(m => {
  1320.            let valid = true;
  1321.            if ((val === 'gen_image' || val === 'gen_video') && m.isVideo) valid = false;
  1322.            if ((val === 'edit_video' || val === 'extend_video') && !m.isVideo) valid = false;
  1323.            if (!valid) m.active = false; else if (m.active) { activeCount++; if (activeCount > max) m.active = false; }
  1324.        });
  1325.        renderRefList(); updateWarnings();
  1326.    }
  1327.  
  1328.    let draggedIndex = null;
  1329.    function updateRefActiveStates() {
  1330.        const actionVal = els.action.value;
  1331.        const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
  1332.        const activeRefs = referenceMedia.filter(m => m.active);
  1333.        const refNodes = Array.from(els.refList.children);
  1334.  
  1335.        referenceMedia.forEach((media, index) => {
  1336.            const item = refNodes[index];
  1337.            if (!item) return;
  1338.  
  1339.            if (media.active) item.classList.remove('inactive');
  1340.            else item.classList.add('inactive');
  1341.  
  1342.            if (!media.isVideo) {
  1343.                const insertBtn = item.querySelector('.ref-insert');
  1344.                if (insertBtn) {
  1345.                    if (disableInsert) {
  1346.                        insertBtn.disabled = true; insertBtn.style.opacity = '0.4'; insertBtn.style.filter = 'grayscale(1)'; insertBtn.style.cursor = 'not-allowed'; insertBtn.title = "Not available in this mode"; insertBtn.innerHTML = `➕ &lt;IMAGE_X&gt;`;
  1347.                    } else if (!media.active) {
  1348.                        insertBtn.disabled = true; insertBtn.style.opacity = '0.4'; insertBtn.style.filter = 'none'; insertBtn.style.cursor = 'not-allowed'; insertBtn.title = "Check 'Use in Payload' first"; insertBtn.innerHTML = `➕ &lt;IMAGE_?&gt;`;
  1349.                    } else {
  1350.                        const dynamicIndex = activeRefs.indexOf(media);
  1351.                        insertBtn.disabled = false; insertBtn.style.opacity = '1'; insertBtn.style.filter = 'none'; insertBtn.style.cursor = 'pointer'; insertBtn.title = "Insert into prompt"; insertBtn.innerHTML = `➕ &lt;IMAGE_${dynamicIndex}&gt;`;
  1352.                    }
  1353.                }
  1354.            }
  1355.        });
  1356.        updateWarnings();
  1357.    }
  1358.  
  1359.    function renderRefList() {
  1360.        els.refList.innerHTML = '';
  1361.        referenceMedia.forEach((media, index) => {
  1362.            const item = document.createElement('div'); item.className = 'ref-item'; item.draggable = true;
  1363.            const activeRefs = referenceMedia.filter(m => m.active); const dynamicIndex = media.active ? activeRefs.indexOf(media) : '?';
  1364.            const actionVal = els.action.value; const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
  1365.  
  1366.            let thumbHtml = '';
  1367.            if (media.isVideo) {
  1368.                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>`;
  1369.                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>`;
  1370.            } else thumbHtml = `<img src="${media.blobUrl || media.base64}" class="ref-thumb zoomable" data-filename="${media.fileName || 'Reference_'+(index+1)+'.jpg'}" title="${media.fileName || 'Click to view'}">`;
  1371.  
  1372.            let insertBtnHtml = '';
  1373.            if (!media.isVideo) {
  1374.                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>`;
  1375.                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>`;
  1376.                else insertBtnHtml = `<button class="ref-action-btn ref-insert" title="Insert into prompt">➕ &lt;IMAGE_${dynamicIndex}&gt;</button>`;
  1377.            }
  1378.  
  1379.            item.innerHTML = `<button class="ref-close-btn" title="Remove Media">&times;</button><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}</div></div>`;
  1380.  
  1381.            const insertBtn = item.querySelector('.ref-insert');
  1382.            if (insertBtn) {
  1383.                insertBtn.addEventListener('click', (e) => {
  1384.                    if (!media.active || insertBtn.disabled) return;
  1385.                    const currentAction = els.action.value; if (currentAction === 'edit_video' || currentAction === 'extend_video') { e.preventDefault(); return alert("<IMAGE_X> tags not supported here."); }
  1386.  
  1387.                    const dynIdx = referenceMedia.filter(m => m.active).indexOf(media);
  1388.                    const promptEl = els.prompt; const tag = `<IMAGE_${dynIdx}>`; const startPos = promptEl.selectionStart; const endPos = promptEl.selectionEnd;
  1389.  
  1390.                    setPromptVal(promptEl.value.substring(0, startPos) + tag + promptEl.value.substring(endPos, promptEl.value.length));
  1391.                    promptEl.selectionStart = promptEl.selectionEnd = startPos + tag.length; promptEl.focus();
  1392.                });
  1393.            }
  1394.            if (!media.active) item.classList.add('inactive');
  1395.  
  1396.            item.querySelector('.ref-active-toggle').addEventListener('change', (e) => {
  1397.                const max = getMaxMedia(); const currentlyActive = referenceMedia.filter(r => r.active).length;
  1398.                if (e.target.checked && currentlyActive >= max) { alert(`Up to ${max} active references allowed.`); e.target.checked = false; return; }
  1399.                media.active = e.target.checked;
  1400.                saveRefs();
  1401.                updateRefActiveStates();
  1402.                syncPromptBackdrop();
  1403.                updateWarnings();
  1404.                renderPromptRefPreviews();
  1405.            });
  1406.  
  1407.            item.addEventListener('dragstart', (e) => { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; setTimeout(() => item.classList.add('dragging'), 0); });
  1408.            item.addEventListener('dragend', () => { item.classList.remove('dragging'); draggedIndex = null; document.querySelectorAll('.ref-item').forEach(el => el.classList.remove('drag-over-top', 'drag-over-bottom')); });
  1409.            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'); } });
  1410.            item.addEventListener('dragleave', () => item.classList.remove('drag-over-top', 'drag-over-bottom'));
  1411.            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(); });
  1412.            item.querySelector('.ref-close-btn').addEventListener('click', () => {
  1413.                const removed = referenceMedia.splice(index, 1)[0];
  1414.                if (removed && removed.blobUrl) URL.revokeObjectURL(removed.blobUrl);
  1415.                renderRefList(); syncPromptBackdrop(); updateWarnings();
  1416.            });
  1417.            els.refList.appendChild(item);
  1418.        });
  1419.        saveRefs();
  1420.        renderPromptRefPreviews();
  1421.    }
  1422.  
  1423.    async function processFile(file) {
  1424.        const isVid = file.type.startsWith('video/'); const isImg = file.type.startsWith('image/');
  1425.        if (!isVid && !isImg) return;
  1426.        if (isVid && (els.action.value === 'gen_image' || els.action.value === 'gen_video')) { els.action.value = 'edit_video'; updateActionUI(); updateGenSettingsMemory(); }
  1427.        else if (isImg && (els.action.value === 'edit_video' || els.action.value === 'extend_video')) { els.action.value = 'gen_image'; updateActionUI(); updateGenSettingsMemory(); }
  1428.  
  1429.        const max = getMaxMedia(); const activeCount = referenceMedia.filter(m => m.active).length;
  1430.        let thumbBase64 = null; if (isVid) thumbBase64 = await generateVideoThumbnail(file);
  1431.  
  1432.        const blobUrl = URL.createObjectURL(file);
  1433.        const reader = new FileReader();
  1434.        reader.onload = async (event) => {
  1435.            const b64 = event.target.result;
  1436.            let w = 0, h = 0;
  1437.            if (isVid && file._w && file._h) { w = file._w; h = file._h; }
  1438.            else if (isImg) {
  1439.                try {
  1440.                    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 = blobUrl; });
  1441.                    w = dims.w; h = dims.h;
  1442.                } catch(e) {}
  1443.            }
  1444.            referenceMedia.unshift({ id: Date.now() + Math.random(), base64: b64, blobUrl: blobUrl, isVideo: isVid, active: activeCount < max, thumb: thumbBase64, fileName: file.name, w, h });
  1445.            renderRefList();
  1446.        };
  1447.        reader.readAsDataURL(file);
  1448.    }
  1449.  
  1450.    function setupMediaAndActionUI() {
  1451.        drawTicks('ticks-batch', MAPS.batch);
  1452.  
  1453.        (async () => {
  1454.            try {
  1455.                let storedRefs = await DBManager.getRefs();
  1456.                if (!storedRefs) {
  1457.                    const legacyRefs = localStorage.getItem('xai_api_refs');
  1458.                    if (legacyRefs) {
  1459.                        storedRefs = JSON.parse(legacyRefs);
  1460.                        localStorage.removeItem('xai_api_refs');
  1461.                    }
  1462.                }
  1463.                if (Array.isArray(storedRefs)) {
  1464.                    referenceMedia = storedRefs;
  1465.                    referenceMedia.forEach(m => {
  1466.                        if (m.base64) m.blobUrl = base64ToBlobUrl(m.base64);
  1467.                    });
  1468.                    updateActionUI();
  1469.                    renderRefList();
  1470.                }
  1471.            } catch(e) {}
  1472.        })();
  1473.  
  1474.        els.highResBtn.addEventListener('click', () => {
  1475.            isHighRes = !isHighRes;
  1476.            els.highResBtn.className = isHighRes ? 'toggle-btn active' : 'toggle-btn';
  1477.            els.highResBtn.innerText = isHighRes ? 'ON (2K / 720p)' : 'OFF (1K / 480p)';
  1478.            updateGenSettingsMemory();
  1479.        });
  1480.        els.n.addEventListener('input', () => { syncSlider(els.n, document.getElementById('val-batch'), MAPS.batch, v => v + (v===1?' Image':' Images')); updateGenSettingsMemory(); });
  1481.        els.duration.addEventListener('input', () => { syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds'); updateGenSettingsMemory(); updateWarnings(); });
  1482.        els.loopsSlider.addEventListener('input', e => { els.loopsNum.value = e.target.value; updateGenSettingsMemory(); });
  1483.        els.loopsNum.addEventListener('input', e => { let v = parseInt(e.target.value) || 1; els.loopsSlider.value = Math.min(v, 20); updateGenSettingsMemory(); });
  1484.  
  1485.        els.action.addEventListener('change', () => { updateActionUI(); updateGenSettingsMemory(); });
  1486.  
  1487.        try {
  1488.            const storedGen = JSON.parse(localStorage.getItem('xai_api_gen_settings') || '{}');
  1489.            if (storedGen.action) els.action.value = storedGen.action;
  1490.            updateActionUI();
  1491.  
  1492.            if (typeof storedGen.isHighRes !== 'undefined') isHighRes = storedGen.isHighRes;
  1493.            else if (storedGen.resImg === '1k' || storedGen.resVid === '480p') isHighRes = false;
  1494.  
  1495.            els.highResBtn.className = isHighRes ? 'toggle-btn active' : 'toggle-btn';
  1496.            els.highResBtn.innerText = isHighRes ? 'ON (2K / 720p)' : 'OFF (1K / 480p)';
  1497.  
  1498.            if (storedGen.n) els.n.value = findMapIndex(MAPS.batch, storedGen.n);
  1499.  
  1500.            if (storedGen.duration) { let idx = activeDurationMap.indexOf(parseInt(storedGen.duration)); els.duration.value = idx !== -1 ? idx : 0; }
  1501.            if (storedGen.loops) { els.loopsNum.value = storedGen.loops; els.loopsSlider.value = Math.min(storedGen.loops, 20); }
  1502.  
  1503.            syncSlider(els.n, document.getElementById('val-batch'), MAPS.batch, v => v + (v===1?' Image':' Images'));
  1504.            syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  1505.        } catch(e) {}
  1506.  
  1507.        updateUIForEditMedia = (mediaUrl, isVideo, fileName, actionOverride) => {
  1508.            referenceMedia.forEach(m => m.active = false);
  1509.            const blobUrl = base64ToBlobUrl(mediaUrl);
  1510.            referenceMedia.unshift({ id: Date.now() + Math.random(), base64: mediaUrl, blobUrl: blobUrl, isVideo: isVideo, active: true, thumb: isVideo ? null : blobUrl, fileName: fileName || (isVideo ? 'Edited_Video.mp4' : 'Edited_Image.png'), w:0, h:0 });
  1511.            els.action.value = actionOverride || (isVideo ? 'edit_video' : 'gen_image');
  1512.            updateActionUI(); updateGenSettingsMemory(); renderRefList(); saveRefs();
  1513.        };
  1514.  
  1515.        els.uploadPlaceholder.addEventListener('click', () => { els.fileInput.click(); });
  1516.        els.fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(processFile); els.fileInput.value = ''; });
  1517.        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()); });
  1518.        els.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); els.dropzone.classList.add('drag-over'); });
  1519.        els.dropzone.addEventListener('dragleave', () => els.dropzone.classList.remove('drag-over'));
  1520.        els.dropzone.addEventListener('drop', (e) => { e.preventDefault(); els.dropzone.classList.remove('drag-over'); if (e.dataTransfer.files) Array.from(e.dataTransfer.files).forEach(processFile); });
  1521.    }
  1522.  
  1523.    // ─── GENERATION & API CORE LOGIC ─────────────────────────────────────────
  1524.    function getMediaDimensions(base64, isVideo) {
  1525.        return new Promise(resolve => {
  1526.            if (isVideo) {
  1527.                const vid = document.createElement('video'); vid.onloadedmetadata = () => resolve({w: vid.videoWidth, h: vid.videoHeight}); vid.onerror = () => resolve({w: 0, h: 0}); vid.src = base64;
  1528.            } else {
  1529.                const img = new Image(); img.onload = () => resolve({w: img.width, h: img.height}); img.onerror = () => resolve({w: 0, h: 0}); img.src = base64;
  1530.            }
  1531.        });
  1532.    }
  1533.  
  1534.    async function buildPayloadData(dynamicPromptText) {
  1535.        const action = els.action.value; const payload = { model: action === 'gen_image' ? "grok-imagine-image" : "grok-imagine-video", prompt: dynamicPromptText };
  1536.        let ar = currentAr.toLowerCase(); const activeRefs = referenceMedia.filter(m => m.active);
  1537.  
  1538.        if (currentAr === 'By First Ref') {
  1539.            if (activeRefs.length > 0) {
  1540.                let ref = activeRefs[0];
  1541.                if (!ref.w || !ref.h) { const dims = await getMediaDimensions(ref.base64, ref.isVideo); ref.w = dims.w; ref.h = dims.h; saveRefs(); }
  1542.                if (ref.w && ref.h) {
  1543.                    const targetRatio = ref.w / ref.h; let bestMatch = '1:1'; let minDiff = Infinity;
  1544.                    arData.forEach(a => {
  1545.                        if (a.isAuto || a.isRef) return;
  1546.                        if (action === 'gen_video' && a.imageOnly ) return;
  1547.                        const r = a.w / a.h; const diff = Math.abs(r - targetRatio);
  1548.                        if (diff < minDiff) { minDiff = diff; bestMatch = a.label; }
  1549.                    });
  1550.                    ar = bestMatch.toLowerCase(); addLog('INFO', 'Calculated AR by First Ref', { targetRatio, selectedAr: ar });
  1551.                } else ar = 'auto';
  1552.            } else ar = 'auto';
  1553.        }
  1554.  
  1555.        if (action === 'gen_image') {
  1556.            payload.n = MAPS.batch[els.n.value]; payload.resolution = isHighRes ? "2k" : "1k"; payload.response_format = "b64_json";
  1557.            if (ar !== 'auto') payload.aspect_ratio = ar;
  1558.            if (activeRefs.length > 0) {
  1559.                if (activeRefs.length === 1) {
  1560.                    if (appSettings.referenceARTrick && ar != 'auto') payload.images = [{ type: "image_url", url: activeRefs[0].base64 }, { type: "image_url", url: activeRefs[0].base64 }];
  1561.                    else payload.image = { url: activeRefs[0].base64 };
  1562.                }
  1563.                else payload.images = activeRefs.map(m => ({ type: "image_url", url: m.base64 }));
  1564.            }
  1565.        } else if (action === 'gen_video') {
  1566.            payload.duration = activeDurationMap[els.duration.value]; payload.resolution = isHighRes ? "720p" : "480p";
  1567.            if (['3:4', '4:3', '9:16', '16:9', '2:3', '3:2'].includes(ar)) payload.aspect_ratio = ar;
  1568.            if ( activeRefs.length > 0 ) {
  1569.                if ( payload.duration > 10 ) {
  1570.                    payload.image = { url: activeRefs[0].base64 };
  1571.                } else {
  1572.                    if (activeRefs.length === 1) {
  1573.                        if (appSettings.referenceARTrick && ar != 'auto') {
  1574.                            payload.reference_images = [{ type: "image_url", url: activeRefs[0].base64 }, { type: "image_url", url: activeRefs[0].base64 }];
  1575.                        }
  1576.                        else {
  1577.                            payload.image = { url: activeRefs[0].base64 };
  1578.                        }
  1579.                    }
  1580.                    else {
  1581.                        payload.reference_images = activeRefs.map(m => ({ url: m.base64 }));
  1582.                    }
  1583.                }
  1584.            }
  1585.        } else if (action === 'edit_video') {
  1586.            if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  1587.        } else if (action === 'extend_video') {
  1588.            payload.duration = activeDurationMap[els.duration.value];
  1589.            if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  1590.        }
  1591.        return payload;
  1592.    }
  1593.  
  1594.    function injectBase64(editedObj, originalObj) {
  1595.        if (!editedObj || typeof editedObj !== 'object') return;
  1596.        for (let key in editedObj) {
  1597.            if (typeof editedObj[key] === 'string' && editedObj[key] === '[BASE64_TRUNCATED_FOR_PREVIEW]') { if (originalObj && originalObj[key]) editedObj[key] = originalObj[key]; }
  1598.            else if (typeof editedObj[key] === 'object') injectBase64(editedObj[key], originalObj ? originalObj[key] : null);
  1599.        }
  1600.    }
  1601.  
  1602.    function updateStatusText( text, color, className ) {
  1603.        els.status.innerText = text;
  1604.        els.status.style.color = color || "#cbd5e1";
  1605.        if (className !== undefined) els.status.className = className;
  1606.    }
  1607.  
  1608.    async function executeGenerationSingle(endpoint, payload, isImageAction, statusEl, currentLoop, totalLoops, galleryEl) {
  1609.        let loopPrefix = totalLoops > 1 ? `[Run ${currentLoop}/${totalLoops}] ` : '';
  1610.        updateStatusText(`${loopPrefix}Processing request...`, "", 'status-pulsing');
  1611.        addLog('INFO', `Starting generation loop ${currentLoop}/${totalLoops}`, { endpoint, isImageAction });
  1612.        currentAbortController = new AbortController(); let attempts = 0; let success = false; let rateLimitFails = 0;
  1613.  
  1614.        try {
  1615.            while (attempts < appSettings.retries && !success && !isRequestCancelled) {
  1616.                try {
  1617.                    updateStatusText(`${loopPrefix}Sending request to xAI...`);
  1618.                    const fullEndpoint = getApiUrl(endpoint);
  1619.                    addLog('NETWORK_REQ', `POST ${fullEndpoint}`, payload);
  1620.                    const response = await fetch(fullEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal: currentAbortController.signal });
  1621.  
  1622.                    if (response.status === 503 || response.status === 500 || response.status === 502) {
  1623.                        attempts++;
  1624.                        updateStatusText(`${loopPrefix}Busy (Error ${response.status}). Retrying... [${attempts}/${appSettings.retries}]`);
  1625.                        addLog('WARN', `Gateway error ${response.status}. Retrying.`);
  1626.                        await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin); continue; }
  1627.                    if (response.status === 401 || response.status === 403) {
  1628.                        updateStatusText(`${loopPrefix}Session Expired (${response.status}). Requesting new cookies...`, "", "#d97706");
  1629.                        await nuclearSessionReset();
  1630.                        await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin); continue;
  1631.                    }
  1632.                    if (!response.ok) {
  1633.                        let errMsg = `HTTP ${response.status}`; let errData = null;
  1634.                        try { errData = await response.json(); addLog('NETWORK_ERR', `Response error JSON`, { status: response.status, data: errData });
  1635.                            if (errData.error && errData.error.message) errMsg += `\n${errData.error.message}`; else if (errData.error && typeof errData.error === 'string') errMsg += `\n${errData.error}`;
  1636.                            if (errData.code) errMsg += `\nCode: ${errData.code}`; if (errData.detail) errMsg += `\n${typeof errData.detail === 'string' ? errData.detail : JSON.stringify(errData.detail)}`;
  1637.                        } catch(e) { addLog('NETWORK_ERR', `Failed to parse error response`, { status: response.status }); }
  1638.                        throw new Error(errMsg);
  1639.                    }
  1640.  
  1641.                    const data = await response.json(); addLog('NETWORK_RES', `Successful response`, data);
  1642.  
  1643.                    if (isImageAction) {
  1644.                        if (data && data.data && Array.isArray(data.data)) {
  1645.                            success = true;
  1646.                            updateStatusText( `${loopPrefix}Processing final images...`, "#10b981", "" );
  1647.                            await Promise.all(data.data.map((imgObj, index) => processAndRenderImage(imgObj, payload.prompt, index + 1, data.data.length, galleryEl)));
  1648.                            updateStatusText( "Ready", "#cbd5e1" );
  1649.                        } else throw new Error("Invalid response format.");
  1650.                    } else {
  1651.                        const reqId = data.request_id; if (!reqId) throw new Error(data.error ? (data.error.message || JSON.stringify(data.error)) : "No Request ID returned.");
  1652.                        let videoReady = false; let pollCount = 0; const MAX_POLLS = Math.max(1, Math.ceil(appSettings.videoPollTimeout / 5));
  1653.                        while (!videoReady && !isRequestCancelled) {
  1654.                            pollCount++; if (pollCount > MAX_POLLS) throw new Error("Timeout: Video likely dropped by filters or stuck in queue."); await sleep(5000); if (isRequestCancelled) break;
  1655.                            addLog('POLL_REQ', `Polling video ID: ${reqId}`, { pollCount, MAX_POLLS });
  1656.                            const pollRes = await fetch(getApiUrl(`/v1/videos/${reqId}`), { signal: currentAbortController.signal });
  1657.                            if (!pollRes.ok) {
  1658.                                if (pollRes.status === 401 || pollRes.status === 403) {
  1659.                                    addLog('POLL_WARN', `Poll got 401/403. Cross-tab wipe likely. Restoring...`);
  1660.                                    updateStatusText(`${loopPrefix}Polling interrupted (401). Restoring session...`);
  1661.                                    try { await fetch('https://console.x.ai/playground/imagine', { credentials: 'include', cache: 'no-store' }); } catch(e) {} await sleep(3000); continue;
  1662.                                 }
  1663.                                 if (pollRes.status >= 400 && pollRes.status < 500) {
  1664.                                     let errData; try { errData = await pollRes.json(); } catch(e) {} addLog('POLL_ERR', `Poll failed HTTP ${pollRes.status}`, errData);
  1665.                                     if (pollRes.status === 404) throw new Error("video lost (404). Session wiped by another tab.");
  1666.                                     if (errData && errData.error) throw new Error(typeof errData.error.message === 'string' ? errData.error.message : JSON.stringify(errData.error));
  1667.                                 }
  1668.                                 continue;
  1669.                             }
  1670.                             const pollData = await pollRes.json(); addLog('POLL_RES', `Poll Result`, pollData);
  1671.                             if (pollData.error) throw new Error(`API Error: ${pollData.error.message || JSON.stringify(pollData.error)}`);
  1672.                             const state = (pollData.status || pollData.state || 'processing').toLowerCase(); let progressText = typeof pollData.progress === 'number' ? ` ${pollData.progress}%` : "";
  1673.                             updateStatusText(`${loopPrefix}Polling video (Status: ${state}${progressText})...[${pollCount}/${MAX_POLLS}]`);
  1674.  
  1675.                             if (state === 'done' || state === 'completed') {
  1676.                                 videoReady = true;
  1677.                                 success = true;
  1678.                                 updateStatusText("Ready", "#cbd5e1", "")
  1679.                                 renderVideoToGallery(pollData.video.url, payload.prompt, galleryEl);
  1680.                             } else if (['failed', 'expired', 'rejected', 'blocked', 'moderated', 'nsfw'].includes(state) || pollData.is_sensitive) {
  1681.                                 if (pollData.video && pollData.video.url) {
  1682.                                     videoReady = true;
  1683.                                     success = true;
  1684.                                     updateStatusText(`${loopPrefix}Warning: Flagged as ${state}, but recovered!`, "#d97706", "")
  1685.                                     renderVideoToGallery(pollData.video.url, payload.prompt, galleryEl);
  1686.                                     addLog('WARN', `Video flagged but recovered`, pollData);
  1687.                                 } else throw new Error(`Generation halted. Reason: ${state}`);
  1688.                             }
  1689.                         }
  1690.                     }
  1691.                } catch (err) {
  1692.                     const errStr = err.message.toLowerCase(); addLog('ERROR', `Generation logic exception`, { message: err.message });
  1693.                     if (err.name === 'AbortError' || isRequestCancelled) {
  1694.                         updateStatusText("Request Cancelled.", "#ef4444", "");
  1695.                         return false;
  1696.                     }
  1697.                     let isLongRateLimit = false; let isShortRateLimit = false;
  1698.                     if (errStr.includes("requests per second (actual/limit)")) {
  1699.                         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+)/);
  1700.                         if (minMatch && minMatch[1] === minMatch[2]) isLongRateLimit = true; else if (secMatch && secMatch[1] === secMatch[2]) isShortRateLimit = true; else isLongRateLimit = true;
  1701.                     } else if (errStr.includes("rate limit") || errStr.includes("resource has been exhausted") || errStr.includes("http 429") || errStr.includes("http 422")) isLongRateLimit = true;
  1702.  
  1703.                     if (isShortRateLimit || isLongRateLimit) {
  1704.                         if (appSettings.maximumGreedMode) {
  1705.                             updateStatusText(`${loopPrefix}Rate Limit Hit (429). Refreshing tab...`, "#ef4444", "" );
  1706.                             await nuclearSessionReset(totalLoops - currentLoop + 1); const u = new URL(window.location.href.split('?')[0]); u.searchParams.set('_rst', Date.now()); window.location.replace(u.toString()); await sleep(10000);
  1707.                         } else {
  1708.                             updateStatusText(`${loopPrefix}Rate Limit Hit (429). Resetting cookies...`);
  1709.                             await nuclearSessionReset();
  1710.                             if (isShortRateLimit) {
  1711.                                 attempts++; if (attempts >= appSettings.retries) {
  1712.                                     updateStatusText(`${loopPrefix}Failed: Max retries reached after per-second rate limits.`, "#ef4444", "");
  1713.                                     break;
  1714.                                 }
  1715.                                 await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin);
  1716.                             } else {
  1717.                                 attempts++;
  1718.                                 if (attempts >= appSettings.retries) {
  1719.                                     updateStatusText(`${loopPrefix}Failed: Max retries reached after rate limits.`, "#ef4444", "");
  1720.                                     break;
  1721.                                 }
  1722.                                 let delaySeconds = parseInt(appSettings.rateLimitDelay) || 60; let countdown = delaySeconds;
  1723.                                 if ((rateLimitFails++) < 1) { await sleep(1000); continue; }
  1724.                                 rateLimitFails = 0; toggleKeepAwake(true);
  1725.                                 while(countdown > 0 && !isRequestCancelled) {
  1726.                                     updateStatusText(`${loopPrefix}Rate Limit Hit. Retrying in ${countdown}s... [${attempts}/${appSettings.retries}]`);
  1727.                                     await sleep(1000); countdown--;
  1728.                                 }
  1729.                                 toggleKeepAwake(false);
  1730.                             }
  1731.                             if (isRequestCancelled) return false; continue;
  1732.                         }
  1733.                     } else if (errStr.includes("video lost") || ((errStr.includes("timeout: video") || errStr.includes("generation halted.") || errStr.includes("video rejected")) && appSettings.autoRetryStuckVideo)) {
  1734.                         attempts++;
  1735.                         if (attempts >= appSettings.retries) {
  1736.                             updateStatusText(`${loopPrefix}Failed: Max retries reached for stuck video.`, "#ef4444", "");
  1737.                             break;
  1738.                         }
  1739.                         updateStatusText(`${loopPrefix}Video Stuck/Failed. Auto-retrying... [${attempts}/${appSettings.retries}]`);
  1740.                         await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin);
  1741.                         if (payload.prompt) payload.prompt += "\u200B"; continue;
  1742.                     } else {
  1743.                         updateStatusText(`${loopPrefix}Error: ${err.message}`, "#ef4444", "");
  1744.                         break;
  1745.                     }
  1746.                 }
  1747.             }
  1748.         } finally { toggleKeepAwake(false); }
  1749.  
  1750.         if (!success && !isRequestCancelled) {
  1751.             if (!statusEl.innerText.includes("Failed:") && !statusEl.innerText.includes("Error:") && !statusEl.innerText.includes("Reloading")) updateStatusText( `${loopPrefix}Failed after ${attempts} retries.` );
  1752.             updateStatusText( statusEl.innerText, "#ef4444", "" );
  1753.             return false;
  1754.         }
  1755.         return success;
  1756.     }
  1757.  
  1758.     function createBatchContainer(promptStr) {
  1759.         const batchContainer = document.createElement('div');
  1760.         batchContainer.className = 'batch-container';
  1761.         const ts = makeTimestamp();
  1762.         batchContainer.innerHTML = `
  1763.             <div class="batch-header" title="Click to copy prompt to input">
  1764.                 <span>${ts}</span>
  1765.                 <span style="font-weight: normal; opacity: 0.8; font-style: italic; max-width: 65%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="${promptStr.replace(/"/g, '&quot;')}">${promptStr}</span>
  1766.            </div>
  1767.            <div class="batch-grid"></div>
  1768.        `;
  1769.        batchContainer.querySelector('.batch-header').addEventListener('click', () => {
  1770.            setPromptVal(promptStr);
  1771.        });
  1772.  
  1773.        const placeholder = els.currentImages.querySelector('.ready-placeholder');
  1774.        if (placeholder) placeholder.remove();
  1775.  
  1776.        els.currentImages.prepend(batchContainer);
  1777.        return batchContainer.querySelector('.batch-grid');
  1778.    }
  1779.  
  1780.    function setupGenerationUI() {
  1781.        els.previewBtn.addEventListener('click', async () => {
  1782.            els.previewBtn.disabled = true; els.previewBtn.innerHTML = `<div class="loading-spinner" style="border-top-color:#64748b; width:12px; height:12px;"></div>`;
  1783.            fullPayloadMemory = await buildPayloadData(parseDynamicPrompt(els.prompt.value.trim()));
  1784.            const displayP = JSON.parse(JSON.stringify(fullPayloadMemory)); const trunc = "[BASE64_TRUNCATED_FOR_PREVIEW]";
  1785.            if (displayP.image) { if (Array.isArray(displayP.image)) displayP.image.forEach(img => (img.url = trunc)); else displayP.image.url = trunc; }
  1786.            if (displayP.images && Array.isArray(displayP.images)) displayP.images.forEach(img => (img.url = trunc));
  1787.            if (displayP.reference_images && Array.isArray(displayP.reference_images)) displayP.reference_images.forEach(img => (img.url = trunc));
  1788.            if (displayP.video) displayP.video.url = trunc;
  1789.            const activeRefs = referenceMedia.filter(m => m.active); let endpoint = '/v1/images/generations';
  1790.            if (els.action.value === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1791.            else if (els.action.value === 'gen_video') endpoint = '/v1/videos/generations';
  1792.            else if (els.action.value === 'edit_video') endpoint = '/v1/videos/edits';
  1793.            else if (els.action.value === 'extend_video') endpoint = '/v1/videos/extensions';
  1794.            els.payloadEndpoint.value = endpoint; els.payloadCode.value = JSON.stringify(displayP, null, 2); els.payloadModal.style.display = 'flex';
  1795.            els.previewBtn.innerHTML = `🔍 Payload`; els.previewBtn.disabled = false;
  1796.        });
  1797.  
  1798.        els.closePayloadBtn.addEventListener('click', () => els.payloadModal.style.display = 'none');
  1799.  
  1800.        els.sendCustomBtn.addEventListener('click', async () => {
  1801.            initAudio(); let customPayload; try { customPayload = JSON.parse(els.payloadCode.value); } catch(e) { return alert("Invalid JSON format in textarea!"); }
  1802.            injectBase64(customPayload, fullPayloadMemory);
  1803.            const endpoint = els.payloadEndpoint.value.trim(); const isImage = customPayload.model === "grok-imagine-image";
  1804.  
  1805.            const currentBatchGrid = createBatchContainer("Custom Payload Execution");
  1806.  
  1807.            els.sendCustomBtn.disabled = true; els.sendCustomBtn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Processing...</div>`; isRequestCancelled = false;
  1808.            const ok = await executeGenerationSingle(endpoint, customPayload, isImage, els.customStatus, 1, 1, currentBatchGrid);
  1809.  
  1810.            if (currentBatchGrid.children.length === 0) {
  1811.                currentBatchGrid.parentElement.remove();
  1812.                if (els.currentImages.children.length === 0) els.currentImages.innerHTML = `<div class="ready-placeholder" style="color: #94a3b8; font-size: 13px; text-align: center; margin-top: 40px; font-weight: 500;">Ready to generate. Results will appear here.</div>`;
  1813.            }
  1814.  
  1815.            els.sendCustomBtn.disabled = false; els.sendCustomBtn.innerHTML = `<div class="btn-content">🚀 Send Custom Payload</div>`; if (ok) notifyUser(false); else notifyUser(true);
  1816.        });
  1817.  
  1818.        els.cancelBtn.addEventListener('click', () => {
  1819.            isRequestCancelled = true; if (currentAbortController) currentAbortController.abort(); toggleKeepAwake(false);
  1820.            els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex'; els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1821.            els.status.innerText = "Request Cancelled."; els.status.className = ""; els.status.style.color = "#ef4444";
  1822.        });
  1823.  
  1824.        els.btn.addEventListener('click', async () => {
  1825.            initAudio(); const basePrompt = els.prompt.value.trim(); if (!basePrompt) return alert("Please enter a prompt.");
  1826.            addLog('UI', 'Generate button clicked', { basePrompt });
  1827.  
  1828.            const action = els.action.value; const activeRefs = referenceMedia.filter(m => m.active);
  1829.            let endpoint = '/v1/images/generations';
  1830.            if (action === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1831.            else if (action === 'gen_video') endpoint = '/v1/videos/generations';
  1832.            else if (action === 'edit_video') endpoint = '/v1/videos/edits';
  1833.            else if (action === 'extend_video') endpoint = '/v1/videos/extensions';
  1834.  
  1835.            const isImage = action === 'gen_image'; const totalLoops = parseInt(els.loopsNum.value) || 1;
  1836.            els.btn.disabled = true; els.cancelBtn.style.display = 'flex'; els.previewBtn.style.display = 'none'; isRequestCancelled = false;
  1837.  
  1838.            const currentBatchGrid = createBatchContainer(basePrompt);
  1839.  
  1840.            let allSuccess = true;
  1841.            for (let i = 1; i <= totalLoops; i++) {
  1842.                if (isRequestCancelled) break; const dynamicPrompt = parseDynamicPrompt(basePrompt);
  1843.                els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Building...</div>`;
  1844.                const payload = await buildPayloadData(dynamicPrompt);
  1845.                els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Gen ${i}/${totalLoops}...</div>`;
  1846.                const ok = await executeGenerationSingle(endpoint, payload, isImage, els.status, i, totalLoops, currentBatchGrid);
  1847.                if (!ok) { allSuccess = false; if (appSettings.breakLoopOnFailure) break; }
  1848.            }
  1849.  
  1850.            if (currentBatchGrid.children.length === 0) {
  1851.                currentBatchGrid.parentElement.remove();
  1852.                if (els.currentImages.children.length === 0) els.currentImages.innerHTML = `<div class="ready-placeholder" style="color: #94a3b8; font-size: 13px; text-align: center; margin-top: 40px; font-weight: 500;">Ready to generate. Results will appear here.</div>`;
  1853.            }
  1854.  
  1855.            if (!isRequestCancelled) {
  1856.                els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex'; els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1857.                if (allSuccess) { els.status.innerText = "All runs complete."; els.status.className = ""; els.status.style.color = "#cbd5e1"; notifyUser(false); addLog('INFO', 'All generation loops completed successfully'); }
  1858.                else { notifyUser(true); addLog('ERROR', 'Generation sequence ended with errors'); }
  1859.            }
  1860.        });
  1861.    }
  1862.  
  1863.    function checkAutoResume() {
  1864.        const resumeLoops = sessionStorage.getItem('xai_resume_loops');
  1865.        if (resumeLoops) {
  1866.            sessionStorage.removeItem('xai_resume_loops'); const loops = parseInt(resumeLoops);
  1867.            if (loops > 0) {
  1868.                els.loopsNum.value = loops; els.loopsSlider.value = Math.min(loops, 20); updateGenSettingsMemory();
  1869.                els.status.innerText = `Auto-resuming ${loops} runs...`; els.status.className = "status-pulsing";
  1870.                setTimeout(() => { if (!els.btn.disabled) els.btn.click(); }, 2500);
  1871.            }
  1872.        }
  1873.    }
  1874.  
  1875.    function bindLogic() {
  1876.        setupModalsAndAuxUI();
  1877.        setupPromptListeners();
  1878.        setupAspectRatioUI();
  1879.        setupMediaAndActionUI();
  1880.        setupGenerationUI();
  1881.        checkAutoResume();
  1882.    }
  1883.  
  1884.    async function processAndRenderImage(imgObj, originalPrompt, num, total, galleryEl) {
  1885.        if (!imgObj.b64_json) return;
  1886.        const mime = imgObj.mime_type || "image/png"; const b64 = imgObj.b64_json; const pngDataUri = `data:${mime};base64,${b64}`;
  1887.        const finalPrompt = imgObj.revised_prompt || originalPrompt; let finalDataUri = pngDataUri; let filename = `Grok 2K - ${makeTimestamp().replace(/:/g, '-')} - ${num}of${total}.png`;
  1888.        if (!appSettings.saveAsPng) { finalDataUri = await convertToJpegWithExif(pngDataUri, finalPrompt); filename = `Grok 2K - ${makeTimestamp().replace(/:/g, '-')} - ${num}of${total}.jpg`; }
  1889.        const card = document.createElement('div'); card.className = 'current-card';
  1890.        card.innerHTML = `
  1891.            <div class="img-wrapper">
  1892.                <img src="${finalDataUri}" class="zoomable" data-filename="${filename}" title="Click to view fullscreen">
  1893.                <a href="${finalDataUri}" download="${filename}" class="overlay-btn overlay-dl-btn" title="Download Full File">${DOWNLOAD_ICON}</a>
  1894.                <button class="overlay-btn overlay-edit-btn" title="Edit this Image">${EDIT_ICON}</button>
  1895.                <button class="overlay-btn overlay-video-btn" title="Make Video">${VIDEO_ICON}</button>
  1896.            </div>
  1897.            <div class="prompt-dropdown" title="Click to copy prompt">${finalPrompt}</div>`;
  1898.  
  1899.        card.querySelector('.prompt-dropdown').addEventListener('click', () => setPromptVal(finalPrompt));
  1900.        card.querySelector('.overlay-edit-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(finalDataUri, false, filename, 'gen_image'); });
  1901.        card.querySelector('.overlay-video-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(finalDataUri, false, filename, 'gen_video'); });
  1902.  
  1903.        const dlBtn = card.querySelector('.overlay-dl-btn');
  1904.        dlBtn.addEventListener('click', () => { card.classList.add('downloaded'); });
  1905.  
  1906.        galleryEl.prepend(card);
  1907.  
  1908.        if (appSettings.autoDownload) {
  1909.            setTimeout(() => {
  1910.                GM_download({ url: finalDataUri, name: filename, saveAs: false });
  1911.                card.classList.add('downloaded');
  1912.            }, 500);
  1913.        }
  1914.    }
  1915.  
  1916.    let lastVideoVolume = 1.0;
  1917.    let lastVideoMuted = null;
  1918.    function renderVideoToGallery(videoUrl, originalPrompt, galleryEl) {
  1919.        if (lastVideoMuted === null) lastVideoMuted = appSettings.videoMuted;
  1920.        const filename = `Grok Video - ${makeTimestamp().replace(/:/g, '-')}.mp4`; const auto = appSettings.videoAutoplay ? "autoplay" : ""; const muted = appSettings.videoMuted ? "muted" : "";
  1921.        const card = document.createElement('div'); card.className = 'current-card';
  1922.        card.innerHTML = `
  1923.            <div class="img-wrapper">
  1924.                <video src="${videoUrl}" controls ${auto} loop style="width: 100%; max-height: 50vh; object-fit: contain; background: #000;"></video>
  1925.                <button class="overlay-btn overlay-dl-btn force-dl" data-url="${videoUrl}" data-filename="${filename}" title="Download MP4">${DOWNLOAD_ICON}</button>
  1926.                <button class="overlay-btn overlay-edit-btn" title="Edit this Video">${EDIT_ICON}</button>
  1927.                <button class="overlay-btn overlay-extend-btn" title="Extend this Video">${EXTEND_ICON}</button>
  1928.            </div>
  1929.            <div class="prompt-dropdown" title="Click to copy prompt">${originalPrompt}</div>`;
  1930.  
  1931.        card.querySelector('.prompt-dropdown').addEventListener('click', () => setPromptVal(originalPrompt));
  1932.  
  1933.        const vidEl = card.querySelector('video');
  1934.        vidEl.volume = lastVideoVolume;
  1935.        vidEl.muted = lastVideoMuted;
  1936.        vidEl.addEventListener('volumechange', (e) => {
  1937.            lastVideoVolume = e.target.volume;
  1938.            lastVideoMuted = e.target.muted;
  1939.        });
  1940.  
  1941.        card.querySelector('.overlay-edit-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename, 'edit_video'); });
  1942.        card.querySelector('.overlay-extend-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename, 'extend_video'); });
  1943.  
  1944.        const dlBtn = card.querySelector('.overlay-dl-btn');
  1945.        dlBtn.addEventListener('click', (e) => {
  1946.            e.preventDefault(); const url = dlBtn.getAttribute('data-url'); const fname = dlBtn.getAttribute('data-filename'); const originalIcon = dlBtn.innerHTML;
  1947.            dlBtn.innerHTML = '<div class="loading-spinner" style="border-top-color: #10b981;"></div>'; dlBtn.style.pointerEvents = 'none'; card.classList.add('downloaded');
  1948.            if (typeof GM_xmlhttpRequest !== "undefined") {
  1949.                GM_xmlhttpRequest({ method: 'GET', url: url, responseType: 'blob', onload: function(response) {
  1950.                        if (response.status >= 200 && response.status < 300) {
  1951.                            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);
  1952.                        } else window.open(url, '_blank');
  1953.                        dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto';
  1954.                    }, onerror: function() { window.open(url, '_blank'); dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto'; } });
  1955.            } else { window.open(url, '_blank'); dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto'; }
  1956.        });
  1957.  
  1958.        galleryEl.prepend(card);
  1959.  
  1960.        if (appSettings.autoDownload) {
  1961.            setTimeout(() => {
  1962.                GM_download({ url: videoUrl, name: filename, saveAs: false });
  1963.                card.classList.add('downloaded');
  1964.            }, 500);
  1965.        }
  1966.    }
  1967.  
  1968.    if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initApp); } else { initApp(); }
  1969. })();
Add Comment
Please, Sign In to add comment