when i click the Send button, nothing happens,  can you fix and also make sure a verbose/log is displayed in the LLM interactions Logs object?

# app.py

import os
import json
from flask import Flask, request, jsonify
import openai,os
from datetime import datetime

app = Flask(__name__)

# Configure OpenAI API key
openai.api_key = os.environ.get("OPENAI_API_KEY")  # Replace with your OpenAI API key

# Log storage (in-memory; for production, use persistent storage)
llm_logs = []

# Directory to save UI states
SAVE_DIR = 'saved_ui_states'
os.makedirs(SAVE_DIR, exist_ok=True)

def generate_ui(application_name, current_ui=None, user_event=None):
    prompt = (
        "You are an assistant that generates complete GUI designs in a strict JSON format "
        "for web applications. The JSON must contain exactly three fields: 'html', 'css', and 'js', "
        "each containing their respective code as a string. Additionally, ensure that all interactive "
        "elements call a global JavaScript function `window.triggerEvent(eventType, eventData)` with appropriate "
        "event types and data. The design should be clean, professional, and responsive."
    )

    user_prompt = (
        f"Create a GUI for a '{application_name}' application with the following parameters:\n"
        f"Current UI JSON: {json.dumps(current_ui) if current_ui else 'None'}\n"
        f"User Event: {json.dumps(user_event) if user_event else 'None'}\n"
        "Ensure the JSON response has the fields 'html', 'css', and 'js'. The HTML should structure the application, "
        "CSS should style it professionally, and JS should handle interactions by calling `window.triggerEvent`."
    )

    try:
        response = openai.ChatCompletion.create(
            model="gpt-4o-mini",  # or another suitable model
            messages=[
                {"role": "system", "content": prompt},
                {"role": "user", "content": user_prompt},
            ],
            temperature=0.3,
            max_tokens=2000,
        )
        content = response.choices[0].message['content'].strip()
        json_start = content.find('{')
        json_str = content[json_start:]
        ui_json = json.loads(json_str)

        # Validate the JSON structure
        if not all(key in ui_json for key in ['html', 'css', 'js']):
            raise ValueError("JSON response does not contain all required fields.")

        # Log the request and response
        log_entry = {
            'timestamp': datetime.utcnow().isoformat(),
            'application_name': application_name,
            'current_ui': current_ui,
            'user_event': user_event,
            'response': ui_json
        }
        llm_logs.append(log_entry)

        return ui_json
    except Exception as e:
        print(f"Error generating UI: {e}")
        return None

