fix the automatic googled overlay


<!DOCTYPE html>
<html>
<head>
    <link rel="icon" type="image/x-icon" href="google.svg">
    <title>Google</title>
    <style>
        body {
            font-family: sans-serif;
        }

        #chat-container {
            display: flex;
            flex-direction: column;
            width: 500px;
            margin: 0 auto;
            border: 1px solid #ccc;
            padding: 10px;
            height: 400px;
            overflow-y: auto;
        }

        .message {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
        }

        .user-message {
            background-color: #eee;
            text-align: right;
            white-space: pre-wrap; 
        }

        .bot-message {
            background-color: #f5f5f5;
            white-space: pre-wrap; 
        }

        #input-area {
            display: flex;
            margin-top: 10px;
        }

        #input-box {
            flex-grow: 1;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        #send-button {
            padding: 5px 10px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        #typing-indicator {
            display: none; 
            margin-top: 5px;
            font-style: italic;
            color: #999;
        }

        #fileInput {
            display: none;
        }
        #attachLabel {
            cursor: pointer;
            margin-right: 8px;
            color: #007bff; 
            font-size: 18px; 
        }

        /* Existing Overlay for Typing Indicator */
        #overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent background */
            display: none; /* Initially hidden */
            z-index: 1000; /* Ensure it's on top */
        }

        /* New Overlay for Googled.png */
        #google-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: url('googled.png'); /* Path to your image */
            background-size: cover; /* Adjust as needed */
            background-repeat: no-repeat;
            display: none; /* Initially hidden */
            z-index: 1001; /* Above the typing overlay */
        }
    </style>
</head>

