this code is missing 3 buttons from the code below it above the input, create the 3 buttons of clear, refresh and vision in this code using the code below it (add same 3 icons from the code below in the head icons section of our code)

from flask import Flask, request, jsonify, render_template_string
import json
import os
import logging
import openai  # Ensure you have the openai library installed
from LLM import request_llm_response  # Ensure this module is correctly implemented

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize OpenAI Client
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY', 'your_openai_api_key').strip()
OPENAI_MODEL = "gpt-4"  # Corrected model name

if not OPENAI_API_KEY:
    logger.error("OpenAI API Key is not set.")
    raise EnvironmentError("OpenAI API Key is not set.")

openai.api_key = OPENAI_API_KEY

app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'your_secret_key')  # Use environment variable for security

def is_valid_gui_definition(gui_def):
    """
    Validates the structure of the GUI definition.
    Accepts either:
    - Fields: 'html' (str), 'scripts' (dict), 'styles' (dict), 'type' (str)
    OR
    - Nested Structure: 'gui' -> 'notepad' -> 'structure' -> 'html' -> ...
    """
    if not isinstance(gui_def, dict):
        logger.error("GUI definition is not a dictionary.")
        return False

    # Check for 'gui' structure
    if 'gui' in gui_def:
        try:
            notepad = gui_def['gui'].get('notepad', {})
            structure = notepad.get('structure', {})
            html = structure.get('html', {})
            # Basic validation for nested structure
            if 'div' not in html:
                logger.error("Missing 'div' in nested HTML structure.")
                return False
            return True
        except Exception as e:
            logger.error(f"Error validating nested GUI structure: {e}")
            return False

    # Existing validation for alternative structure
    required_fields = ['html', 'scripts', 'styles', 'type']
    for field in required_fields:
        if field not in gui_def:
            logger.error(f"Missing field '{field}' in GUI definition.")
            return False
        if field == 'html' and not isinstance(gui_def['html'], str):
            logger.error("'html' field is not a string.")
            return False
        if field == 'scripts' and not isinstance(gui_def['scripts'], dict):
            logger.error("'scripts' field is not a dictionary.")
            return False
        if field == 'styles' and not isinstance(gui_def['styles'], dict):
            logger.error("'styles' field is not a dictionary.")
            return False
        if field == 'type' and not isinstance(gui_def['type'], str):
            logger.error("'type' field is not a string.")
            return False
    return True

# HTML Template
index_html = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic App Generator</title>
    <style>
        /* Reset CSS */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        /* Body Styling */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #1e1e1e;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 100vh;
            color: #ffffff;
        }

        /* Header Buttons */
        #buttons-container {
            margin: 20px 0;
            display: flex;
            gap: 10px;
        }

        .control-button {
            background: none;
            color: white;
            border: none;
            cursor: pointer;
            font-size: 20px;
            padding: 10px;
            transition: color 0.3s;
        }

        .control-button:hover {
            color: #3498db;
        }

        /* Input Container */
        #input-container {
            width: 90%;
            max-width: 800px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            margin-bottom: 20px;
            position: relative;
        }

        #user-input {
            flex-grow: 1;
            padding: 15px 20px;
            font-size: 16px;
            border: 2px solid #ccc;
            border-radius: 30px;
            outline: none;
            resize: none;
            transition: border 0.3s;
            background-color: #2c2c2c;
            color: #ffffff;
        }

        #user-input:focus {
            border-color: #3498db;
        }

        .control-button.send-button {
            background: none;
            position: absolute;
            right: 10px;
            color: #2ecc71;
            font-size: 20px;
        }

        .control-button.send-button:hover {
            color: #27ae60;
        }

        /* File Upload Button (Paper Clip) */
        .control-button.attach-button {
            background: none;
            position: absolute;
            right: 50px;
            color: #f1c40f;
            font-size: 20px;
        }

        .control-button.attach-button:hover {
            color: #f39c12;
        }

        /* Save and Load Buttons */
        .control-button.save-button {
            background: none;
            color: #e67e22;
            font-size: 20px;
        }

        .control-button.save-button:hover {
            color: #d35400;
        }

        .control-button.load-button {
            background: none;
            color: #9b59b6;
            font-size: 20px;
        }

        .control-button.load-button:hover {
            color: #8e44ad;
        }

        /* Spinner */
        .spinner {
            display: none;
            width: 50px;
            height: 50px;
            border: 6px solid #f3f3f3;
            border-top: 6px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 20px auto;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        /* Status Label */
        #status-label {
            margin-top: 10px;
            font-weight: bold;
            color: #e74c3c;
            display: none;
        }

        /* App Container */
        #app-container {
            width: 90%;
            max-width: 800px;
            min-height: 300px;
            background-color: #2c2c2c;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            padding: 20px;
            overflow: auto;
        }

        /* Response Displays */
        #llm-response-display, #sent-prompt-display, #code-display {
            width: 90%;
            max-width: 800px;
            background-color: #2c2c2c;
            border-left: 5px solid #3498db;
            padding: 15px 20px;
            margin: 10px 0;
            border-radius: 5px;
            font-family: monospace;
            white-space: pre-wrap;
            word-wrap: break-word;
            display: none;
        }

        /* Responsive Design */
        @media (max-width: 600px) {
            .control-button {
                font-size: 18px;
                padding: 8px;
            }

            #user-input {
                font-size: 14px;
            }

            .control-button.send-button, .control-button.attach-button {
                font-size: 18px;
            }
        }

    </style>
