When the tab is opened, make the body to be unscrollable or overflow: hidden;
function initChat() {
        // Create a container for the chat elements
        const chatWrapper = document.createElement('div');
        chatWrapper.id = 'scis-chat-wrapper';
        chatWrapper.innerHTML = chatHTML;
        document.body.appendChild(chatWrapper);

        // Initialize all the variables and event listeners
        const chatButton = document.getElementById('chat-button');
        const chatContainer = document.getElementById('chat-container');
        const chatInput = document.getElementById('chat-input');
        const sendButton = document.getElementById('send-button');
        const chatMessages = document.getElementById('chat-messages');
        const clearChatButton = document.getElementById('clear-chat');
        let isOpen = false;
        let conversationHistory = [];
        let isTyping = false;

        window.isSystemPromptAdded = false;

        if (!isSystemPromptAdded) {
            conversationHistory.unshift({
                role: "system",
                content: SYSTEM_PROMPT
            });
            isSystemPromptAdded = true; // Update the flag
            console.log('System prompt added:', SYSTEM_PROMPT,);
        }



        // Load conversation history from localStorage
        const savedHistory = localStorage.getItem('chatHistory');
        if (savedHistory) {
            conversationHistory = JSON.parse(savedHistory);
            conversationHistory
                .filter((msg) => msg.role !== 'system') // Exclude system prompt
                .forEach((msg) => {
                    addMessage(msg.content, msg.role === 'user' ? 'user' : 'bot', false);
                });
        }
        

        function showTypingIndicator() {
            const typingDiv = document.createElement('div');
            typingDiv.className = 'typing-indicator';
            typingDiv.innerHTML = `
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            `;
            chatMessages.appendChild(typingDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
            return typingDiv;
        }

        function removeTypingIndicator(indicator) {
            if (indicator && indicator.parentNode) {
                indicator.parentNode.removeChild(indicator);
            }
        }

        function printHistory() {
            console.group('Conversation History');
            console.log(JSON.stringify(conversationHistory, null, 2));
            console.groupEnd();
        }

        async function sendMessage() {
            const message = chatInput.value.trim();
            if (!message || isTyping) return;
        
            addMessage(message, 'user', true);
            printHistory();
            chatInput.value = '';
            isTyping = true;
        
            const typingIndicator = showTypingIndicator();
        
            if (conversationHistory.length === 0) {
                if (typeof SYSTEM_PROMPT === 'undefined') {
                    console.error('SYSTEM_PROMPT is not defined!');
                } else {
                    console.log('Adding system prompt:', SYSTEM_PROMPT);
                    conversationHistory.push({
                        role: "system",
                        content: SYSTEM_PROMPT
                    });
                }
            }
                        
            try {
                const response = await fetch('https://gpt4omini-6ucx5cuf.b4a.run/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        model: 'gpt-4o-mini',
                        provider: 'DDG',
                        messages: conversationHistory
                    })
                });
        
                const data = await response.json();
                removeTypingIndicator(typingIndicator);
                
                if (data.choices && data.choices[0] && data.choices[0].message) {
                    const botResponse = data.choices[0].message.content;
                    addMessage(botResponse, 'bot', true);
                }
            } catch (error) {
                console.error('Error:', error);
                removeTypingIndicator(typingIndicator);
                addMessage('Sorry, there was an error processing your request.', 'bot', true);
            }
            isTyping = false;
        }
        

        function addMessage(text, sender, saveToHistory = true) {
            // Skip rendering system messages in the chat interface
            if (sender === 'system') {
                if (saveToHistory) {
                    conversationHistory.push({
                        role: 'system',
                        content: text
                    });
                }
                return; // Do not render in the UI
            }
        
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message', `${sender}-message`);
        
            if (text.includes('<') && text.includes('>')) {
                // For rendering HTML content
                messageDiv.innerHTML = text;
            } else {
                // For regular text messages
                messageDiv.textContent = text;
            }
        
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        
        
            if (saveToHistory) {
                const role = sender === 'user' ? 'user' : 'assistant';
                conversationHistory.push({
                    role: role,
                    content: text
                });
                localStorage.setItem('chatHistory', JSON.stringify(conversationHistory));
            }
        }
        
        

        // Event Listeners
        chatButton.addEventListener('click', () => {
            isOpen = !isOpen;
            chatContainer.classList.toggle('open');
            chatButton.classList.remove('pulse');
            if (isOpen) {
                chatInput.focus();
            }
            console.log(isOpen);
        });

        clearChatButton.addEventListener('click', () => {
            chatMessages.innerHTML = `<div class="message bot-message">Hello! Welcome to the SCIS website. You can ask anything about SCIS!

안녕하세요! 수원기독국제학교 웹사이트에 오신것을 환영합니다. 학교에 대해 무엇이든 물어보세요!</div>`;
            window.isSystemPromptAdded = false;
            conversationHistory = [];

            if (!isSystemPromptAdded) {
                conversationHistory.unshift({
                    role: "system",
                    content: SYSTEM_PROMPT
                });
                isSystemPromptAdded = true; // Update the flag
                console.log('System prompt added:', SYSTEM_PROMPT,);
            }
            localStorage.removeItem('chatHistory');
        });

        sendButton.addEventListener('click', sendMessage);
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // Add pulse animation to chat button periodically
        setInterval(() => {
            if (!isOpen) {
                chatButton.classList.add('pulse');
            }
        }, 10000);
    }

    // Initialize the chat when the DOM is fully loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initChat);
    } else {
        initChat();
    }