Transform this whole code into the best version it can be in all areas. Send the fully working full code. -- <!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 href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #6200ea;
            --primary-light: #9d46ff;
            --primary-dark: #0a00b6;
            --secondary-color: #03dac6;
            --secondary-light: #66fff9;
            --secondary-dark: #00a896;
            --background-color: #f5f5f5;
            --background-dark: #121212;
            --surface-color: #ffffff;
            --surface-dark: #1e1e1e;
            --error-color: #b00020;
            --text-color: #000000;
            --text-light: #ffffff;
            --border-radius: 12px;
            --transition-duration: 0.3s;
            --max-width: 1200px;
            --box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            --font-family: 'Roboto', sans-serif;
        }

        .dark-theme {
            --background-color: #121212;
            --surface-color: #1e1e1e;
            --text-color: #e0e0e0;
            --text-light: #ffffff;
            --box-shadow: 0 4px 6px rgba(255,255,255,0.1);
        }

        *, *::before, *::after {
            box-sizing: border-box;
        }

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

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

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }

        header h1 {
            font-size: 2.5rem;
            color: var(--primary-color);
            margin: 0;
            transition: color var(--transition-duration);
        }

        main {
            width: 100%;
        }

        form {
            background-color: var(--surface-color);
            padding: 30px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            transition: transform var(--transition-duration), box-shadow var(--transition-duration);
            width: 100%;
        }

        form:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
        }

        fieldset {
            border: none;
            margin-bottom: 25px;
            padding: 0;
        }

        legend {
            font-size: 1.6rem;
            margin-bottom: 20px;
            color: var(--primary-color);
            font-weight: 500;
            border-bottom: 2px solid var(--primary-light);
            padding-bottom: 5px;
        }

        .form-group {
            margin-bottom: 20px;
            display: flex;
            flex-direction: column;
        }

        label {
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-color);
            transition: color var(--transition-duration);
        }

        input[type="text"],
        input[type="password"],
        input[type="number"],
        textarea,
        select {
            padding: 12px 16px;
            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"]::placeholder,
        input[type="password"]::placeholder,
        input[type="number"]::placeholder,
        textarea::placeholder,
        select::placeholder {
            color: var(--secondary-color);
        }

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

        textarea {
            resize: vertical;
            min-height: 100px;
        }

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

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

        .button-group {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin-top: 25px;
        }

        button {
            flex: 1;
            background-color: var(--primary-color);
            color: var(--text-light);
            padding: 14px 20px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: background-color var(--transition-duration), transform var(--transition-duration);
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: var(--box-shadow);
        }

        button:hover {
            background-color: var(--primary-light);
            transform: translateY(-3px);
        }

        button:active {
            transform: translateY(0);
            box-shadow: var(--box-shadow);
        }

        button:focus {
            outline: 2px solid var(--secondary-color);
        }

        button i {
            margin-right: 8px;
        }

        .secondary-button {
            background-color: var(--secondary-color);
            color: var(--text-light);
            text-decoration: none;
            padding: 14px 20px;
            border-radius: var(--border-radius);
            transition: background-color var(--transition-duration), transform var(--transition-duration);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            box-shadow: var(--box-shadow);
            cursor: pointer;
        }

        .secondary-button:hover {
            background-color: var(--secondary-light);
            transform: translateY(-3px);
        }

        .secondary-button:active {
            transform: translateY(0);
            box-shadow: var(--box-shadow);
        }

        .secondary-button:focus {
            outline: 2px solid var(--secondary-color);
        }

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

        .danger-button:hover {
            background-color: #cf6679;
            transform: translateY(-3px);
        }

        .danger-button:active {
            transform: translateY(0);
            box-shadow: var(--box-shadow);
        }

        .danger-button:focus {
            outline: 2px solid var(--secondary-color);
        }

        .loading-container {
            display: none;
            align-items: center;
            margin-top: 15px;
            padding: 10px 20px;
            background-color: var(--surface-color);
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
        }

        .loading-text {
            margin-right: 15px;
            font-weight: 500;
            color: var(--text-color);
        }

        .loading-spinner {
            border: 4px solid rgba(98, 0, 234, 0.3);
            border-top: 4px solid var(--primary-color);
            border-radius: 50%;
            width: 25px;
            height: 25px;
            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 {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 35px;
        }

        .image-wrapper {
            position: relative;
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: var(--box-shadow);
            transition: transform var(--transition-duration), box-shadow var(--transition-duration);
            background-color: var(--surface-color);
        }

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

        .image-wrapper img {
            width: 100%;
            height: 200px;
            object-fit: cover;
            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: 10px;
        }

        .image-icons i {
            background-color: rgba(0, 0, 0, 0.6);
            padding: 8px;
            border-radius: 50%;
            color: var(--text-light);
            font-size: 0.9rem;
            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 {
            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;
            animation: fadeIn 0.3s ease;
        }

        .modal-content {
            position: relative;
            max-width: 90%;
            max-height: 90%;
            border-radius: var(--border-radius);
            overflow: hidden;
            background-color: var(--surface-color);
            box-shadow: var(--box-shadow);
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

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

        .modal-prompt {
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(98, 0, 234, 0.8);
            color: var(--text-light);
            padding: 10px 15px;
            border-radius: var(--border-radius);
            max-width: 90%;
            text-align: center;
            font-size: 0.95rem;
        }

        .close-modal {
            position: absolute;
            top: 15px;
            right: 15px;
            color: var(--text-light);
            background: none;
            border: none;
            font-size: 1.8rem;
            cursor: pointer;
            transition: color var(--transition-duration), transform var(--transition-duration);
            padding: 5px;
            border-radius: 50%;
            background-color: rgba(0,0,0,0.5);
        }

        .close-modal:hover {
            color: var(--danger-color);
            background-color: rgba(0,0,0,0.7);
            transform: scale(1.1);
        }

        .history-container {
            display: none;
            background-color: var(--surface-color);
            padding: 25px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            backdrop-filter: blur(5px);
            margin-top: 35px;
            transition: transform var(--transition-duration), box-shadow var(--transition-duration);
            width: 100%;
        }

        .history-container:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.3);
        }

        .history-container h2 {
            color: var(--primary-color);
            margin-bottom: 20px;
            font-size: 2rem;
            font-weight: 500;
            text-align: center;
        }

        .delete-history-btn {
            background-color: var(--danger-color);
            color: var(--text-light);
            margin-top: 20px;
            width: 100%;
            padding: 14px 20px;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: background-color var(--transition-duration), transform var(--transition-duration);
            box-shadow: var(--box-shadow);
        }

        .delete-history-btn:hover {
            background-color: #cf6679;
            transform: translateY(-3px);
        }

        .delete-history-btn:active {
            transform: translateY(0);
            box-shadow: var(--box-shadow);
        }

        .delete-history-btn:focus {
            outline: 2px solid var(--secondary-color);
        }

        .toast {
            visibility: hidden;
            min-width: 300px;
            max-width: 400px;
            margin: 0 auto;
            background-color: rgba(50, 50, 50, 0.95);
            color: #fff;
            text-align: center;
            border-radius: var(--border-radius);
            padding: 16px 24px;
            position: fixed;
            z-index: 1001;
            left: 50%;
            bottom: 40px;
            transform: translateX(-50%);
            transition: opacity 0.5s ease, visibility 0.5s;
            font-size: 1rem;
            box-shadow: var(--box-shadow);
        }

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

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

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

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

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

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

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

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

            .button-group button,
            .delete-history-btn {
                font-size: 0.9rem;
                padding: 10px 16px;
            }

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

            .modal-content img {
                max-height: 70vh;
            }
        }
    </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-moon"></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(--error-color);">*</span></label>
                        <div class="flex-container">
                            <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 get-api-key" aria-label="Get API Key via Telegram">
                                <i class="fab fa-telegram"></i> Get API Key
                            </a>
                        </div>
                        <small id="apiKeyHelp">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(--error-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(--error-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(--error-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(--error-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(--error-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(--error-color);">*</span></label>
                        <select id="scheduler" name="scheduler" required aria-required="true">
                            <option value="" disabled selected>Select a scheduler</option>
                            <option value="UniPCMultistepScheduler">UniPC Multistep Scheduler</option>
                            <option value="LMSDiscreteScheduler">LMS Discrete Scheduler</option>
                            <option value="DDIMScheduler">DDIM Scheduler</option>
                            <option value="EulerDiscreteScheduler">Euler Discrete Scheduler</option>
                            <option value="PNDMScheduler">PNDM Scheduler</option>
                            <option value="DPMSolverMultistepScheduler">DPM Solver Multistep Scheduler</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>

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

            <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>

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

            <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>

            <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>

            <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';

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

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

        // Grab all necessary 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')
        };

        // Cloudflare Worker URLs for Load Balancing
        const cloudflareWorkerUrls = [
            'https://sh.dafeyan784.workers.dev/?target=https://api.abhibhai.com/api/v6/images/text2img'
            
        ];
        let currentWorkerIndex = 0; // To keep track of the next Worker URL to use

        // Request Controller to manage ongoing requests
        let currentRequestController = null;

        // Function to display toast notifications
        const showToast = (message) => {
            elements.toast.textContent = message;
            elements.toast.classList.add('show');
            setTimeout(() => elements.toast.classList.remove('show'), TOAST_DISPLAY_TIME);
        };

        // Function to log errors and show toast
        const logError = (message, error = '') => {
            console.error(message, error);
            showToast(`${message} ${error}`);
        };

        // Debounce function to limit the rate of function calls
        const debounce = (func, delay) => {
            let timeoutId;
            return (...args) => {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => func.apply(this, args), delay);
            };
        };

        // Toggle between dark and light themes
        const toggleTheme = () => {
            document.body.classList.toggle('dark-theme');
            savePreferences();
            updateThemeIcon();
        };

        // Update the theme toggle icon based on the current theme
        const updateThemeIcon = () => {
            const icon = elements.themeToggle.querySelector('i');
            if (document.body.classList.contains('dark-theme')) {
                icon.classList.remove('fa-moon');
                icon.classList.add('fa-sun');
            } else {
                icon.classList.remove('fa-sun');
                icon.classList.add('fa-moon');
            }
        };

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

        // Event listener for theme toggle
        elements.themeToggle.addEventListener('click', toggleTheme);

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

        // Save preferences to IndexedDB with debounce
        const savePreferences = debounce(async () => {
            try {
                const size = elements.size.value.split('x').map(Number);
                const preferences = {
                    id: 1, // Fixed ID for singleton
                    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);
            } catch (error) {
                logError("Failed to save preferences.", error.message);
            }
        }, 300);

        // Load preferences from IndexedDB
        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;
                }
            } catch (error) {
                logError("Failed to load preferences.", error.message);
            }
        };

        // Attach event listeners to form elements for saving preferences
        Object.values(elements).forEach(element => {
            if (element && ['INPUT', 'SELECT', 'TEXTAREA'].includes(element.tagName)) {
                element.addEventListener('input', savePreferences);
                element.addEventListener('change', savePreferences);
            }
        });

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

        // Event listener for form submission
        elements.form.addEventListener('submit', async (e) => {
            e.preventDefault();
            if (!validateForm()) {
                showToast("Please fill in all required fields.");
                return;
            }
            enqueueRequest();
        });

        // Enqueue and handle image generation request
        const enqueueRequest = async () => {
            // Cancel any ongoing request
            if (currentRequestController) {
                currentRequestController.abort();
            }

            // Initialize a new AbortController for the new request
            currentRequestController = new AbortController();

            const payload = generatePayload();
            const workerUrl = getNextWorkerUrl();

            showLoading(true);

            try {
                const data = await makeRequest(workerUrl, payload, currentRequestController.signal);
                await handleImageResponse(data.output, payload.prompt);
                showToast("Images generated successfully!");
            } catch (error) {
                if (error.name === 'AbortError') {
                    console.warn("Previous request aborted.");
                } else {
                    logError("Failed to generate images.", error.message);
                }
            } finally {
                showLoading(false);
            }
        };

        // 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
            };
        };

        // Round-robin mechanism to select the next Worker URL
        const getNextWorkerUrl = () => {
            const url = cloudflareWorkerUrls[currentWorkerIndex];
            currentWorkerIndex = (currentWorkerIndex + 1) % cloudflareWorkerUrls.length;
            return url;
        };

        // Make the API request
        const makeRequest = async (url, payload, signal) => {
            let attempt = 0;

            while (attempt <= MAX_RETRIES) {
                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);
                    return data;
                } catch (error) {
                    if (error.name === 'AbortError') {
                        throw error; // Propagate AbortError to handle it gracefully
                    }

                    attempt++;
                    if (attempt > MAX_RETRIES) {
                        throw new Error("Max retries exceeded.");
                    }

                    logError(`Attempt ${attempt} failed: ${error.message}. Retrying in ${RETRY_DELAY / 1000} seconds...`);
                    await delay(RETRY_DELAY);
                }
            }
        };

        // Handle streamed response from the API
        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;
                if (contentLength) {
                    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 the progress bar based on percentage
        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');
            }
        };

        // Delay utility
        const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

        // Handle the API's image response
        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 store in IndexedDB
        const addImage = async (url, prompt) => {
            try {
                const existing = await db.images.where('url').equals(url).first();
                if (existing) return;

                const imgWrapper = createImageWrapper(url, prompt);
                elements.imageContainer.prepend(imgWrapper);

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

                await manageHistorySize();
            } catch (error) {
                logError("Failed to add image.", error.message);
            }
        };

        // Create image wrapper with interactive icons
        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.", '');
            };
            img.addEventListener('click', () => openModal(url, prompt));

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

            return wrapper;
        };

        // Create interactive icons for each image
        const createImageIcons = (url, prompt, wrapper) => {
            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.setAttribute('aria-label', '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.setAttribute('aria-label', '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.setAttribute('aria-label', '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.setAttribute('aria-label', '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 function
        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 with fallback
        const copyToClipboard = async (text, successMessage) => {
            try {
                await navigator.clipboard.writeText(text);
                showToast(successMessage);
            } catch {
                const textarea = document.createElement('textarea');
                textarea.value = text;
                textarea.setAttribute('readonly', '');
                textarea.style.position = 'absolute';
                textarea.style.left = '-9999px';
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                showToast(successMessage);
            }
        };

        // Delete individual image
        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.message);
            }
        };

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

        // Event listener for history button
        elements.historyButton.addEventListener('click', async () => {
            const isVisible = elements.historyContainer.style.display === 'block';
            elements.historyContainer.style.display = isVisible ? 'none' : 'block';
            if (!isVisible) {
                await loadHistory();
                elements.historyButton.setAttribute('aria-expanded', 'true');
            } else {
                elements.historyButton.setAttribute('aria-expanded', 'false');
            }
        });

        // Load image 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); text-align: center;">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.message);
            }
        };

        // Event listener for delete history button
        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); text-align: center;">History cleared.</p>';
                showToast("All image history deleted.");
            } catch (error) {
                logError("Failed to delete image history.", error.message);
            }
        });

        // Event listener for clear form button
        elements.clearButton.addEventListener('click', () => {
            if (!confirm("Are you sure you want to clear all fields?")) return;
            elements.form.reset();
            showToast("Form cleared.");
            savePreferences();
            // Remove error classes if any
            const errorFields = elements.form.querySelectorAll('.error');
            errorFields.forEach(field => field.classList.remove('error'));
        });

        // Open modal to display full-size image
        const openModal = (url, prompt) => {
            elements.modalImage.src = url;
            elements.modalPrompt.textContent = prompt || '';
            elements.modal.style.display = 'flex';
            preventBodyScroll(true);
            elements.closeModal.focus();
        };

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

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

        // Event listeners for online/offline status
        window.addEventListener('offline', () => showToast("You are offline. Please check your internet connection."));
        window.addEventListener('online', () => showToast("You are back online."));

        // Initialize the application
        const init = async () => {
            await loadTheme();
            await loadPreferences();
            await loadHistory();
        };

        init();

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