</head>
<body>
    <!-- Header Buttons -->
    <div id="buttons-container">
        <button class="control-button save-button" id="save-button" title="Save UI">💾</button>
        <button class="control-button load-button" id="load-button" title="Load UI">📂</button>
    </div>

    <!-- Input Area -->
    <div id="input-container">
        <textarea id="user-input" placeholder="Enter your app request..." rows="3"></textarea>
        <button class="control-button attach-button" id="attach-button" title="Attach JSON">📎</button>
        <button class="control-button send-button" id="send-button" title="Send Request">➡️</button>
    </div>

    <!-- File Upload -->
    <input type="file" id="file-input" accept=".json" style="display: none;" />

    <!-- Status Label -->
    <div id="status-label"></div>

    <!-- Loading Spinner -->
    <div class="spinner" id="loading-indicator"></div>

    <!-- Sent Prompt Display -->
    <div id="sent-prompt-display"></div>

    <!-- LLM Response Display -->
    <div id="llm-response-display"></div>

    <!-- Application Container -->
    <div id="app-container">
        <p style="color: #aaaaaa;">Your generated application will appear here.</p>
    </div>

    <!-- Code Display (Optional) -->
    <div id="code-display">
        <pre id="code-content"></pre>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Element References
            const userInput = document.getElementById('user-input');
            const sendButton = document.getElementById('send-button');
            const attachButton = document.getElementById('attach-button');
            const fileInput = document.getElementById('file-input');
            const saveButton = document.getElementById('save-button');
            const loadButton = document.getElementById('load-button');
            const appContainer = document.getElementById('app-container');
            const loadingIndicator = document.getElementById('loading-indicator');
            const llmResponseDisplay = document.getElementById('llm-response-display');
            const llmResponseContent = document.getElementById('llm-response-display');
            const statusLabel = document.getElementById('status-label');
            const sentPromptDisplay = document.getElementById('sent-prompt-display');
            const codeDisplay = document.getElementById('code-display');
            const codeContent = document.getElementById('code-content');
            let currentCode = null;

            // Helper Functions
            function showLoading() {
                loadingIndicator.style.display = 'block';
            }

            function hideLoading() {
                loadingIndicator.style.display = 'none';
            }

            function displayStatus(message, isError = false) {
                statusLabel.textContent = message;
                statusLabel.style.color = isError ? '#e74c3c' : '#2ecc71';
                statusLabel.style.display = 'block';
                setTimeout(() => {
                    statusLabel.style.display = 'none';
                }, 5000);
            }

            function displaySentPrompt(prompt) {
                sentPromptDisplay.textContent = 'Sent Prompt: ' + prompt;
                sentPromptDisplay.style.display = 'block';
            }

            function displayLLMResponse(data) {
                llmResponseDisplay.textContent = JSON.stringify(data, null, 2);
                llmResponseDisplay.style.display = 'block';
            }

            function displayRawJSON(data) {
                llmResponseDisplay.textContent = JSON.stringify(data, null, 2);
                llmResponseDisplay.style.display = 'block';
            }

            // Helper function to build HTML from element objects
            function buildHTML(element) {
                const tag = Object.keys(element)[0];
                const attributes = element[tag];
                const attrs = [];
                for (const attr in attributes) {
                    if (attr !== 'children') {
                        attrs.push(`${attr}="${attributes[attr]}"`);
                    }
                }
                const attrsStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';
                let innerHTML = '';
                if (attributes.children && Array.isArray(attributes.children)) {
                    innerHTML = attributes.children.map(child => buildHTML(child)).join('');
                }
                return `<${tag}${attrsStr}>${innerHTML}</${tag}>`;
            }

            // Function to convert nested HTML structure to HTML string
            function nestedHTMLToHTMLString(nestedHTML) {
                return buildHTML(nestedHTML);
            }

            // Function to convert styles object to CSS string
            function stylesToCSS(stylesObj) {
                let cssString = '';
                for (const selector in stylesObj) {
                    if (stylesObj.hasOwnProperty(selector)) {
                        cssString += `${selector} {\n`;
                        const styles = stylesObj[selector];
                        for (const property in styles) {
                            if (styles.hasOwnProperty(property)) {
                                cssString += `  ${property}: ${styles[property]};\n`;
                            }
                        }
                        cssString += `}\n`;
                    }
                }
                return cssString;
            }

            // Function to inject scripts into the DOM
            function injectScripts(scriptsObj) {
                for (const funcName in scriptsObj) {
                    if (scriptsObj.hasOwnProperty(funcName)) {
                        const scriptContent = scriptsObj[funcName];
                        const script = document.createElement('script');
                        script.type = 'text/javascript';
                        script.text = scriptContent;
                        document.body.appendChild(script);
                    }
                }
            }

            // Updated renderApp function to handle nested GUI definitions
            function renderApp(guiDefinition) {
                appContainer.innerHTML = '';
                try {
                    // Inject Styles
                    if (guiDefinition.styles && typeof guiDefinition.styles === 'object') {
                        const css = stylesToCSS(guiDefinition.styles);
                        const styleTag = document.createElement('style');
                        styleTag.type = 'text/css';
                        styleTag.appendChild(document.createTextNode(css));
                        document.head.appendChild(styleTag);
                    }

                    // Inject HTML
                    if (guiDefinition.htmlElements && Array.isArray(guiDefinition.htmlElements)) {
                        const html = guiDefinition.htmlElements.map(element => buildHTML(element)).join('');
                        appContainer.innerHTML = html;
                    } 
                    else if (guiDefinition.gui && guiDefinition.gui.notepad && guiDefinition.gui.notepad.structure && guiDefinition.gui.notepad.structure.html) {
                        const nestedHtml = guiDefinition.gui.notepad.structure.html;
                        const htmlString = nestedHTMLToHTMLString(nestedHtml);
                        appContainer.innerHTML = htmlString;
                    } 
                    else if (guiDefinition.html && typeof guiDefinition.html === 'string') {
                        appContainer.innerHTML = guiDefinition.html;
                    } 
                    else {
                        appContainer.innerHTML = '<p style="color: #aaaaaa;">No valid GUI content available.</p>';
                        console.warn("Invalid structure in GUI definition:", guiDefinition);
                    }

                    // Inject Scripts
                    if (guiDefinition.scripts && typeof guiDefinition.scripts === 'object') {
                        injectScripts(guiDefinition.scripts);
                    }

                } catch (error) {
                    appContainer.innerHTML = '<p style="color: #e74c3c;">Failed to parse GUI definition. Check console for errors.</p>';
                    console.error('Error in renderApp:', error);
                }
            }

            // Send User Request
            function sendUserRequest() {
                const userRequest = userInput.value.trim();
                if (userRequest === '') {
                    alert('Please enter a request.');
                    return;
                }
                const payload = { user_request: userRequest, current_code: currentCode };
                const promptToSend = JSON.stringify(payload, null, 2);
                displaySentPrompt(promptToSend);
                showLoading();
                fetch('/generate_app', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => { throw errData; });
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.success) {
                        displayStatus('GUI generated successfully!', false);
                        currentCode = data.gui_definition;
                        renderApp(currentCode);
                        llmResponseDisplay.style.display = 'none';  // Hide previous responses
                    } else {
                        displayStatus('Error: ' + data.error, true);
                        displayRawJSON(data);  // Show raw JSON for debugging
                    }
                })
                .catch(error => {
                    hideLoading();
                    displayStatus('Error: ' + (error.error || 'Unknown error'), true);
                    displayRawJSON(error);  // Show raw JSON for debugging
                });
            }

            // Event Listeners
            sendButton.addEventListener('click', sendUserRequest);

            userInput.addEventListener('keypress', function (e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendUserRequest();
                }
            });

            // Attach Button Handler
            attachButton.addEventListener('click', function () {
                fileInput.click();
            });

            fileInput.addEventListener('change', function () {
                const file = fileInput.files[0];
                if (!file) {
                    return;
                }
                const reader = new FileReader();
                reader.onload = function (e) {
                    try {
                        const data = JSON.parse(e.target.result);
                        currentCode = data;
                        renderApp(currentCode);
                        displayStatus('JSON file loaded successfully!', false);
                        llmResponseDisplay.style.display = 'none';  // Hide previous responses
                    } catch (err) {
                        displayStatus('Invalid JSON file.', true);
                        displayRawJSON({ error: 'Invalid JSON file.' });
                    }
                };
                reader.onerror = function () {
                    displayStatus('Error reading file.', true);
                    displayRawJSON({ error: 'Error reading file.' });
                };
                reader.readAsText(file);
            });

            // Save UI Functionality
            saveButton.addEventListener('click', function () {
                if (!currentCode) {
                    alert('No UI to save.');
                    return;
                }
                const dataStr = JSON.stringify(currentCode, null, 2);
                const blob = new Blob([dataStr], { type: "application/json" });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'gui_definition.json';
                a.click();
                URL.revokeObjectURL(url);
                displayStatus('UI saved successfully!', false);
            });

            // Load UI Functionality (Optional: You can implement additional behaviors here)
            loadButton.addEventListener('click', function () {
                fileInput.click();
            });

            // Refresh and Improve App
            refreshButton.addEventListener('click', function () {
                if (!currentCode) {
                    alert('No code to refresh. Please generate an app first.');
                    return;
                }
                showLoading();
                fetch('/improve_app', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ current_code: currentCode })
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => { throw errData; });
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.success) {
                        displayStatus('GUI improved successfully!', false);
                        currentCode = data.gui_definition;
                        renderApp(currentCode);
                        llmResponseDisplay.style.display = 'none';  // Hide previous responses
                    } else {
                        displayStatus('Error: ' + data.error, true);
                        displayRawJSON(data);  // Show raw JSON for debugging
                    }
                })
                .catch(error => {
                    hideLoading();
                    displayStatus('Error: ' + (error.error || 'Unknown error'), true);
                    displayRawJSON(error);  // Show raw JSON for debugging
                });
            });

            // Clear Interface
            clearButton.addEventListener('click', function () {
                try {
                    currentCode = null;
                    codeDisplay.style.display = 'none';
                    llmResponseDisplay.style.display = 'none';
                    sentPromptDisplay.style.display = 'none';
                    codeContent.textContent = '';
                    appContainer.innerHTML = '<p style="color: #aaaaaa;">Your generated application will appear here.</p>';
                    userInput.value = '';
                    displayStatus('Interface cleared.', false);
                } catch (error) {
                    displayStatus('Error clearing the interface.', true);
                    console.error('Error in clearButton:', error);
                }
            });

            // Placeholder for AI Vision Button Functionality
            aiVisionButton.addEventListener('click', function () {
                alert('AI Vision functionality is not yet implemented.');
            });
        });
    </script>
