Guest User

Untitled

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