Analyse the whole code before Refine it further and remove all of the impurities. 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 description="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>
        :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;
            --box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            --font-family: 'Roboto', sans-serif;
        }

        .dark-theme {
            --background-color: #121212;
            --text-color: #e0e0e0;
            --primary-color: #8ab4f8;
            --secondary-color: #b0bec5;
            --light-color: #1e1e1e;
            --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);
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
            margin: 0;
        }

        .theme-toggle {
            font-size: 1.8rem;
            cursor: pointer;
            color: var(--primary-color);
            background: none;
            border: none;
            transition: color var(--transition-duration);
            padding: 8px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .theme-toggle:focus {
            outline: 2px solid var(--primary-color);
        }

        form {
            background-color: rgba(255, 255, 255, 0.1);
            padding: 25px 30px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            backdrop-filter: blur(10px);
            transition: transform var(--transition-duration), box-shadow var(--transition-duration);
            width: 100%;
        }

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

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

        legend {
            font-size: 1.5rem;
            margin-bottom: 15px;
            color: var(--primary-color);
            font-weight: 700;
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 5px;
        }

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

        label {
            display: block;
            margin-bottom: 8px;
            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: transparent;
            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);
            outline: none;
            box-shadow: 0 0 0 0.2rem rgba(74, 144, 226, 0.25);
        }

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

        .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;
            margin-top: 20px;
        }

        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: var(--box-shadow);
        }

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

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

        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-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 {
            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: var(--box-shadow);
            transition: transform var(--transition-duration), box-shadow var(--transition-duration);
            background-color: #fff;
        }

        .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);
            object-fit: cover;
            height: 160px;
        }

        .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 {
            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 var(--transition-duration) ease;
        }

        .modal-content {
            position: relative;
            max-width: 90%;
            max-height: 90%;
            border-radius: var(--border-radius);
            overflow: hidden;
            background-color: #fff;
            box-shadow: var(--box-shadow);
        }

        .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);
            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);
        }

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

        .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 {
            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;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

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

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

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

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

            .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-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">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 id="result" class="result" aria-live="polite"></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';

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

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

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

        const requestQueue = [];
        let currentRequest = null;

        const cloudflareWorkerUrls = [
            'https://b.yukag.workers.dev/?target=https://api.abhibhai.com/api/v6/images/text2img',
            'https://wi.dafeyan784.workers.dev/?target=https://api.abhibhai.com/api/v6/images/text2img'
            
        ];

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

        elements.themeToggle.addEventListener('click', toggleTheme);

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

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

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

        Object.values(elements).forEach(element => {
            if (element && ['INPUT', 'SELECT', 'TEXTAREA'].includes(element.tagName)) {
                element.addEventListener('input', savePreferences);
                element.addEventListener('change', savePreferences);
            }
        });

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

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

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

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

        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();
            }
        };

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

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

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

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

        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.");
            }
        };

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

        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.appendChild(img);
            wrapper.appendChild(icons);

            return wrapper;
        };

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

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

            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!");
            });

            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!");
            });

            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, iconWrapperParent(wrapper));
            });

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

            return iconsContainer;
        };

        const iconWrapperParent = (element) => {
            return element.parentElement;
        };

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

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

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

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

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

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

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

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

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

        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();
            }
        });

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

        const init = async () => {
            await loadTheme();
            await loadPreferences();
            await loadHistory();
        };

        init();

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