</body>
</html>
'''

@app.route('/')
def index():
    try:
        return render_template_string(index_html)
    except Exception as e:
        logger.exception("Error rendering index page.")
        return "Internal Server Error", 500

@app.route('/generate_app', methods=['POST'])
def generate_app():
    try:
        data = request.get_json()
        if not data:
            logger.warning("No JSON data received.")
            return jsonify({'success': False, 'error': 'No JSON data received.'}), 400

        user_request = data.get('user_request', '').strip()
        current_code = data.get('current_code', None)

        if not user_request:
            logger.warning("No user_request provided.")
            return jsonify({'success': False, 'error': 'No user request provided.'}), 400

        try:
            result = request_llm_response(user_request, current_code)
        except Exception as e:
            logger.exception("Error in request_llm_response.")
            return jsonify({'success': False, 'error': 'LLM request failed: ' + str(e)}), 500

        llm_response = result.get('llm_response', 'LLM response not provided')
        gui_definition = result.get('gui_definition', None)
        success = result.get('success', False)
        error_message = result.get('error', 'Unknown error occurred.')

        prompt_sent = result.get('prompt_sent', 'Prompt not available')  # Assuming request_llm_response returns this

        response_data = {
            'llm_response': llm_response,
            'prompt_sent': prompt_sent
        }

        if success and gui_definition:
            if is_valid_gui_definition(gui_definition):
                response_data.update({'success': True, 'gui_definition': gui_definition})
            else:
                logger.error("Invalid GUI definition structure received from LLM.")
                response_data.update({
                    'success': False,
                    'error': 'Invalid GUI definition structure.',
                    'raw_response': gui_definition
                })
        else:
            logger.error(f"LLM response unsuccessful: {error_message}")
            response_data.update({'success': False, 'error': error_message})

        return jsonify(response_data)
    except Exception as e:
        logger.exception("Unhandled exception in generate_app.")
        return jsonify({'success': False, 'error': 'Internal server error.'}), 500

@app.route('/improve_app', methods=['POST'])
def improve_app():
    try:
        data = request.get_json()
        if not data:
            logger.warning("No JSON data received in improve_app.")
            return jsonify({'success': False, 'error': 'No JSON data received.'}), 400

        current_code = data.get('current_code', None)

        if not current_code:
            logger.warning("No current_code provided for improvement.")
            return jsonify({'success': False, 'error': 'No current code available to improve.'}), 400

        try:
            result = request_llm_response("", current_code)
        except Exception as e:
            logger.exception("Error in request_llm_response during improve_app.")
            return jsonify({'success': False, 'error': 'LLM request failed: ' + str(e)}), 500

        llm_response = result.get('llm_response', 'LLM response not provided')
        gui_definition = result.get('gui_definition', None)
        success = result.get('success', False)
        error_message = result.get('error', 'Unknown error occurred.')

        prompt_sent = result.get('prompt_sent', 'Prompt not available')  # Assuming request_llm_response returns this

        response_data = {
            'llm_response': llm_response,
            'prompt_sent': prompt_sent
        }

        if success and gui_definition:
            if is_valid_gui_definition(gui_definition):
                response_data.update({'success': True, 'gui_definition': gui_definition})
            else:
                logger.error("Invalid GUI definition structure received from LLM during improve_app.")
                response_data.update({
                    'success': False,
                    'error': 'Invalid GUI definition structure.',
                    'raw_response': gui_definition
                })
        else:
            logger.error(f"LLM improve_app response unsuccessful: {error_message}")
            response_data.update({'success': False, 'error': error_message})

        return jsonify(response_data)
    except Exception as e:
        logger.exception("Unhandled exception in improve_app.")
        return jsonify({'success': False, 'error': 'Internal server error.'}), 500

if __name__ == '__main__':
    try:
        app.run(debug=True)
    except Exception as e:
        logger.exception("Failed to start the Flask application.")


CODE TO TAKE BUTTON EXAMPLES TO COPY TO OUR HEAD ICONS SECTION:

from flask import Flask, request, jsonify, render_template_string
import json
import re
import os
from openai import OpenAI

# Initialize OpenAI Client
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY', 'your_openai_api_key').strip()
OPENAI_MODEL = "gpt-4"

if not OPENAI_API_KEY:
    raise EnvironmentError("OpenAI API Key is not set.")

client = OpenAI(api_key=OPENAI_API_KEY)

app = Flask(__name__)
app.secret_key = 'your_secret_key'

# HTML template with clear structure and functionality
index_html = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic App Generator</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f5f5f5;
        }
        #input-container {
            display: flex;
            align-items: center;
            position: relative;
            width: 100%;
            max-width: 800px;
            margin-bottom: 10px;
        }
        #user-input {
            flex-grow: 1;
            padding: 12px 20px;
            font-size: 18px;
            border: 1px solid #d9d9d9;
            border-radius: 24px;
            outline: none;
            width: 100%;
            resize: none;
            box-sizing: border-box;
        }
        .control-button {
            background: transparent;
            color: #3498db;
            border: none;
            cursor: pointer;
            font-size: 24px;
            padding: 8px;
            margin-left: 8px;
        }
        #send-button, #upload-button {
            position: absolute;
            right: 10px;
        }
        #upload-button {
            right: 50px;
        }
        #file-input {
            display: none;
        }
        #app-container {
            width: 100%;
            max-width: 800px;
            max-height: 600px;
            margin-bottom: 20px;
            overflow: auto;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            background-color: #f9f9f9;
            padding: 20px;
            box-sizing: border-box;
        }
        #code-display, #llm-response-display, #sent-prompt-display {
            width: 100%;
            max-width: 800px;
            padding: 20px;
            border-radius: 8px;
            overflow: auto;
            font-family: monospace;
            display: none;
        }
        .spinner {
            display: none;
            width: 50px;
            height: 50px;
            border: 8px solid #f3f3f3;
            border-top: 8px solid #3498db;
            border-radius: 50%;
            animation: spin 2s linear infinite;
            margin: auto;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        #status-label {
            margin-top: 10px;
            font-weight: bold;
            color: #3498db;
        }
    </style>
</head>
<body>
    <div id="buttons-container">
        <button class="control-button" id="refresh-button" title="Refresh and Improve">🔄</button>
        <button class="control-button" id="clear-button" title="Clear GUI">🗑️</button>
        <button class="control-button" id="ai-vision-button" title="AI Vision">👁️</button>
    </div>
    <div id="input-container">
        <textarea id="user-input" placeholder="Enter your app request..." rows="2"></textarea>
        <button class="control-button" id="upload-button" title="Attach JSON">📎</button>
        <button class="control-button" id="send-button">➡️</button>
        <input type="file" id="file-input" accept=".json" />
    </div>
    <div id="sent-prompt-display"></div> <!-- Displaying the prompt sent to LLM -->
    <div id="status-label"></div>
    <div id="loading-indicator" class="spinner"></div>
    <div id="app-container"></div>
    <div id="code-display">
        <pre id="code-content"></pre>
    </div>
    <div id="llm-response-display">
        <pre id="llm-response-content"></pre>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const userInput = document.getElementById('user-input');
            const sendButton = document.getElementById('send-button');
            const uploadButton = document.getElementById('upload-button');
            const fileInput = document.getElementById('file-input');
            const refreshButton = document.getElementById('refresh-button');
            const clearButton = document.getElementById('clear-button');
            const appContainer = document.getElementById('app-container');
            const loadingIndicator = document.getElementById('loading-indicator');
            const llmResponseDisplay = document.getElementById('llm-response-display');
            const llmResponseContent = document.getElementById('llm-response-content');
            const statusLabel = document.getElementById('status-label');
            const sentPromptDisplay = document.getElementById('sent-prompt-display');
            let currentCode = null;

            function showLoading() {
                loadingIndicator.style.display = 'block';
            }

            function hideLoading() {
                loadingIndicator.style.display = 'none';
            }

            function displaySentPrompt(prompt) {
                sentPromptDisplay.textContent = 'Sent Prompt: ' + prompt;
                sentPromptDisplay.style.display = 'block';
            }

            function sendUserRequest() {
                const userRequest = userInput.value.trim();
                if (userRequest === '') {
                    alert('Please enter a request.');
                    return;
                }
                const promptToSend = JSON.stringify({ user_request: userRequest, current_code: currentCode }, null, 2);
                displaySentPrompt(promptToSend); // Show the prompt sent to LLM
                showLoading();
                fetch('/generate_app', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: promptToSend
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    llmResponseContent.textContent = data.llm_response || 'No LLM response';
                    llmResponseDisplay.style.display = 'block';
                    if (data.success) {
                        currentCode = data.gui_definition;
                        renderApp(currentCode);
                        statusLabel.textContent = '';
                    } else {
                        statusLabel.textContent = 'Error: ' + data.error;
                    }
                })
                .catch(error => {
                    hideLoading();
                    statusLabel.textContent = 'Error: ' + error;
                });
            }

            function renderApp(guiDefinition) {
                appContainer.innerHTML = ''; // Clear previous content
                try {
                    if (guiDefinition.component && guiDefinition.component.html) {
                        appContainer.innerHTML = guiDefinition.component.html; // Access the correct HTML structure
                    } else {
                        appContainer.innerHTML = '<p>No valid GUI content available.</p>'; // Fallback message
                        console.warn("Invalid structure in GUI definition:", guiDefinition);
                    }
                } catch (error) {
                    appContainer.innerHTML = '<p>Failed to parse GUI definition. Check console for errors.</p>';
                    console.error('Error in renderApp:', error);
                }
            }

            sendButton.addEventListener('click', sendUserRequest);

            userInput.addEventListener('keypress', function (e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendUserRequest();
                }
            });

            uploadButton.addEventListener('click', function () {
                fileInput.click();
            });

            fileInput.addEventListener('change', function () {
                const file = fileInput.files[0];
                if (!file) {
                    return;
                }
                const reader = new FileReader();
                reader.onload = function (e) {
                    try {
                        const data = JSON.parse(e.target.result);
                        currentCode = data;
                        renderApp(currentCode);
                        statusLabel.textContent = '';
                    } catch (err) {
                        statusLabel.textContent = 'Invalid JSON file.';
                    }
                };
                reader.readAsText(file);
            });

            refreshButton.addEventListener('click', function () {
                if (!currentCode) {
                    alert('No code to refresh. Please generate an app first.');
                    return;
                }
                showLoading();
                fetch('/improve_app', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ current_code: currentCode })
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    llmResponseContent.textContent = data.llm_response || '';
                    llmResponseDisplay.style.display = 'block';
                    if (data.success) {
                        currentCode = data.gui_definition;
                        renderApp(currentCode);
                        statusLabel.textContent = '';
                    } else {
                        statusLabel.textContent = 'Error: ' + data.error;
                    }
                })
                .catch(error => {
                    hideLoading();
                    statusLabel.textContent = 'Error: ' + error;
                });
            });

            clearButton.addEventListener('click', function () {
                currentCode = null;
                codeDisplay.style.display = 'none';
                llmResponseDisplay.style.display = 'none';
                sentPromptDisplay.style.display = 'none';
                codeContent.textContent = '';
                appContainer.innerHTML = '';
                userInput.value = '';
                statusLabel.textContent = '';
            });
        });
    </script>
</head>
<body>
</body>
</html>
'''