<body>
    <div id="chat-container">
        <!-- Existing Overlay for Typing Indicator -->
        <div id="overlay"></div>
        <!-- Chat messages will appear here -->
    </div>
    <div id="input-area">
        <textarea id="input-box" placeholder="Enter your message..." rows="3"></textarea>
        <label for="fileInput" id="attachLabel">📎</label>
        <input type="file" id="fileInput" multiple>
        <button id="send-button">Send</button>
    </div>
    <div id="typing-indicator">Gemini is typing...</div> 

    <!-- New Overlay for Googled.png -->
    <div id="google-overlay"></div>

    <script>
        // Existing JavaScript Code...
        const API_KEYS = [
            'AIzaSyBdc_A8VxExwO6-0LY1--r2-Ym73lMg-h4',
            'AIzaSyBydeCpaNOIPSk794CpTGnfKrxbjCgJLu4',
            'AIzaSyCQ7tBHtctxlNs61Zm2Y__7KYeDLfz5dms',
            'AIzaSyAip_DFfKNC35MFIorEoNK4y6czP9P65-c'
        ];
        let apiKeyIndex = 0;

        function getCurrentApiKey() {
            return API_KEYS[apiKeyIndex];
        }

        const API_URL = 'https://generativelanguage.googleapis.com';
        const chatContainer = document.getElementById('chat-container');
        const inputBox = document.getElementById('input-box');
        const sendButton = document.getElementById('send-button');
        const typingIndicator = document.getElementById('typing-indicator');
        const fileInput = document.getElementById('fileInput');

        let history = []; // Initialize history here

        sendButton.addEventListener('click', sendMessage);
        inputBox.addEventListener('keydown', (event) => {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        });

        async function sendMessage() {
            const userMessageText = inputBox.value.trim(); // Get message from inputBox
            const files = fileInput.files;

            if (!userMessageText && files.length === 0) {
                alert('Please enter a message or select a file.');
                return;
            }

            if (files.length > 0) {
                let fileNames = [];
                for (let i = 0; i < files.length; i++) {
                    fileNames.push(files[i].name);
                }
                appendMessage('User', `[Files attached: ${fileNames.join(', ')}]`);
                showTypingIndicator();
            }
            if (userMessageText) {
                appendMessage('User', `${userMessageText}`);
                showTypingIndicator();
            }

            const userParts = [];

            if (files.length > 0) {
                try {
                    for (let i = 0; i < files.length; i++) {
                        const file = files[i];
                        const fileUri = await uploadFile(file);
                        userParts.push({
                            "fileData": {
                                "fileUri": fileUri,
                                "mimeType": file.type
                            }
                        });
                    }
                } catch (error) {
                    console.error('File upload failed:', error);
                    appendMessage('Error', 'Failed to upload one or more files.');
                    hideTypingIndicator();
                    return;
                }
            }

            if (userMessageText) {
                userParts.push({
                    "text": userMessageText
                });
            }

            history.push({
                "role": "user",
                "parts": userParts
            });

            const requestBody = {
                "contents": history,
                "generationConfig": {
                    "temperature": 0,
                    "topK": 40,
                    "topP": 0.95,
                    "maxOutputTokens": 10000,
                    "responseMimeType": "text/plain"
                }
            };

            try {
                await attemptApiRequest(requestBody);
            } catch (error) {
                console.error('Error:', error);
                appendMessage('Error', 'Failed to get response from the API.');
            } finally {
                hideTypingIndicator();
            }

            inputBox.value = '';
            fileInput.value = '';
        }

        function appendMessage(sender, message) {
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message', sender === 'User' ? 'user-message' : 'bot-message');

            const senderSpan = document.createElement('span');
            senderSpan.style.fontWeight = 'bold'; // Make sender bold
            senderSpan.textContent = `${sender}: `;
            messageDiv.appendChild(senderSpan);
           
            const messageText = document.createTextNode(message);
            messageDiv.appendChild(messageText);

            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        function hideTypingIndicator() {
            typingIndicator.style.display = 'none';
            overlay.style.display = 'none'; // Hide existing overlay
        }

        async function attemptApiRequest(requestBody) {
            const maxAttempts = API_KEYS.length;
            let attempts = 0;

            while (attempts < maxAttempts) {
                const apiKey = getCurrentApiKey();
                try {
                    const response = await fetch(`${API_URL}/v1beta/models/gemini-1.5-pro:generateContent?key=${apiKey}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(requestBody)
                    });

                    if (!response.ok) {
                        const errorText = await response.text();
                        throw new Error(`API request failed: ${response.status} ${response.statusText} - ${errorText}`);
                    }

                    const data = await response.json();

                    const botResponse = data.candidates[0].content.parts.map(part => part.text || '').join('');
                    appendMessage('Bot', `${botResponse}`);

                    history.push({
                        "role": "model",
                        "parts": data.candidates[0].content.parts
                    });

                    return;

                } catch (error) {
                    console.warn(`Attempt with API key at index ${apiKeyIndex} failed:`, error);

                    attempts++;
                    apiKeyIndex = (apiKeyIndex + 1) % API_KEYS.length;

                    if (attempts >= maxAttempts) {
                        throw new Error('All API keys have failed.');
                    } else {
                        console.log(`Retrying with next API key (index ${apiKeyIndex})...`);
                    }
                }
            }
        }

        const overlay = document.getElementById('overlay');

        function showTypingIndicator() {
            typingIndicator.style.display = 'block';
            overlay.style.display = 'block'; // Show existing overlay
        }

        async function uploadFile(file) {
            const metadata = { "file": { "display_name": file.name } };

            const maxAttempts = API_KEYS.length;
            let attempts = 0;

            while (attempts < maxAttempts) {
                const apiKey = getCurrentApiKey();
                try {
                    const initiateUploadResponse = await fetch(`${API_URL}/upload/v1beta/files?key=${apiKey}`, {
                        method: 'POST',
                        headers: {
                            'X-Goog-Upload-Command': 'start',
                            'X-Goog-Upload-Protocol': 'resumable',
                            'Content-Type': 'application/json; charset=UTF-8',
                            'X-Goog-Upload-Header-Content-Type': file.type,
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify(metadata)
                    });

                    if (!initiateUploadResponse.ok) {
                        const errorText = await initiateUploadResponse.text();
                        throw new Error(`Failed to initiate file upload: ${initiateUploadResponse.status} ${initiateUploadResponse.statusText} - ${errorText}`);
                    }

                    const uploadUrl = initiateUploadResponse.headers.get('X-Goog-Upload-URL');
                    if (!uploadUrl) {
                        throw new Error('Upload URL not returned from initiate upload request.');
                    }

                    const uploadResponse = await fetch(uploadUrl, {
                        method: 'POST',
                        headers: {
                            'X-Goog-Upload-Command': 'upload, finalize',
                            'X-Goog-Upload-Offset': '0',
                            'Content-Type': file.type,
                            'Content-Length': file.size.toString(),  // Important for larger files
                        },
                        body: file
                    });


                    if (!uploadResponse.ok) {
                        const errorText = await uploadResponse.text();
                        throw new Error(`Failed to upload file content: ${uploadResponse.status} ${uploadResponse.statusText} - ${errorText}`); // More specific error message
                    }

                    const uploadResult = await uploadResponse.json();
                    const fileUri = uploadResult.file.uri;  // Get the file URI
                    if (!fileUri) {
                        throw new Error('File URI not returned from file upload response.'); // More specific error message
                    }
                    return fileUri; // Return the file URI


                } catch (error) {
                    console.warn(`File upload attempt with API key at index ${apiKeyIndex} failed:`, error);
                    attempts++;
                    apiKeyIndex = (apiKeyIndex + 1) % API_KEYS.length;

                    if (attempts >= maxAttempts) {
                        throw new Error('All API keys have failed for file upload.');
                    } else {
                        console.log(`Retrying file upload with next API key (index ${apiKeyIndex})...`);
                    }
                }
            }
        }

        // New JavaScript Code for Overlay Toggle via Key Combination

        // Flag to prevent multiple toggles on key hold
        let toggleOverlayPressed = false;

        document.addEventListener('keydown', function(event) {
            // Check if Ctrl, Shift, and Alt are pressed along with 'G' or 'g'
            if (event.ctrlKey && event.shiftKey && event.altKey && (event.key === 'G' || event.key === 'g')) {
                if (!toggleOverlayPressed) { // Prevent repeated toggles if key is held down
                    toggleGoogleOverlay();
                    toggleOverlayPressed = true;
                }
                event.preventDefault(); // Prevent default actions if necessary
            }
        });

        document.addEventListener('keyup', function(event) {
            // Reset the flag when 'G' key is released
            if (event.key === 'G' || event.key === 'g') {
                toggleOverlayPressed = false;
            }
        });

        function toggleGoogleOverlay() {
            const googleOverlay = document.getElementById('google-overlay');
            if (googleOverlay.style.display === 'none' || googleOverlay.style.display === '') {
                googleOverlay.style.display = 'block';
            } else {
                googleOverlay.style.display = 'none';
            }
        }
    </script>
</body>
</html>