Make the UI/UX better. Make it more visually appealing. Handle all of the edge cases. Improve the quality of the whole codes. Make the UI/UX even better. Don't hold back. Don't compromis. Don't use any framework. Make the whole codes 10 times better. Improve all aspects of this whole codes. improve anything that can be improved. If everything is improved then improve it even further. Focus on all aspects as many times you want just make it perfect. Send the full improved codes with breaking any functionalities. 
---- 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Advanced Image Generation using AI models">
    <title>Advanced Image Generation</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link rel="preconnect" href="https://unpkg.com" crossorigin>
    <link rel="preconnect" href="https://fonts.googleapis.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);
            --transition-duration: 0.3s;
        }

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

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Roboto', sans-serif;
            background-color: var(--background-color);
            color: var(--text-color);
            line-height: 1.6;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 100vh;
            transition: background-color var(--transition-duration), color var(--transition-duration);
        }

        .container {
            max-width: 800px;
            width: 100%;
        }

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

        h1, h2 {
            color: var(--primary-color);
            margin-bottom: 20px;
            text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.1);
        }

        h1 {
            font-size: 2.5rem;
        }

        h2 {
            font-size: 2rem;
        }

        .theme-toggle {
            font-size: 1.5rem;
            cursor: pointer;
            color: var(--primary-color);
            transition: color var(--transition-duration);
            position: absolute;
            right: 20px;
            top: 60px;
        }

        .form-container, .result, .history-container {
            background-color: rgba(255, 255, 255, 0.05);
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            transition: transform var(--transition-duration) ease, box-shadow var(--transition-duration) ease;
        }

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

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

        .enhancePrompt label {
            margin-right: 10px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            color: var(--text-color);
            transition: color var(--transition-duration);
        }

        input, textarea, select {
            width: 100%;
            padding: 12px;
            border: 1px solid var(--secondary-color);
            border-radius: 6px;
            transition: all var(--transition-duration) ease;
            font-size: 1rem;
            background-color: var(--background-color);
            color: var(--text-color);
        }

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

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

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

        button i {
            margin-right: 8px;
        }

        .button-group {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
        }

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

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

        .delete-history {
            background-color: var(--danger-color);
            margin-top: 10px;
        }

        .delete-history:hover {
            background-color: #c82333;
        }

        .error {
            color: var(--danger-color);
            font-weight: bold;
        }

        #loading, #progress-bar-container {
            display: none;
            margin-top: 10px;
        }

        .loading-container {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
        }

        .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;
            margin-left: 10px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

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

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

        .image-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .image-wrapper {
            position: relative;
            width: 100%;
            overflow: hidden;
            border-radius: 12px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }

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

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

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

        .image-icons i {
            color: white;
            font-size: 1.5rem;
            transition: color var(--transition-duration) ease;
            cursor: pointer;
        }

        .image-icons i:hover {
            color: var(--primary-color);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 1000;
            overflow: hidden;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            max-width: 80%;
            max-height: 80%;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            overflow: auto;
            border-radius: 10px;
        }

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

        .modal-prompt {
            position: absolute;
            bottom: 20px;
            background-color: rgba(0, 0, 0, 0.7);
            color: #fff;
            padding: 10px;
            border-radius: 5px;
            max-width: 90%;
            overflow-wrap: break-word;
            text-align: center;
        }

        @keyframes animatetop {
            from { top: -300px; opacity: 0; }
            to { top: 0; opacity: 1; }
        }

        #toast {
            visibility: hidden;
            min-width: 250px;
            margin-left: -125px;
            background-color: rgba(50, 50, 50, 0.9);
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 16px;
            position: fixed;
            z-index: 1;
            left: 50%;
            bottom: 30px;
            transition: visibility 0s, opacity 0.5s linear;
            opacity: 0;
        }

        #toast.show {
            visibility: visible;
            opacity: 1;
            animation: fadein 0.5s, fadeout 0.5s 2.5s;
        }

        @keyframes fadein {
            from { bottom: 0; opacity: 0; }
            to { bottom: 30px; opacity: 1; }
        }

        @keyframes fadeout {
            from { bottom: 30px; opacity: 1; }
            to { bottom: 0; opacity: 0; }
        }

        @media (max-width: 600px) {
            body {
                padding: 10px;
            }
            h1 {
                font-size: 1.8rem;
            }
            .form-container, .result, .history-container {
                padding: 20px;
            }
            button {
                font-size: 0.9rem;
            }
            .button-group {
                grid-template-columns: 1fr;
            }
            .close {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>Advanced Image Generation</h1>
            <i class="fas fa-adjust theme-toggle" id="themeToggle" title="Toggle Dark/Light Theme"></i>
        </header>
        <main>
            <form id="imageForm" aria-label="Image Generation Form" novalidate>
                <div class="form-group">
                    <label for="apiKey">API Key:</label>
                    <input type="password" id="apiKey" name="apiKey" required placeholder="Enter API Key" aria-required="true">
                    <button type="button" class="get-api-key" onclick="window.open('https://t.me/AbhiBotsBot', '_blank')">
                        <i class="fab fa-telegram"></i> Get API Key
                    </button>
                </div>
                <div class="form-group">
                    <label for="modelId">Model:</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:</label>
                    <textarea id="prompt" name="prompt" rows="4" required placeholder="Enter your prompt" aria-required="true"></textarea>
                </div>
                <div class="form-group">
                    <label for="negativePrompt">Negative Prompt:</label>
                    <textarea id="negativePrompt" name="negativePrompt" rows="3" placeholder="Optional"></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:</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:</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:</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:</label>
                    <select id="scheduler" name="scheduler" required aria-required="true">
                        <option value="" disabled selected>Select a scheduler</option>
                        <option value="UniPCMultistepScheduler">UniPCMultistepScheduler</option>
                        <option value="LMSDiscreteScheduler">LMSDiscreteScheduler</option>
                        <option value="DDIMScheduler">DDIMScheduler</option>
                        <option value="EulerDiscreteScheduler">EulerDiscreteScheduler</option>
                        <option value="PNDMScheduler">PNDMScheduler</option>
                        <option value="DPMSolverMultistepScheduler">DPMSolverMultistepScheduler</option>
                    </select>
                </div>
                <div class="enhancePrompt">
                    <label for="enhancePrompt">Enhance image:</label>
                    <input type="checkbox" id="enhancePrompt">
                </div>
                <div class="button-group">
                    <button type="submit"><i class="fas fa-image"></i> Generate</button>
                    <button type="button" id="clearButton"><i class="fas fa-eraser"></i> Clear All</button>
                    <button type="button" id="historyButton" class="history-button"><i class="fas fa-history"></i> History</button>
                </div>
            </form>
            <div id="loading" class="loading-container">
                <div class="loading-text">Generating image...</div>
                <div class="loading-spinner"></div>
            </div>
            <div id="progress-bar-container" class="progress-bar-container">
                <div id="progress-bar" class="progress-bar"></div>
            </div>
            <div id="result" class="result"></div>
            <div class="image-container" id="imageContainer"></div>
            <div id="historyContainer" class="history-container" style="display: none;">
                <h2>Image History</h2>
                <div id="historyImages" class="image-container"></div>
                <button class="delete-history" id="deleteHistoryButton"><i class="fas fa-trash"></i> Clear History</button>
            </div>
            <div id="imageModal" class="modal" role="dialog" aria-labelledby="modalTitle" aria-describedby="modalDesc">
                <div class="modal-content">
                    <span class="close" aria-label="Close modal">&times;</span>
                    <img id="modalImage" src="" alt="Image Preview">
                    <div class="modal-prompt" id="modalPrompt"></div>
                </div>
            </div>
            <div id="toast" aria-live="polite"></div>
        </main>
    </div>
    
    <script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script>
    <script>
        (() => {
            const MAX_HISTORY_SIZE = 30;
            const RETRY_DELAY = 2000;
            const MAX_RETRIES = 3;
            const TOAST_DISPLAY_TIME = 3000;
            const requestQueue = [];
            let currentRequest = null;

            const db = new Dexie("ImageGenerationDB");
            db.version(3).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'),
                loading: document.getElementById('loading'),
                progressBarContainer: document.getElementById('progress-bar-container'),
                progressBar: document.getElementById('progress-bar'),
                result: document.getElementById('result'),
                imageContainer: document.getElementById('imageContainer'),
                form: document.getElementById('imageForm'),
                historyContainer: document.getElementById('historyContainer'),
                historyImages: document.getElementById('historyImages'),
                modal: document.getElementById("imageModal"),
                modalImg: document.getElementById("modalImage"),
                modalPrompt: document.getElementById("modalPrompt"),
                closeModal: document.querySelector(".close"),
                toast: document.getElementById("toast"),
                clearButton: document.getElementById('clearButton'),
                historyButton: document.getElementById('historyButton'),
                deleteHistoryButton: document.getElementById('deleteHistoryButton'),
                themeToggle: document.getElementById('themeToggle')
            };

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

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

            const toggleTheme = () => {
                const isDarkTheme = !document.body.classList.contains('dark-theme');
                document.body.classList.toggle('dark-theme', isDarkTheme);
                savePreferences();
            };
            elements.themeToggle.addEventListener('click', toggleTheme);

            const loadTheme = async () => {
                try {
                    const preferences = await db.preferences.get(1);
                    if (preferences && preferences.theme) {
                        document.body.classList.toggle('dark-theme', preferences.theme === 'dark');
                    }
                } catch (error) {
                    logError("Error loading theme:", error);
                }
            };

            const loadPreferences = async () => {
                try {
                    const preferences = await db.preferences.get(1);
                    if (preferences) {
                        Object.entries(preferences).forEach(([key, value]) => {
                            const element = elements[key];
                            if (element) {
                                if (element.type === 'checkbox') {
                                    element.checked = value;
                                } else {
                                    element.value = value || '';
                                }
                            }
                        });
                        showToast("Preferences loaded successfully!");
                    }
                } catch (error) {
                    logError("Error loading preferences:", error);
                }
            };

            const savePreferences = async () => {
                try {
                    const sizeValue = elements.size.value.split('x');
                    const preferences = {
                        id: 1,
                        apiKey: elements.apiKey.value,
                        modelId: elements.modelId.value,
                        prompt: elements.prompt.value,
                        negativePrompt: elements.negativePrompt.value,
                        width: parseInt(sizeValue[0], 10) || 512,
                        height: parseInt(sizeValue[1], 10) || 512,
                        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);
                    showToast("Preferences saved successfully!");
                } catch (error) {
                    logError("Error saving preferences:", error);
                }
            };

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

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

            const handleFormSubmit = async (event) => {
                event.preventDefault();
                if (!validateForm()) {
                    showToast("Please fill in all required fields.");
                    return;
                }
                showToast("Image is generating, please wait...");
                showLoadingState(true);
                queueRequest();
            };
            elements.form.addEventListener('submit', handleFormSubmit);

            const queueRequest = () => {
                if (currentRequest) {
                    currentRequest.abort();
                }
                requestQueue.push({
                    payload: generatePayload(),
                    attempt: 0
                });
                processQueue();
            };

            const processQueue = async () => {
                if (currentRequest || requestQueue.length === 0) {
                    return;
                }

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

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

            const generatePayload = () => {
                const sizeValue = elements.size.value.split('x');
                return {
                    api_key: elements.apiKey.value,
                    model_id: elements.modelId.value,
                    prompt: elements.prompt.value,
                    negative_prompt: elements.negativePrompt.value,
                    width: parseInt(sizeValue[0], 10) || 512,
                    height: parseInt(sizeValue[1], 10) || 512,
                    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 makeRequest = async (payload, attempt, signal) => {
                if (attempt >= MAX_RETRIES || attempt >= cloudflareWorkerUrls.length) {
                    showToast("All attempts failed. Please try again later.");
                    showLoadingState(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) {
                        const data = await handleStreamResponse(response);
                        showLoadingState(false);
                        await handleImageResponse(data.output, payload.prompt);
                    } else {
                        throw new Error('Network response was not ok');
                    }
                } catch (error) {
                    if (!signal.aborted) {
                        logError(`Attempt ${attempt + 1} failed:`, error);
                        await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
                        requestQueue.push({ payload, attempt: attempt + 1 });
                    }
                }
            };

            const handleImageResponse = async (output, prompt) => {
                if (output && output.length > 0) {
                    await Promise.all(output.map(imageUrl => addImageToContainer(imageUrl, prompt)));
                    showToast("Images generated successfully!");
                } else {
                    throw new Error("No images found in response.");
                }
            };

            const handleStreamResponse = async (response) => {
                const reader = response.body.getReader();
                const contentLength = parseInt(response.headers.get('Content-Length'), 10) || 0;
                let receivedLength = 0;
                let chunks = [];
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    chunks.push(value);
                    receivedLength += value.length;
                    updateProgressBar(receivedLength, contentLength);
                }
                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 = (receivedLength, contentLength) => {
                if (contentLength > 0) {
                    elements.progressBar.style.width = `${(receivedLength / contentLength) * 100}%`;
                }
            };

            const showLoadingState = (isLoading) => {
                elements.loading.style.display = isLoading ? 'flex' : 'none';
                elements.progressBarContainer.style.display = isLoading ? 'block' : 'none';
                if (!isLoading) {
                    elements.result.innerHTML = '';
                    elements.imageContainer.innerHTML = '';
                }
            };

            const addImageToContainer = async (imageUrl, prompt) => {
                if (!imageUrl) return;
                try {
                    const existingImage = await db.images.where('url').equals(imageUrl).first();
                    if (existingImage) return;
                    
                    const imgWrapper = createImageWrapper(imageUrl, prompt);
                    elements.imageContainer.appendChild(imgWrapper);

                    await db.images.add({ url: imageUrl, timestamp: new Date(), prompt });
                    await manageImageHistory();
                } catch (error) {
                    logError("Error adding image to container:", error);
                }
            };

            const createImageWrapper = (imageUrl, prompt) => {
                const imgWrapper = document.createElement('div');
                imgWrapper.classList.add('image-wrapper');
                
                const img = document.createElement('img');
                img.src = imageUrl;
                img.alt = prompt || "Generated image";
                img.setAttribute('data-prompt', prompt);
                img.onload = () => img.classList.add('loaded');
                img.onerror = () => {
                    imgWrapper.remove();
                    logError("Error loading image:", imageUrl);
                };
                img.onclick = () => openModal(imageUrl, prompt);
                
                const icons = createImageIcons(imageUrl, prompt);
                imgWrapper.appendChild(img);
                imgWrapper.appendChild(icons);
                
                return imgWrapper;
            };

            const createImageIcons = (imageUrl, prompt) => {
                const icons = document.createElement('div');
                icons.classList.add('image-icons');
                
                const downloadIcon = document.createElement('i');
                downloadIcon.classList.add('fas', 'fa-download');
                downloadIcon.onclick = (e) => {
                    e.stopPropagation();
                    downloadImage(imageUrl);
                };

                const shareIcon = document.createElement('i');
                shareIcon.classList.add('fas', 'fa-share-alt');
                shareIcon.onclick = (e) => {
                    e.stopPropagation();
                    displayImageUrl(imageUrl);
                };
                
                const copyPromptIcon = document.createElement('i');
                copyPromptIcon.classList.add('fas', 'fa-copy');
                copyPromptIcon.onclick = (e) => {
                    e.stopPropagation();
                    copyTextToClipboard(prompt);
                };
                
                const deleteIcon = document.createElement('i');
                deleteIcon.classList.add('fas', 'fa-trash');
                deleteIcon.onclick = async (e) => {
                    e.stopPropagation();
                    await deleteImage(imageUrl);
                    e.target.closest('.image-wrapper').remove();
                };
                
                icons.appendChild(downloadIcon);
                icons.appendChild(shareIcon);
                icons.appendChild(copyPromptIcon);
                icons.appendChild(deleteIcon);
                
                return icons;
            };

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

            const copyTextToClipboard = (text) => {
                navigator.clipboard.writeText(text)
                    .then(() => showToast('Prompt copied to clipboard!'))
                    .catch(() => {
                        const tempInput = document.createElement('input');
                        tempInput.value = text;
                        document.body.appendChild(tempInput);
                        tempInput.select();
                        document.execCommand('copy');
                        document.body.removeChild(tempInput);
                        showToast('Prompt copied to clipboard!');
                    });
            };

            const deleteImage = async (imageUrl) => {
                try {
                    const image = await db.images.where('url').equals(imageUrl).first();
                    if (image) {
                        await db.images.delete(image.id);
                        showToast("Image deleted successfully!");
                    }
                } catch (error) {
                    logError("Error deleting image:", error);
                }
            };

            const displayImageUrl = (imageUrl) => {
                navigator.clipboard.writeText(imageUrl)
                    .then(() => showToast('Image URL copied to clipboard!'))
                    .catch(() => {
                        const tempInput = document.createElement('input');
                        tempInput.value = imageUrl;
                        document.body.appendChild(tempInput);
                        tempInput.select();
                        document.execCommand('copy');
                        document.body.removeChild(tempInput);
                        showToast('Image URL copied to clipboard!');
                    });
            };

            const manageImageHistory = async () => {
                const count = await db.images.count();
                if (count > MAX_HISTORY_SIZE) {
                    const oldest = await db.images.orderBy('timestamp').limit(count - MAX_HISTORY_SIZE).toArray();
                    await db.images.bulkDelete(oldest.map(img => img.id));
                }
            };

            const clearForm = () => {
                if (confirm('Are you sure you want to clear the form?')) {
                    elements.form.reset();
                    elements.result.innerHTML = '';
                    elements.imageContainer.innerHTML = '';
                    showToast("Form cleared!");
                    elements.form.querySelectorAll('.error').forEach(elem => elem.classList.remove('error'));
                }
            };
            elements.clearButton.addEventListener('click', clearForm);

            const openModal = (imageUrl, prompt) => {
                elements.modal.style.display = "flex";
                elements.modalImg.src = imageUrl;
                elements.modalImg.alt = prompt || "Generated image";
                elements.modalPrompt.textContent = prompt;
                preventBodyScroll(true);
            };
            
            const closeModal = () => {
                elements.modal.style.display = "none";
                elements.modalImg.src = "";
                elements.modalPrompt.textContent = "";
                preventBodyScroll(false);
            };
            
            elements.closeModal.addEventListener('click', closeModal);
            window.addEventListener('click', (event) => {
                if (event.target === elements.modal) {
                    closeModal();
                }
            });
            window.addEventListener('keydown', (event) => {
                if (event.key === "Escape") {
                    closeModal();
                }
            });

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

            const toggleHistoryView = async () => {
                const isVisible = elements.historyContainer.style.display === 'block';
                elements.historyContainer.style.display = isVisible ? 'none' : 'block';
                if (!isVisible) {
                    elements.historyImages.innerHTML = '';
                    try {
                        const images = await db.images.orderBy('timestamp').reverse().toArray();
                        updateHistoryImages(images);
                        showToast("Image history loaded successfully!");
                    } catch (error) {
                        logError("Error loading history images:", error);
                    }
                }
            };
            elements.historyButton.addEventListener('click', toggleHistoryView);

            const updateHistoryImages = (images) => {
                const fragment = document.createDocumentFragment();
                images.forEach(image => {
                    const imgWrapper = createImageWrapper(image.url, image.prompt);
                    fragment.appendChild(imgWrapper);
                });
                elements.historyImages.appendChild(fragment);
            };

            const deleteHistory = async () => {
                if (confirm('Are you sure you want to delete all image history?')) {
                    try {
                        await db.images.clear();
                        elements.historyImages.innerHTML = '';
                        elements.historyContainer.style.display = 'none';
                        showToast("Image history deleted successfully!");
                    } catch (error) {
                        logError("Error deleting history:", error);
                    }
                }
            };
            elements.deleteHistoryButton.addEventListener('click', deleteHistory);

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

            const validateForm = () => {
                const inputs = elements.form.querySelectorAll('input[required], textarea[required], select[required]');
                return Array.from(inputs).every(input => input.value.trim() !== '');
            };

            const requiredInputs = document.querySelectorAll('input[required], textarea[required], select[required]');
            requiredInputs.forEach(input => {
                input.addEventListener('input', () => {
                    input.classList.toggle('error', input.value.trim() === '');
                });
            });

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

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