@app.route('/')
def index():
    return render_template_string(index_html)

@app.route('/generate_app', methods=['POST'])
def generate_app():
    data = request.get_json()
    user_request = data.get('user_request', '').strip()
    current_code = data.get('current_code', None)
    if not user_request:
        return jsonify({'success': False, 'error': 'No user request provided.'})

    result = request_llm_response(user_request, current_code)
    response_data = {
        'llm_response': result.get('llm_response', 'LLM response not provided'),
        'prompt': user_request  # Include the prompt for debugging
    }

    if result['success']:
        response_data.update({'success': True, 'gui_definition': result['gui_definition']})
    else:
        response_data.update({'success': False, 'error': result['error']})

    return jsonify(response_data)

@app.route('/improve_app', methods=['POST'])
def improve_app():
    data = request.get_json()
    current_code = data.get('current_code', None)
    if not current_code:
        return jsonify({'success': False, 'error': 'No current code to improve.'})

    result = request_llm_response("", current_code)
    response_data = {
        'llm_response': result.get('llm_response', 'LLM response not provided')
    }

    if result['success']:
        response_data.update({'success': True, 'gui_definition': result['gui_definition']})
    else:
        response_data.update({'success': False, 'error': result['error']})

    return jsonify(response_data)

if __name__ == '__main__':
    app.run(debug=True)