Guest User

Untitled

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