Make the UI/UX better. Make it more visually appealing. Handle all of the edge cases. Improve the quality of the whole code. Make the UI/UX even better. Don't hold back. Don't compromise. Don't use any framework. Make the whole code better as possible. Improve all aspects of this whole code. improve anything that can be improved. If everything is improved then improve it even further. Focus on all aspects as many times you want just to make it perfect. ensure all of the ui elements are placed correctly. Send the full improved codes with breaking any functionalities. 
----
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta 
          name="viewport" 
          content="width=device-width, initial-scale=1.0"
    >
    <meta 
          name="description" 
          content="Advanced Image Generation using AI models"
    >
    <title>Advanced Image Generation</title>
    
    <!-- Font Awesome for Icons -->
    <link 
          rel="stylesheet" 
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
          
          crossorigin="anonymous" 
          referrerpolicy="no-referrer" 
    />
    
    <!-- Google Fonts -->
    <link 
          rel="preconnect" 
          href="https://fonts.googleapis.com"
    >
    <link 
          rel="preconnect" 
          href="https://fonts.gstatic.com" 
          crossorigin
    >
    <link 
          href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" 
          rel="stylesheet"
    >
    
    <style>
        /* CSS Variables for Theming */
        :root {
            --primary-color: #4a90e2;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
            --background-color: var(--light-color);
            --text-color: var(--dark-color);
            --border-radius: 8px;
            --transition-duration: 0.3s;
            --max-width: 1000px;
        }

        /* Dark Theme Overrides */
        .dark-theme {
            --background-color: #121212;
            --text-color: var(--light-color);
            --primary-color: #8ab4f8;
            --secondary-color: #b0bec5;
        }

        /* Global Reset and Base Styles */
        *,
        *::before,
        *::after {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 20px;
            font-family: 'Roboto', sans-serif;
            background-color: var(--background-color);
            color: var(--text-color);
            transition: background-color var(--transition-duration), color var(--transition-duration);
            display: flex;
            justify-content: center;
            min-height: 100vh;
        }

        .container {
            max-width: var(--max-width);
            width: 100%;
        }

        /* Header Styles */
        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            position: relative;
        }

        header h1 {
            font-size: 2.5rem;
            color: var(--primary-color);
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        }

        .theme-toggle {
            font-size: 1.8rem;
            cursor: pointer;
            color: var(--primary-color);
            transition: color var(--transition-duration);
        }

        /* Form Styles */
        form {
            background-color: rgba(255, 255, 255, 0.1);
            padding: 25px 30px;
            border-radius: var(--border-radius);
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            transition: transform var(--transition-duration), box-shadow var(--transition-duration);
        }

        form:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
        }

        fieldset {
            border: none;
            margin-bottom: 20px;
        }

        legend {
            font-size: 1.5rem;
            margin-bottom: 10px;
            color: var(--primary-color);
            font-weight: 700;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: var(--text-color);
        }

        input[type="text"],
        input[type="password"],
        input[type="number"],
        textarea,
        select {
            width: 100%;
            padding: 12px;
            border: 1px solid var(--secondary-color);
            border-radius: var(--border-radius);
            background-color: var(--background-color);
            color: var(--text-color);
            font-size: 1rem;
            transition: border-color var(--transition-duration), box-shadow var(--transition-duration);
        }

        input[type="text"]:focus,
        input[type="password"]:focus,
        input[type="number"]:focus,
        textarea:focus,
        select:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 0.2rem rgba(74, 144, 226, 0.25);
        }

        textarea {
            resize: vertical;
        }

        .enhance-prompt {
            display: flex;
            align-items: center;
            margin-top: 10px;
        }

        .enhance-prompt input {
            margin-right: 10px;
        }

        .button-group {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        button {
            flex: 1;
            background-color: var(--primary-color);
            color: #fff;
            padding: 12px 20px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 1rem;
            transition: background-color var(--transition-duration), transform var(--transition-duration);
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }

        button:hover {
            background-color: #3578c7;
            transform: translateY(-2px);
        }

        button i {
            margin-right: 8px;
        }

        .secondary-button {
            background-color: var(--secondary-color);
            color: #fff;
        }

        .secondary-button:hover {
            background-color: #5a6268;
        }

        .danger-button {
            background-color: var(--danger-color);
        }

        .danger-button:hover {
            background-color: #c82333;
        }

        /* Loading and Progress Bar */
        .loading-container {
            display: none;
            align-items: center;
            margin-top: 15px;
        }

        .loading-text {
            margin-right: 10px;
            font-weight: 500;
        }

        .loading-spinner {
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-top: 4px solid var(--primary-color);
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .progress-bar-container {
            display: none;
            width: 100%;
            background-color: var(--secondary-color);
            border-radius: var(--border-radius);
            overflow: hidden;
            margin-top: 15px;
        }

        .progress-bar {
            height: 6px;
            background-color: var(--primary-color);
            width: 0%;
            transition: width 0.3s ease;
        }

        /* Image Container */
        .image-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
            gap: 20px;
            margin-top: 25px;
        }

        .image-wrapper {
            position: relative;
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            transition: transform var(--transition-duration), box-shadow var(--transition-duration);
        }

        .image-wrapper:hover {
            transform: scale(1.02);
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
        }

        .image-wrapper img {
            width: 100%;
            display: block;
            cursor: pointer;
            transition: transform var(--transition-duration);
        }

        .image-wrapper img:hover {
            transform: scale(1.05);
        }

        .image-icons {
            position: absolute;
            bottom: 10px;
            right: 10px;
            display: flex;
            gap: 8px;
        }

        .image-icons i {
            background-color: rgba(0, 0, 0, 0.6);
            padding: 6px;
            border-radius: 50%;
            color: #fff;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color var(--transition-duration), transform var(--transition-duration);
        }

        .image-icons i:hover {
            background-color: var(--primary-color);
            transform: scale(1.1);
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.85);
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .modal-content {
            position: relative;
            max-width: 90%;
            max-height: 90%;
            border-radius: var(--border-radius);
            overflow: hidden;
        }

        .modal-content img {
            width: 100%;
            height: auto;
            display: block;
        }

        .modal-prompt {
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.7);
            color: #fff;
            padding: 8px 12px;
            border-radius: var(--border-radius);
            max-width: 90%;
            text-align: center;
            font-size: 0.9rem;
        }

        .close-modal {
            position: absolute;
            top: 10px;
            right: 10px;
            color: #fff;
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            transition: color var(--transition-duration);
        }

        .close-modal:hover {
            color: var(--danger-color);
        }

        /* History Container */
        .history-container {
            display: none;
            background-color: rgba(255, 255, 255, 0.1);
            padding: 20px 25px;
            border-radius: var(--border-radius);
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            margin-top: 25px;
            transition: transform var(--transition-duration), box-shadow var(--transition-duration);
        }

        .history-container:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 35px rgba(0, 0, 0, 0.2);
        }

        .history-container h2 {
            color: var(--primary-color);
            margin-bottom: 15px;
            font-size: 1.8rem;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
        }

        .delete-history-btn {
            background-color: var(--danger-color);
            margin-top: 15px;
            width: 100%;
        }

        /* Toast Notification */
        .toast {
            visibility: hidden;
            min-width: 250px;
            max-width: 350px;
            margin: 0 auto;
            background-color: rgba(50, 50, 50, 0.95);
            color: #fff;
            text-align: center;
            border-radius: var(--border-radius);
            padding: 14px 20px;
            position: fixed;
            z-index: 1001;
            left: 50%;
            bottom: 30px;
            transform: translateX(-50%);
            transition: opacity 0.5s ease, visibility 0.5s;
            font-size: 1rem;
        }

        .toast.show {
            visibility: visible;
            opacity: 1;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            header h1 {
                font-size: 2rem;
            }

            form, .history-container {
                padding: 20px;
            }

            .button-group {
                flex-direction: column;
            }

            .image-container {
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
                gap: 15px;
            }
        }

        @media (max-width: 480px) {
            header h1 {
                font-size: 1.8rem;
            }

            .theme-toggle {
                font-size: 1.5rem;
            }

            .button-group button {
                font-size: 0.9rem;
                padding: 10px;
            }

            .image-container {
                grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>Advanced Image Generation</h1>
            <button 
                    class="theme-toggle" 
                    id="themeToggle" 
                    aria-label="Toggle Dark/Light Theme"
            >
                <i class="fas fa-adjust"></i>
            </button>
        </header>

        <main>
            <form 
                  id="imageForm" 
                  aria-label="Image Generation Form" 
                  novalidate
            >
                <fieldset>
                    <legend>API Configuration</legend>
                    <div class="form-group">
                        <label for="apiKey">API Key <span aria-hidden="true" style="color: var(--danger-color);">*</span></label>
                        <div style="display: flex; gap: 10px;">
                            <input 
                                   type="password" 
                                   id="apiKey" 
                                   name="apiKey" 
                                   required 
                                   placeholder="Enter your API Key" 
                                   aria-required="true"
                                   aria-describedby="apiKeyHelp"
                            >
                            <a 
                               href="https://t.me/AbhiBotsBot" 
                               target="_blank" 
                               rel="noopener noreferrer" 
                               class="secondary-button" 
                               style="flex: none;"
                               aria-label="Get API Key via Telegram"
                            >
                                <i class="fab fa-telegram"></i> Get API Key
                            </a>
                        </div>
                        <small id="apiKeyHelp" style="color: var(--secondary-color);">Your API Key is required to generate images.</small>
                    </div>
                </fieldset>

                <fieldset>
                    <legend>Image Parameters</legend>
                    <div class="form-group">
                        <label for="modelId">Model <span aria-hidden="true" style="color: var(--danger-color);">*</span></label>
                        <select 
                                id="modelId" 
                                name="modelId" 
                                required 
                                aria-required="true"
                        >
                            <option value="" disabled selected>Select a model</option>
                            <option value="flux">Flux</option>
                            <option value="midjourney">Stable Diffusion v4</option>
                            <option value="sdxlceshi">Stable Diffusion XL</option>
                            <option value="anything-v3">Anything V3</option>
                            <option value="sdxl">SDXL 1.0</option>
                            <option value="realistic-vision-v13">Realistic Vision V1.3</option>
                            <option value="anything-v4">Anything V4</option>
                            <option value="anything-v5">Anything V5</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="prompt">Prompt <span aria-hidden="true" style="color: var(--danger-color);">*</span></label>
                        <textarea 
                                  id="prompt" 
                                  name="prompt" 
                                  rows="4" 
                                  required 
                                  placeholder="Describe the image you want to generate" 
                                  aria-required="true"
                        ></textarea>
                    </div>

                    <div class="form-group">
                        <label for="negativePrompt">Negative Prompt</label>
                        <textarea 
                                  id="negativePrompt" 
                                  name="negativePrompt" 
                                  rows="3" 
                                  placeholder="Describe what you DON'T want in the image"
                        ></textarea>
                    </div>

                    <div class="form-group">
                        <label for="size">Size <i class="fas fa-ruler-combined" title="Select image size"></i></label>
                        <select 
                                id="size" 
                                name="size" 
                                required 
                                aria-required="true"
                        >
                            <option value="1024x1024">Square (1024x1024)</option>
                            <option value="1024x768">Landscape (1024x768)</option>
                            <option value="768x1024">Portrait (768x1024)</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="samples">Samples <span aria-hidden="true" style="color: var(--danger-color);">*</span></label>
                        <input 
                               type="number" 
                               id="samples" 
                               name="samples" 
                               value="1" 
                               min="1" 
                               max="4" 
                               required 
                               aria-required="true"
                        >
                    </div>

                    <div class="form-group">
                        <label for="steps">Inference Steps <span aria-hidden="true" style="color: var(--danger-color);">*</span></label>
                        <input 
                               type="number" 
                               id="steps" 
                               name="steps" 
                               value="30" 
                               min="1" 
                               max="150" 
                               required 
                               aria-required="true"
                        >
                    </div>

                    <div class="form-group">
                        <label for="guidanceScale">Guidance Scale <span aria-hidden="true" style="color: var(--danger-color);">*</span></label>
                        <input 
                               type="number" 
                               id="guidanceScale" 
                               name="guidanceScale" 
                               value="7.5" 
                               step="0.1" 
                               min="1" 
                               max="20" 
                               required 
                               aria-required="true"
                        >
                    </div>

                    <div class="form-group">
                        <label for="scheduler">Scheduler <span aria-hidden="true" style="color: var(--danger-color);">*</span></label>
                        <select 
                                id="scheduler" 
                                name="scheduler" 
                                required 
                                aria-required="true"
                        >
                            <option value="" disabled selected>Select a scheduler</option>
                            <option value="UniPCMultistepScheduler">UniPCMultistepScheduler</option>
                            <option value="LMSDiscreteScheduler">LMSDiscreteScheduler</option>
                            <option value="DDIMScheduler">DDIMScheduler</option>
                            <option value="EulerDiscreteScheduler">EulerDiscreteScheduler</option>
                            <option value="PNDMScheduler">PNDMScheduler</option>
                            <option value="DPMSolverMultistepScheduler">DPMSolverMultistepScheduler</option>
                        </select>
                    </div>

                    <div class="enhance-prompt">
                        <input 
                               type="checkbox" 
                               id="enhancePrompt" 
                               name="enhancePrompt"
                        >
                        <label for="enhancePrompt">Enhance Image</label>
                    </div>
                </fieldset>

                <div class="button-group">
                    <button type="submit" aria-label="Generate Image">
                        <i class="fas fa-image"></i> Generate
                    </button>
                    <button 
                            type="button" 
                            id="clearButton" 
                            class="secondary-button" 
                            aria-label="Clear All Fields"
                    >
                        <i class="fas fa-eraser"></i> Clear All
                    </button>
                    <button 
                            type="button" 
                            id="historyButton" 
                            class="secondary-button" 
                            aria-label="View Image History"
                    >
                        <i class="fas fa-history"></i> History
                    </button>
                </div>
            </form>

            <!-- Loading Indicator -->
            <div 
                 id="loading" 
                 class="loading-container" 
                 aria-live="polite" 
                 aria-busy="true"
            >
                <div class="loading-text">Generating image...</div>
                <div class="loading-spinner" role="status" aria-hidden="true"></div>
            </div>

            <!-- Progress Bar -->
            <div 
                 id="progressBarContainer" 
                 class="progress-bar-container" 
                 aria-hidden="true"
            >
                <div 
                     id="progressBar" 
                     class="progress-bar" 
                     role="progressbar" 
                     aria-valuenow="0" 
                     aria-valuemin="0" 
                     aria-valuemax="100"
                ></div>
            </div>

            <!-- Result Display -->
            <div 
                 id="result" 
                 class="result" 
                 aria-live="polite"
            ></div>

            <!-- Image Gallery -->
            <div 
                 class="image-container" 
                 id="imageContainer"
                 aria-label="Generated Images Gallery"
            ></div>

            <!-- Image History -->
            <div 
                 id="historyContainer" 
                 class="history-container" 
                 aria-hidden="true"
            >
                <h2>Image History</h2>
                <div 
                     id="historyImages" 
                     class="image-container" 
                     aria-label="Image History Gallery"
                ></div>
                <button 
                        class="danger-button" 
                        id="deleteHistoryButton" 
                        aria-label="Clear Image History"
                >
                    <i class="fas fa-trash"></i> Clear History
                </button>
            </div>

            <!-- Image Modal -->
            <div 
                 id="imageModal" 
                 class="modal" 
                 role="dialog" 
                 aria-modal="true" 
                 aria-labelledby="modalTitle" 
                 aria-describedby="modalDesc"
            >
                <div class="modal-content">
                    <button 
                            class="close-modal" 
                            aria-label="Close Image Modal"
                            id="closeModal"
                    >
                        &times;
                    </button>
                    <img 
                         id="modalImage" 
                         src="" 
                         alt="Full Size Generated Image"
                    >
                    <div 
                         class="modal-prompt" 
                         id="modalPrompt" 
                         aria-live="polite"
                    ></div>
                </div>
            </div>

            <!-- Toast Notification -->
            <div 
                 id="toast" 
                 class="toast" 
                 role="status" 
                 aria-live="polite" 
                 aria-atomic="true"
            ></div>
        </main>
    </div>
    
    <!-- Dexie.js for IndexedDB -->
    <script 
            src="https://unpkg.com/dexie@latest/dist/dexie.js"
            crossorigin="anonymous"
    ></script>
    <script>
    (() => {
        'use strict';

        // Constants
        const MAX_HISTORY_SIZE = 30;
        const RETRY_DELAY = 2000;
        const MAX_RETRIES = 3;
        const TOAST_DISPLAY_TIME = 3000;

        // Initialize IndexedDB using Dexie
        const db = new Dexie("ImageGenerationDB");
        db.version(1).stores({
            preferences: '++id, apiKey, modelId, prompt, negativePrompt, width, height, samples, steps, guidanceScale, scheduler, enhancePrompt, theme',
            images: '++id, url, timestamp, prompt'
        });

        // Cache DOM Elements
        const elements = {
            apiKey: document.getElementById('apiKey'),
            modelId: document.getElementById('modelId'),
            prompt: document.getElementById('prompt'),
            negativePrompt: document.getElementById('negativePrompt'),
            size: document.getElementById('size'),
            samples: document.getElementById('samples'),
            steps: document.getElementById('steps'),
            guidanceScale: document.getElementById('guidanceScale'),
            scheduler: document.getElementById('scheduler'),
            enhancePrompt: document.getElementById('enhancePrompt'),
            form: document.getElementById('imageForm'),
            loading: document.getElementById('loading'),
            progressBarContainer: document.getElementById('progressBarContainer'),
            progressBar: document.getElementById('progressBar'),
            imageContainer: document.getElementById('imageContainer'),
            historyContainer: document.getElementById('historyContainer'),
            historyImages: document.getElementById('historyImages'),
            historyButton: document.getElementById('historyButton'),
            deleteHistoryButton: document.getElementById('deleteHistoryButton'),
            clearButton: document.getElementById('clearButton'),
            modal: document.getElementById('imageModal'),
            modalImage: document.getElementById('modalImage'),
            modalPrompt: document.getElementById('modalPrompt'),
            closeModal: document.getElementById('closeModal'),
            toast: document.getElementById('toast'),
            themeToggle: document.getElementById('themeToggle')
        };

        // Queue Management
        const requestQueue = [];
        let currentRequest = null;

        // Cloudflare Worker URLs
        const cloudflareWorkerUrls = [
            'https://shy.gebep49539.workers.dev/https://api.abhibhai.com/api/v6/images/text2img'
        ];

        // Utility Functions
        const showToast = (message) => {
            elements.toast.textContent = message;
            elements.toast.classList.add('show');
            setTimeout(() => elements.toast.classList.remove('show'), TOAST_DISPLAY_TIME);
        };

        const logError = (message, error) => {
            console.error(message, error);
            showToast(message);
        };

        const debounce = (func, delay) => {
            let timeoutId;
            return (...args) => {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => func.apply(this, args), delay);
            };
        };

        const toggleTheme = () => {
            document.body.classList.toggle('dark-theme');
            savePreferences();
        };

        const preventBodyScroll = (prevent) => {
            document.body.style.overflow = prevent ? 'hidden' : 'auto';
        };

        // Theme Handling
        elements.themeToggle.addEventListener('click', toggleTheme);

        // Load Theme Preference
        const loadTheme = async () => {
            try {
                const pref = await db.preferences.get(1);
                if (pref && pref.theme) {
                    document.body.classList.toggle('dark-theme', pref.theme === 'dark');
                }
            } catch (error) {
                logError("Failed to load theme preference.", error);
            }
        };

        // Save Preferences
        const savePreferences = debounce(async () => {
            try {
                const size = elements.size.value.split('x').map(Number);
                const preferences = {
                    apiKey: elements.apiKey.value.trim(),
                    modelId: elements.modelId.value,
                    prompt: elements.prompt.value.trim(),
                    negativePrompt: elements.negativePrompt.value.trim(),
                    width: size[0] || 1024,
                    height: size[1] || 1024,
                    samples: parseInt(elements.samples.value, 10) || 1,
                    steps: parseInt(elements.steps.value, 10) || 30,
                    guidanceScale: parseFloat(elements.guidanceScale.value) || 7.5,
                    scheduler: elements.scheduler.value,
                    enhancePrompt: elements.enhancePrompt.checked,
                    theme: document.body.classList.contains('dark-theme') ? 'dark' : 'light'
                };
                await db.preferences.put(preferences, 1);
            } catch (error) {
                logError("Failed to save preferences.", error);
            }
        }, 300);

        // Load Preferences
        const loadPreferences = async () => {
            try {
                const preferences = await db.preferences.get(1);
                if (preferences) {
                    elements.apiKey.value = preferences.apiKey || '';
                    elements.modelId.value = preferences.modelId || '';
                    elements.prompt.value = preferences.prompt || '';
                    elements.negativePrompt.value = preferences.negativePrompt || '';
                    elements.size.value = `${preferences.width || 1024}x${preferences.height || 1024}`;
                    elements.samples.value = preferences.samples || 1;
                    elements.steps.value = preferences.steps || 30;
                    elements.guidanceScale.value = preferences.guidanceScale || 7.5;
                    elements.scheduler.value = preferences.scheduler || '';
                    elements.enhancePrompt.checked = preferences.enhancePrompt || false;
                    showToast("Preferences loaded successfully!");
                }
            } catch (error) {
                logError("Failed to load preferences.", error);
            }
        };

        // Form Input Event Listeners for Saving Preferences
        Object.values(elements).forEach(element => {
            if (element && ['INPUT', 'SELECT', 'TEXTAREA'].includes(element.tagName)) {
                element.addEventListener('input', savePreferences);
                element.addEventListener('change', savePreferences);
            }
        });

        // Validate Form Inputs
        const validateForm = () => {
            const requiredFields = elements.form.querySelectorAll('[required]');
            for (let field of requiredFields) {
                if (!field.value.trim()) {
                    field.classList.add('error');
                    return false;
                } else {
                    field.classList.remove('error');
                }
            }
            return true;
        };

        // Handle Form Submission
        elements.form.addEventListener('submit', async (e) => {
            e.preventDefault();
            if (!validateForm()) {
                showToast("Please fill in all required fields.");
                return;
            }
            showLoading(true);
            enqueueRequest();
        });

        // Enqueue API Request
        const enqueueRequest = () => {
            const payload = generatePayload();
            requestQueue.push({ payload, attempt: 0 });
            processQueue();
        };

        // Generate Payload from Form Inputs
        const generatePayload = () => {
            const size = elements.size.value.split('x').map(Number);
            return {
                api_key: elements.apiKey.value.trim(),
                model_id: elements.modelId.value,
                prompt: elements.prompt.value.trim(),
                negative_prompt: elements.negativePrompt.value.trim(),
                width: size[0] || 1024,
                height: size[1] || 1024,
                samples: parseInt(elements.samples.value, 10) || 1,
                num_inference_steps: parseInt(elements.steps.value, 10) || 30,
                guidance_scale: parseFloat(elements.guidanceScale.value) || 7.5,
                scheduler: elements.scheduler.value,
                enhance_prompt: elements.enhancePrompt.checked
            };
        };

        // Process Request Queue
        const processQueue = async () => {
            if (currentRequest || requestQueue.length === 0) return;

            const { payload, attempt } = requestQueue.shift();
            currentRequest = new AbortController();

            try {
                await makeRequest(payload, attempt, currentRequest.signal);
            } catch (error) {
                logError("Request processing failed.", error);
            } finally {
                currentRequest = null;
                processQueue();
            }
        };

        // Make API Request
        const makeRequest = async (payload, attempt, signal) => {
            if (attempt >= MAX_RETRIES) {
                showToast("Failed to generate images after multiple attempts.");
                showLoading(false);
                return;
            }

            const url = cloudflareWorkerUrls[attempt % cloudflareWorkerUrls.length];

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload),
                    signal
                });

                if (!response.ok) throw new Error(`Server responded with status ${response.status}`);

                const data = await handleStreamResponse(response);
                await handleImageResponse(data.output, payload.prompt);
                showToast("Images generated successfully!");
            } catch (error) {
                if (error.name !== 'AbortError') {
                    logError(`Attempt ${attempt + 1} failed: ${error.message}`, error);
                    requestQueue.push({ payload, attempt: attempt + 1 });
                    setTimeout(() => processQueue(), RETRY_DELAY);
                }
            } finally {
                if (requestQueue.length === 0) {
                    showLoading(false);
                }
            }
        };

        // Handle Streamed Response
        const handleStreamResponse = async (response) => {
            const reader = response.body.getReader();
            let receivedLength = 0;
            const chunks = [];
            const contentLength = parseInt(response.headers.get('Content-Length')) || 0;

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;
                chunks.push(value);
                receivedLength += value.length;
                updateProgressBar((receivedLength / contentLength) * 100);
            }

            const chunksAll = new Uint8Array(receivedLength);
            let position = 0;
            for (const chunk of chunks) {
                chunksAll.set(chunk, position);
                position += chunk.length;
            }

            return JSON.parse(new TextDecoder('utf-8').decode(chunksAll));
        };

        // Update Progress Bar
        const updateProgressBar = (percentage) => {
            elements.progressBar.style.width = `${percentage}%`;
            elements.progressBar.setAttribute('aria-valuenow', percentage.toFixed(0));
        };

        // Show or Hide Loading Indicators
        const showLoading = (isLoading) => {
            elements.loading.style.display = isLoading ? 'flex' : 'none';
            elements.progressBarContainer.style.display = isLoading ? 'block' : 'none';
            if (!isLoading) {
                elements.progressBar.style.width = '0%';
                elements.progressBar.setAttribute('aria-valuenow', '0');
            }
        };

        // Handle API Response Images
        const handleImageResponse = async (images, prompt) => {
            if (Array.isArray(images) && images.length > 0) {
                for (let imageUrl of images) {
                    await addImage(imageUrl, prompt);
                }
            } else {
                throw new Error("No images returned from the API.");
            }
        };

        // Add Image to Gallery and IndexedDB
        const addImage = async (url, prompt) => {
            try {
                // Prevent Duplicate Images
                const existing = await db.images.where('url').equals(url).first();
                if (existing) return;

                // Create Image Wrapper
                const imgWrapper = createImageWrapper(url, prompt);
                elements.imageContainer.prepend(imgWrapper);

                // Add to IndexedDB
                await db.images.add({
                    url,
                    timestamp: new Date(),
                    prompt
                });

                // Manage History Size
                await manageHistorySize();
            } catch (error) {
                logError("Failed to add image.", error);
            }
        };

        // Create Image Wrapper Element
        const createImageWrapper = (url, prompt) => {
            const wrapper = document.createElement('div');
            wrapper.classList.add('image-wrapper');

            const img = document.createElement('img');
            img.src = url;
            img.alt = prompt || "Generated Image";
            img.loading = "lazy";
            img.onerror = () => {
                wrapper.remove();
                logError("Failed to load image.", url);
            };
            img.addEventListener('click', () => openModal(url, prompt));

            const icons = createImageIcons(url, prompt);
            wrapper.appendChild(img);
            wrapper.appendChild(icons);

            return wrapper;
        };

        // Create Image Action Icons
        const createImageIcons = (url, prompt) => {
            const iconsContainer = document.createElement('div');
            iconsContainer.classList.add('image-icons');

            // Download Icon
            const downloadIcon = document.createElement('i');
            downloadIcon.classList.add('fas', 'fa-download');
            downloadIcon.title = "Download Image";
            downloadIcon.addEventListener('click', (e) => {
                e.stopPropagation();
                downloadImage(url);
            });

            // Share Icon
            const shareIcon = document.createElement('i');
            shareIcon.classList.add('fas', 'fa-share-alt');
            shareIcon.title = "Copy Image URL";
            shareIcon.addEventListener('click', (e) => {
                e.stopPropagation();
                copyToClipboard(url, "Image URL copied!");
            });

            // Copy Prompt Icon
            const copyPromptIcon = document.createElement('i');
            copyPromptIcon.classList.add('fas', 'fa-copy');
            copyPromptIcon.title = "Copy Prompt";
            copyPromptIcon.addEventListener('click', (e) => {
                e.stopPropagation();
                copyToClipboard(prompt, "Prompt copied!");
            });

            // Delete Icon
            const deleteIcon = document.createElement('i');
            deleteIcon.classList.add('fas', 'fa-trash');
            deleteIcon.title = "Delete Image";
            deleteIcon.addEventListener('click', async (e) => {
                e.stopPropagation();
                await deleteImage(url, wrapper);
            });

            iconsContainer.appendChild(downloadIcon);
            iconsContainer.appendChild(shareIcon);
            iconsContainer.appendChild(copyPromptIcon);
            iconsContainer.appendChild(deleteIcon);

            return iconsContainer;
        };

        // Download Image
        const downloadImage = (url) => {
            const link = document.createElement('a');
            link.href = url;
            link.download = 'generated-image.png';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };

        // Copy Text to Clipboard
        const copyToClipboard = async (text, successMessage) => {
            try {
                await navigator.clipboard.writeText(text);
                showToast(successMessage);
            } catch {
                // Fallback for older browsers
                const textarea = document.createElement('textarea');
                textarea.value = text;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                showToast(successMessage);
            }
        };

        // Delete Image from Gallery and IndexedDB
        const deleteImage = async (url, wrapper) => {
            if (!confirm("Are you sure you want to delete this image?")) return;
            try {
                const image = await db.images.where('url').equals(url).first();
                if (image) {
                    await db.images.delete(image.id);
                    wrapper.remove();
                    showToast("Image deleted successfully.");
                }
            } catch (error) {
                logError("Failed to delete image.", error);
            }
        };

        // Manage History Size
        const manageHistorySize = async () => {
            try {
                const count = await db.images.count();
                if (count > MAX_HISTORY_SIZE) {
                    const oldest = await db.images.orderBy('timestamp').limit(count - MAX_HISTORY_SIZE).toArray();
                    const ids = oldest.map(img => img.id);
                    await db.images.bulkDelete(ids);
                }
            } catch (error) {
                logError("Failed to manage history size.", error);
            }
        };

        // Show or Hide Image History
        elements.historyButton.addEventListener('click', async () => {
            const isVisible = elements.historyContainer.style.display === 'block';
            elements.historyContainer.style.display = isVisible ? 'none' : 'block';
            if (!isVisible) {
                await loadHistory();
            }
        });

        // Load History from IndexedDB
        const loadHistory = async () => {
            try {
                elements.historyImages.innerHTML = '';
                const images = await db.images.orderBy('timestamp').reverse().toArray();
                if (images.length === 0) {
                    elements.historyImages.innerHTML = '<p style="color: var(--secondary-color);">No history available.</p>';
                    return;
                }
                const fragment = document.createDocumentFragment();
                images.forEach(img => {
                    const imgWrapper = createImageWrapper(img.url, img.prompt);
                    fragment.appendChild(imgWrapper);
                });
                elements.historyImages.appendChild(fragment);
            } catch (error) {
                logError("Failed to load image history.", error);
            }
        };

        // Delete Entire History
        elements.deleteHistoryButton.addEventListener('click', async () => {
            if (!confirm("Are you sure you want to delete all image history?")) return;
            try {
                await db.images.clear();
                elements.historyImages.innerHTML = '<p style="color: var(--secondary-color);">History cleared.</p>';
                showToast("All image history deleted.");
            } catch (error) {
                logError("Failed to delete image history.", error);
            }
        });

        // Clear Form Fields
        elements.clearButton.addEventListener('click', () => {
            if (!confirm("Are you sure you want to clear all fields?")) return;
            elements.form.reset();
            showToast("Form cleared.");
        });

        // Open Modal with Image
        const openModal = (url, prompt) => {
            elements.modalImage.src = url;
            elements.modalPrompt.textContent = prompt || '';
            elements.modal.style.display = 'flex';
            preventBodyScroll(true);
        };

        // Close Modal
        const closeModal = () => {
            elements.modal.style.display = 'none';
            elements.modalImage.src = '';
            elements.modalPrompt.textContent = '';
            preventBodyScroll(false);
        };

        elements.closeModal.addEventListener('click', closeModal);
        window.addEventListener('click', (e) => {
            if (e.target === elements.modal) {
                closeModal();
            }
        });
        window.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                closeModal();
            }
        });

        // Handle Network Status
        window.addEventListener('offline', () => showToast("You are offline. Please check your internet connection."));
        window.addEventListener('online', () => showToast("You are back online."));

        // Initialize Application
        const init = async () => {
            await loadTheme();
            await loadPreferences();
        };

        // Call Initialization
        init();

    })();
</script>
</body>
</html>