@app.route('/')
def index():
    # HTML, CSS, and JS are all inlined here
    return '''
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta httpequiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initialscale=1.0">
        <title>AI App Generator</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
                margin: 0;
                padding: 0;
                display: flex;
                flex-direction: column;
                align-items: center;
                min-height: 100vh;
            }
            .container {
                width: 90%;
                max-width: 1000px;
                margin-top: 30px;
            }
            .buttonsection {
                display: flex;
                justify-content: center;
                margin-bottom: 20px;
                gap: 10px;
            }
            .buttonsection button {
                padding: 10px 20px;
                font-size: 14px;
                border: none;
                background-color: #6c757d;
                color: white;
                cursor: pointer;
                border-radius: 4px;
            }
            .buttonsection button:hover {
                background-color: #5a6268;
            }
            .inputsection {
                display: flex;
                margin-bottom: 20px;
                gap: 10px;
            }
            .inputsection input {
                flex: 1;
                padding: 12px;
                font-size: 16px;
                border: 1px solid #ccc;
                border-radius: 4px;
                outline: none;
            }
            .inputsection button {
                padding: 12px 24px;
                font-size: 16px;
                border: none;
                background-color: #4285f4;
                color: white;
                cursor: pointer;
                border-radius: 4px;
            }
            .inputsection button:hover {
                background-color: #357ae8;
            }
            .generatedui {
                background-color: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                margin-bottom: 20px;
            }
            .logsection {
                background-color: #fff;
                padding: 15px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                height: 300px;
                overflow-y: scroll;
                width: 100%;
            }
            .logentry {
                font-family: monospace;
                font-size: 12px;
                margin-bottom: 5px;
            }
            h1, h2 {
                text-align: center;
                color: #333;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>AI App Generator</h1>
            <div class="buttonsection">
                <button onclick="refreshUI()">Refresh</button>
                <button onclick="clearUI()">Clear</button>
                <button onclick="saveUI()">Save</button>
            </div>
            <div class="inputsection">
                <input type="text" id="appInput" placeholder="Enter application name (e.g., Notepad, Music Player)">
                <button onclick="generateApp()">Send</button>
            </div>
            <div id="generatedUI" class="generatedui">
                <!-- Generated UI will appear here -->
            </div>
            <h2>LLM Interaction Logs</h2>
            <div id="logs" class="logsection">
                <!-- Logs will appear here -->
            </div>
        </div>
    
        <script>
            let currentUI = null;
    
            /**
             * JSON UI File Formats
    
             // JSON format received from the LLM:
             {
                 "html": "<div>...</div>",
                 "css": "/* CSS styles here */",
                 "js": "/* JavaScript code here */"
             }
    
             // JSON format saved by the application:
             {
                 "html": "<div>...</div>",
                 "css": "/* CSS styles here */",
                 "js": "/* JavaScript code here */",
                 "state": {
                     // Any additional state information, such as user inputs
                 }
             }
            */
    
            async function generateApp() {
                const appName = document.getElementById('appInput').value.trim();
                if (!appName) {
                    alert('Please enter an application name.');
                    return;
                }
    
                // Send request to generate UI
                const response = await fetch('/generate', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({application_name: appName})
                });
    
                if (response.ok) {
                    const uiJson = await response.json();
                    currentUI = uiJson;
                    renderUI(uiJson);
                    appendLog(`Generated UI for "${appName}".`);
                } else {
                    const error = await response.json();
                    alert('Error: ' + error.error);
                    appendLog(`Error generating UI for "${appName}": ${error.error}`);
                }
            }
    
            function renderUI(uiJson) {
                const generatedUI = document.getElementById('generatedUI');
                generatedUI.innerHTML = ''; // Clear previous UI
    
                // Create style element
                const style = document.createElement('style');
                style.innerHTML = uiJson.css;
                document.head.appendChild(style);
    
                // Create a container for the generated HTML
                const container = document.createElement('div');
                container.innerHTML = uiJson.html;
    
                // Append container to generatedUI div
                generatedUI.appendChild(container);
    
                // Execute the generated JS
                try {
                    const script = document.createElement('script');
                    script.innerHTML = uiJson.js;
                    document.body.appendChild(script);
                    appendLog('Executed generated JavaScript.');
                } catch (e) {
                    console.error('Error executing generated JS:', e);
                    appendLog('Error executing generated JavaScript.');
                }
            }
    
            async function handleEvent(eventType, eventData) {
                // Send event data to backend to get updated UI
                const response = await fetch('/event', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        event_type: eventType,
                        event_data: eventData
                    })
                });
    
                if (response.ok) {
                    const updatedUiJson = await response.json();
                    currentUI = updatedUiJson;
                    renderUI(updatedUiJson);
                    appendLog(`Handled event '${eventType}' with data: ${JSON.stringify(eventData)}`);
                } else {
                    const error = await response.json();
                    appendLog(`Error handling event '${eventType}': ${error.error}`);
                }
            }
    
            function appendLog(message) {
                const logs = document.getElementById('logs');
                const logEntry = document.createElement('div');
                logEntry.className = 'logentry';
                const timestamp = new Date().toLocaleString();
                logEntry.textContent = `[${timestamp}] ${message}`;
                logs.prepend(logEntry);
            }
    
            // Override the global triggerEvent function
            window.triggerEvent = function(eventType, eventData) {
                handleEvent(eventType, eventData);
            }
    
            // Function to refresh the current UI by requesting an improved version from the LLM
            async function refreshUI() {
                if (!currentUI) {
                    alert('No UI to refresh. Please generate an application first.');
                    return;
                }
    
                const appName = document.getElementById('appInput').value.trim() || 'DynamicApp';
    
                const response = await fetch('/refresh', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        application_name: appName,
                        current_ui: currentUI
                    })
                });
    
                if (response.ok) {
                    const updatedUiJson = await response.json();
                    currentUI = updatedUiJson;
                    renderUI(updatedUiJson);
                    appendLog(`Refreshed UI for "${appName}".`);
                } else {
                    const error = await response.json();
                    alert('Error: ' + error.error);
                    appendLog(`Error refreshing UI for "${appName}": ${error.error}`);
                }
            }
    
            // Function to clear the current UI
            function clearUI() {
                const generatedUI = document.getElementById('generatedUI');
                generatedUI.innerHTML = ''; // Clear UI
                currentUI = null;
                appendLog('Cleared the generated UI.');
            }
    
            // Function to save the current UI state to a JSON file
            async function saveUI() {
                if (!currentUI) {
                    alert('No UI to save.');
                    return;
                }
    
                const filename = prompt('Enter filename to save the UI (e.g., my_app.json):', `saved_ui_${Date.now()}.json`);
                if (!filename) {
                    alert('Save cancelled.');
                    return;
                }
    
                const response = await fetch('/save', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        ui_json: currentUI,
                        filename: filename
                    })
                });
    
                if (response.ok) {
                    const res = await response.json();
                    appendLog(`Saved UI to ${res.filepath}`);
                    alert(`UI saved successfully to ${res.filepath}`);
                } else {
                    const error = await response.json();
                    alert('Error: ' + error.error);
                    appendLog(`Error saving UI: ${error.error}`);
                }
            }
    
            // Periodically fetch and display logs from the server
            async function fetchLogs() {
                const response = await fetch('/logs');
                if (response.ok) {
                    const logs = await response.json();
                    const logsDiv = document.getElementById('logs');
                    logsDiv.innerHTML = ''; // Clear current logs
                    logs.slice(-100).reverse().forEach(log => { // Show last 100 logs
                        let logText = '';
                        if (log.application_name) {
                            logText = `[${new Date(log.timestamp).toLocaleString()}] Application: ${log.application_name}`;
                        } else if (log.event_type) {
                            logText = `[${new Date(log.timestamp).toLocaleString()}] Event: ${log.event_type} - Data: ${JSON.stringify(log.event_data)}`;
                        } else if (log.message) {
                            logText = `[${new Date(log.timestamp).toLocaleString()}] ${log.message}`;
                        }
                        const logEntry = document.createElement('div');
                        logEntry.className = 'logentry';
                        logEntry.textContent = logText;
                        logsDiv.appendChild(logEntry);
                    });
                }
            }
    
            // Fetch logs every 5 seconds
            setInterval(fetchLogs, 5000);
            // Initial fetch
            fetchLogs();
        </script>
    </body>
    </html>
    '''

