<!DOCTYPE html>
<html>
<head>
    <title>AI Prompt</title>
    <style>
        #chatHistory {
            min-height: 200px;
            border: 1px solid #ccc;
            margin-bottom: 10px;
            padding: 10px;
        }
        .user {
            color: blue;
        }
        .model {
            color: green;
        }
    </style>
</head>
<body>
    <h1>AI phiên bản hết tiền</h1>
    <form id="aiForm">
        <input type="text" name="prompt" style="min-width: 300px">
        <button type="submit">Generate</button>
    </form>
    <button id="resetButton">Reset Chat</button>
    <div id="chatHistory"></div>
    <div id="aiResponse"></div>

    <script>
        const form = document.getElementById('aiForm');
        const responseDiv = document.getElementById('aiResponse');
        const chatHistoryDiv = document.getElementById('chatHistory');
        const resetButton = document.getElementById('resetButton');

        let chatHistory = loadChatHistory();
        displayChatHistory();

        form.addEventListener('submit', async function(event) {
            event.preventDefault();
            const formData = new FormData(form);
            const prompt = formData.get('prompt');
            addToChatHistory('user', prompt);
            responseDiv.textContent = 'Loading...';

            try {
                const response = await fetch('/generate-ai', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ prompt, history: chatHistory })
                });

                if (!response.ok) {
                    const err = await response.text();
                    throw new Error(`Failed to generate AI content, HTTP Status: ${response.status} ${err}`);
                }

                const text = await response.text();
                addToChatHistory('model', text); // Add model response to history
                responseDiv.textContent = ''; // Clear loading message
            } catch (error) {
                responseDiv.textContent = `Error: ${error.message}`;
            }
        });

        resetButton.addEventListener('click', function() {
            chatHistory = [];
            localStorage.removeItem('chatHistory');
            displayChatHistory();
            responseDiv.textContent = '';
        });

        function addToChatHistory(role, text) {
            chatHistory.push({ role, parts: [{ text }] });
            saveChatHistory();
            displayChatHistory();
        }

        function loadChatHistory() {
            const storedHistory = localStorage.getItem('chatHistory');
            return storedHistory ? JSON.parse(storedHistory) : [];
        }

        function saveChatHistory() {
            localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
        }

        function displayChatHistory() {
            chatHistoryDiv.innerHTML = '';
            for (const message of chatHistory) {
                const messageElement = document.createElement('p');
                messageElement.classList.add(message.role);
                messageElement.textContent = `${message.role}: ${message.parts[0].text}`;
                chatHistoryDiv.appendChild(messageElement);
            }
        }
    </script>
</body>
</html>