@app.route('/generate', methods=['POST'])
def generate():
    data = request.get_json()
    application_name = data.get('application_name')
    current_ui = data.get('current_ui')
    user_event = data.get('user_event')

    if not application_name:
        return jsonify({'error': 'No application name provided.'}), 400

    ui_json = generate_ui(application_name, current_ui, user_event)
    if ui_json:
        return jsonify(ui_json)
    else:
        return jsonify({'error': 'Failed to generate UI.'}), 500

@app.route('/refresh', methods=['POST'])
def refresh():
    data = request.get_json()
    application_name = data.get('application_name', 'DynamicApp')
    current_ui = data.get('current_ui')

    if not current_ui:
        return jsonify({'error': 'No current UI provided for refresh.'}), 400

    ui_json = generate_ui(application_name, current_ui=current_ui)
    if ui_json:
        return jsonify(ui_json)
    else:
        return jsonify({'error': 'Failed to refresh UI.'}), 500

@app.route('/save', methods=['POST'])
def save_ui():
    data = request.get_json()
    ui_json = data.get('ui_json')
    filename = data.get('filename', f'saved_ui_{datetime.utcnow().isoformat()}.json')

    if not ui_json:
        return jsonify({'error': 'No UI JSON provided to save.'}), 400

    try:
        filepath = os.path.join(SAVE_DIR, filename)
        with open(filepath, 'w') as f:
            json.dump(ui_json, f, indent=4)
        append_log(f"UI saved to {filepath}")
        return jsonify({'status': 'UI saved successfully.', 'filepath': filepath}), 200
    except Exception as e:
        print(f"Error saving UI: {e}")
        return jsonify({'error': 'Failed to save UI.'}), 500

@app.route('/load', methods=['POST'])
def load_ui():
    data = request.get_json()
    filepath = data.get('filepath')

    if not filepath or not os.path.isfile(filepath):
        return jsonify({'error': 'Invalid or missing filepath.'}), 400

    try:
        with open(filepath, 'r') as f:
            ui_json = json.load(f)
        append_log(f"UI loaded from {filepath}")
        return jsonify(ui_json), 200
    except Exception as e:
        print(f"Error loading UI: {e}")
        return jsonify({'error': 'Failed to load UI.'}), 500

@app.route('/event', methods=['POST'])
def handle_event():
    data = request.get_json()
    event_type = data.get('event_type')
    event_data = data.get('event_data')

    if not event_type:
        return jsonify({'error': 'No event type provided.'}), 400

    # Retrieve the latest UI JSON from logs
    last_ui = None
    for log in reversed(llm_logs):
        if 'response' in log and log['response']:
            last_ui = log['response']
            break

    user_event = {
        'event_type': event_type,
        'event_data': event_data
    }

    # Generate updated UI based on the event
    updated_ui = generate_ui("DynamicApp", current_ui=last_ui, user_event=user_event)

    if updated_ui:
        append_log(f"Event '{event_type}' handled with data: {event_data}")
        return jsonify(updated_ui)
    else:
        return jsonify({'error': 'Failed to update UI based on event.'}), 500

@app.route('/logs', methods=['GET'])
def get_logs():
    return jsonify(llm_logs[-100:]), 200  # Return last 100 logs

def append_log(message):
    log_entry = {
        'timestamp': datetime.utcnow().isoformat(),
        'message': message
    }
    llm_logs.append(log_entry)

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