i want the following code to include two buttons, one to clear chat and the other to clear the triggers. <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Text Message Experience</title>
<style>
:root {
    --primary-color: #FF69B4;
    --secondary-color: #FFB6C1;
    --background-color: #FFF0F5;
    --text-color: #4A0E1C;
    --gradient-start: #FF1493;
    --gradient-end: #FF69B4;
}
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    margin: 0;
    padding: 0;
    background-color: var(--background-color);
}
.container {
    max-width: 600px;
    margin: 0 auto;
    background-color: #fff;
    box-shadow: 0 0 30px rgba(255, 105, 180, 0.2);
    height: 100vh;
    display: flex;
    flex-direction: column;
}
.header {
    background: linear-gradient(135deg, var(--gradient-start), var(--gradient-end));
    color: white;
    padding: 20px;
    text-align: center;
    position: relative;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.header h1 {
    margin: 0;
    font-size: 32px;
    text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
    letter-spacing: 2px;
}
.main-buttons {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    height: calc(100vh - 80px);
    background-color: var(--background-color);
    background-image:
        radial-gradient(circle at 10% 20%, rgba(255, 182, 193, 0.2) 0%, transparent 20%),
        radial-gradient(circle at 90% 80%, rgba(255, 105, 180, 0.2) 0%, transparent 20%),
        url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ff69b4' fill-opacity='0.1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}
.main-button {
    background: linear-gradient(135deg, var(--gradient-start), var(--gradient-end));
    color: white;
    border: none;
    padding: 20px 40px;
    font-size: 24px;
    border-radius: 50px;
    cursor: pointer;
    width: 80%;
    max-width: 300px;
    margin: 15px 0;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    text-transform: uppercase;
    letter-spacing: 2px;
    position: relative;
    overflow: hidden;
}
.main-button:before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(120deg, transparent, rgba(255,255,255,0.3), transparent);
    transition: all 0.5s;
}
.main-button:hover:before {
    left: 100%;
}
.main-button:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 8px rgba(0,0,0,0.15);
}
.back-button {
    position: absolute;
    top: 50%;
    left: 10px;
    transform: translateY(-50%);
    background: none;
    border: none;
    cursor: pointer;
    font-size: 24px;
    color: white;
    transition: all 0.3s ease;
}
.back-button:hover {
    transform: translateY(-50%) scale(1.1);
}
.chat-container, .create-container {
    display: none;
    flex-direction: column;
    flex-grow: 1;
    height: 100vh;
    background-color: var(--background-color);
    background-image:
        radial-gradient(circle at 10% 20%, rgba(255, 182, 193, 0.2) 0%, transparent 20%),
        radial-gradient(circle at 90% 80%, rgba(255, 105, 180, 0.2) 0%, transparent 20%),
        url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ff69b4' fill-opacity='0.1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}
.chat-header {
    background-color: var(--primary-color);
    color: white;
    padding: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.profile-picture {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    border: 2px solid white;
}
.contact-name {
    font-size: 20px;
    font-weight: bold;
}
.chat-messages {
    flex-grow: 1;
    overflow-y: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
}
.message {
    max-width: 70%;
    margin-bottom: 10px;
    padding: 12px 16px;
    border-radius: 20px;
    line-height: 1.4;
    display: inline-block;
    animation: fadeIn 0.3s ease-out;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}
.system-message {
    background-color: var(--secondary-color);
    color: var(--text-color);
    align-self: flex-start;
    border-bottom-left-radius: 5px;
}
.user-message {
    background-color: var(--primary-color);
    color: white;
    align-self: flex-end;
    border-bottom-right-radius: 5px;
}
.chat-input {
    display: flex;
    padding: 15px;
    background-color: white;
    border-top: 1px solid var(--secondary-color);
}
.chat-input input {
    flex-grow: 1;
    border: 1px solid var(--secondary-color);
    border-radius: 25px;
    padding: 12px 20px;
    font-size: 16px;
    outline: none;
    transition: all 0.3s ease;
}
.chat-input input:focus {
    box-shadow: 0 0 5px rgba(255, 105, 180, 0.5);
}
.chat-input button {
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    margin-left: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}
.chat-input button:hover {
    background-color: var(--gradient-start);
    transform: scale(1.05);
}
.video-message, .photo-message {
    max-width: 70%;
    margin-bottom: 10px;
    align-self: flex-start;
}
.video-message video, .photo-message img {
    max-width: 100%;
    border-radius: 20px;
    max-height: 300px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.create-form {
    display: flex;
    flex-direction: column;
    gap: 15px;
    padding: 20px;
    background-color: transparent;
}
.create-form input[type="text"],
.create-form input[type="number"],
.create-form select {
    padding: 12px;
    border: 1px solid var(--secondary-color);
    border-radius: 25px;
    font-size: 16px;
    transition: all 0.3s ease;
    background-color: rgba(255, 255, 255, 0.8);
}
.create-form input[type="text"]:focus,
.create-form input[type="number"]:focus,
.create-form select:focus {
    outline: none;
    box-shadow: 0 0 5px rgba(255, 105, 180, 0.5);
}
.create-form button {
    background-color: var(--primary-color);
    color: white;
    border: none;
    padding: 12px;
    border-radius: 25px;
    cursor: pointer;
    font-size: 18px;
    transition: all 0.3s ease;
}
.create-form button:hover {
    background-color: var(--gradient-start);
    transform: translateY(-2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.trigger-list {
    margin-top: 20px;
    border-top: 1px solid var(--secondary-color);
    padding-top: 10px;
}
.media-upload, .message-input, .poll-option {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-bottom: 10px;
}
.media-upload input[type="file"],
.media-upload input[type="number"],
.message-input input[type="text"],
.message-input input[type="number"],
.poll-option input[type="text"] {
    width: 100%;
}
.typing-indicator {
    color: #888;
    font-style: italic;
    margin-bottom: 10px;
    display: none;
    align-self: flex-start;
    background-color: var(--secondary-color);
    padding: 8px 12px;
    border-radius: 18px;
    font-size: 14px;
    animation: pulse 1.5s infinite;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
@keyframes pulse {
    0% { opacity: 0.5; }
    50% { opacity: 1; }
    100% { opacity: 0.5; }
}
.typing-indicator::after {
    content: '';
    display: inline-block;
    animation: ellipsis 1.5s infinite;
    width: 20px;
    text-align: left;
}
@keyframes ellipsis {
    0% { content: ''; }
    25% { content: '.'; }
    50% { content: '..'; }
    75% { content: '...'; }
    100% { content: ''; }
}
</style>
</head>
<body>
<div class="container">
    <div id="startupScreen">
        <div class="header">
            <h1>Text Message Experience</h1>
        </div>
        <div class="main-buttons" id="mainButtons">
            <button class="main-button" id="createButton">CREATE</button>
            <button class="main-button" id="enjoyButton">ENJOY</button>
        </div>
    </div>
    <div class="create-container" id="createContainer">
        <div class="header">
            <button class="back-button" id="createBackButton">&#8592;</button>
            <h2 style="font-size: 20px; margin: 0;">Create New Trigger</h2>
        </div>
        <form id="createForm" class="create-form">
            <input type="text" id="triggerInput" placeholder="Enter trigger phrase" required>
            <div>
                <input type="checkbox" id="hasMessage">
                <label for="hasMessage">Include message(s)</label>
            </div>
            <div id="messageOptions" style="display: none;">
                <select id="messageCount">
                    <option value="1">1 message</option>
                    <option value="2">2 messages</option>
                    <option value="3">3 messages</option>
                    <option value="4">4 messages</option>
                    <option value="5">5 messages</option>
                </select>
                <div id="messageInputs"></div>
            </div>
            <div>
                <input type="checkbox" id="hasMedia">
                <label for="hasMedia">Include media</label>
            </div>
            <div id="mediaOptions" style="display: none;">
                <select id="mediaCount">
                    <option value="1">1 item</option>
                    <option value="2">2 items</option>
                    <option value="3">3 items</option>
                    <option value="4">4 items</option>
                    <option value="5">5 items</option>
                </select>
                <div id="mediaUploads"></div>
            </div>
            <div>
                <input type="checkbox" id="hasPoll">
                <label for="hasPoll">Include poll</label>
            </div>
            <div id="pollOptions" style="display: none;">
                <select id="pollButtonCount">
                    <option value="2">2 buttons</option>
                    <option value="3">3 buttons</option>
                    <option value="4">4 buttons</option>
                </select>
                <input type="file" id="pollVideo" accept="video/*">
                <input type="number" id="pollDelay" placeholder="Poll delay (seconds)" value="1" min="0">
                <div id="pollButtons"></div>
            </div>
            <button type="submit">Save Trigger</button>
        </form>
        <div class="trigger-list">
            <h3>Saved Triggers:</h3>
            <ul id="triggerList"></ul>
        </div>
    </div>
    <div class="chat-container" id="chatContainer">
        <div class="chat-header">
            <button class="back-button" id="chatBackButton">&#8592;</button>
            <img src="img/pfppic.jpg" alt="Profile Picture" class="profile-picture">
            <span class="contact-name">WIP</span>
        </div>
        <div class="chat-messages" id="chatMessages">
            <!-- Messages will be dynamically added here -->
            <div class="typing-indicator" id="typingIndicator">WIP is typing</div>
        </div>
        <div class="chat-input">
            <input type="text" id="chatMessageInput" placeholder="Type a message...">
            <button id="sendButton">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="22" y1="2" x2="11" y2="13"></line>
                    <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                </svg>
            </button>
        </div>
    </div>
</div>
<script>
// IndexedDB setup
let db;
const dbName = 'ChatAppDB';
const dbVersion = 1;

const request = indexedDB.open(dbName, dbVersion);

request.onerror = function(event) {
    console.error("IndexedDB error:", event.target.error);
};

request.onsuccess = function(event) {
    db = event.target.result;
    console.log("IndexedDB opened successfully");
    loadSavedTriggers();
    loadChatHistory();
};

request.onupgradeneeded = function(event) {
    db = event.target.result;
    const triggerStore = db.createObjectStore('triggers', { keyPath: 'id', autoIncrement: true });
    const chatStore = db.createObjectStore('chatMessages', { keyPath: 'id', autoIncrement: true });
    console.log("Object stores created");
};

// DOM elements
const startupScreen = document.getElementById('startupScreen');
const createContainer = document.getElementById('createContainer');
const chatContainer = document.getElementById('chatContainer');
const chatMessages = document.getElementById('chatMessages');
const chatMessageInput = document.getElementById('chatMessageInput');
const sendButton = document.getElementById('sendButton');
const createButton = document.getElementById('createButton');
const enjoyButton = document.getElementById('enjoyButton');
const createBackButton = document.getElementById('createBackButton');
const chatBackButton = document.getElementById('chatBackButton');
const typingIndicator = document.getElementById('typingIndicator');
const createForm = document.getElementById('createForm');
const triggerInput = document.getElementById('triggerInput');
const hasMessage = document.getElementById('hasMessage');
const messageOptions = document.getElementById('messageOptions');
const messageCount = document.getElementById('messageCount');
const messageInputs = document.getElementById('messageInputs');
const hasMedia = document.getElementById('hasMedia');
const mediaOptions = document.getElementById('mediaOptions');
const mediaCount = document.getElementById('mediaCount');
const mediaUploads = document.getElementById('mediaUploads');
const hasPoll = document.getElementById('hasPoll');
const pollOptions = document.getElementById('pollOptions');
const pollButtonCount = document.getElementById('pollButtonCount');
const pollVideo = document.getElementById('pollVideo');
const pollDelay = document.getElementById('pollDelay');
const pollButtons = document.getElementById('pollButtons');
const triggerList = document.getElementById('triggerList');

let savedTriggers = [];

// Event listeners
hasMessage.addEventListener('change', function() {
    messageOptions.style.display = this.checked ? 'block' : 'none';
    updateMessageInputs();
});

hasMedia.addEventListener('change', function() {
    mediaOptions.style.display = this.checked ? 'block' : 'none';
    updateMediaUploads();
});

hasPoll.addEventListener('change', function() {
    pollOptions.style.display = this.checked ? 'block' : 'none';
    updatePollButtons();
});

messageCount.addEventListener('change', updateMessageInputs);
mediaCount.addEventListener('change', updateMediaUploads);
pollButtonCount.addEventListener('change', updatePollButtons);

// Helper functions
function updateMessageInputs() {
    messageInputs.innerHTML = '';
    const count = parseInt(messageCount.value);
    for (let i = 0; i < count; i++) {
        const messageInputDiv = document.createElement('div');
        messageInputDiv.classList.add('message-input');
        const input = document.createElement('input');
        input.type = 'text';
        input.placeholder = `Message ${i + 1}`;
        const delayInput = document.createElement('input');
        delayInput.type = 'number';
        delayInput.placeholder = `Message ${i + 1} delay (seconds)`;
        delayInput.value = '1';
        delayInput.min = '0';
        messageInputDiv.appendChild(input);
        messageInputDiv.appendChild(delayInput);
        messageInputs.appendChild(messageInputDiv);
    }
}

function updateMediaUploads() {
    mediaUploads.innerHTML = '';
    const count = parseInt(mediaCount.value);
    for (let i = 0; i < count; i++) {
        const mediaUploadDiv = document.createElement('div');
        mediaUploadDiv.classList.add('media-upload');
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'video/*,image/*';
        const delayInput = document.createElement('input');
        delayInput.type = 'number';
        delayInput.placeholder = `Media ${i + 1} delay (seconds)`;
        delayInput.value = '1';
        delayInput.min = '0';
        mediaUploadDiv.appendChild(input);
        mediaUploadDiv.appendChild(delayInput);
        mediaUploads.appendChild(mediaUploadDiv);
    }
}

function updatePollButtons() {
    pollButtons.innerHTML = '';
    const count = parseInt(pollButtonCount.value);
    for (let i = 0; i < count; i++) {
        const pollOptionDiv = document.createElement('div');
        pollOptionDiv.classList.add('poll-option');
        const input = document.createElement('input');
        input.type = 'text';
        input.placeholder = `Button ${i + 1} text`;
        pollOptionDiv.appendChild(input);
        pollButtons.appendChild(pollOptionDiv);
    }
}

// Save trigger to IndexedDB
function saveTrigger(trigger) {
    const transaction = db.transaction(['triggers'], 'readwrite');
    const store = transaction.objectStore('triggers');
    const request = store.add(trigger);

    request.onsuccess = function(event) {
        console.log("Trigger added to the store", event.target.result);
        loadSavedTriggers();
    };

    request.onerror = function(event) {
        console.error("Error adding trigger:", event.target.error);
    };
}

// Load saved triggers from IndexedDB
function loadSavedTriggers() {
    const transaction = db.transaction(['triggers'], 'readonly');
    const store = transaction.objectStore('triggers');
    const request = store.getAll();

    request.onsuccess = function(event) {
        savedTriggers = event.target.result;
        updateTriggerList();
    };

    request.onerror = function(event) {
        console.error("Error loading triggers:", event.target.error);
    };
}

// Update trigger list in UI
function updateTriggerList() {
    triggerList.innerHTML = '';
    savedTriggers.forEach(trigger => {
        const li = document.createElement('li');
        li.textContent = trigger.trigger;
        triggerList.appendChild(li);
    });
}

// Create form submit event
createForm.addEventListener('submit', function(e) {
    e.preventDefault();

    const newTrigger = {
        trigger: triggerInput.value,
        hasMessage: hasMessage.checked,
        messages: Array.from(messageInputs.querySelectorAll('.message-input')).map(div => ({
            text: div.querySelector('input[type="text"]').value,
            delay: parseInt(div.querySelector('input[type="number"]').value) || 1
        })),
        hasMedia: hasMedia.checked,
        media: [],
        hasPoll: hasPoll.checked,
        poll: hasPoll.checked ? {
            delay: parseInt(pollDelay.value) || 1,
            buttons: Array.from(pollButtons.querySelectorAll('.poll-option input')).map(input => input.value)
        } : null
    };

    // Handle media files
    const mediaFiles = Array.from(mediaUploads.querySelectorAll('.media-upload')).map(div => ({
        file: div.querySelector('input[type="file"]').files[0],
        delay: parseInt(div.querySelector('input[type="number"]').value) || 1
    })).filter(media => media.file !== undefined);

    // Handle poll video
    const pollVideoFile = pollVideo.files[0];

    // Use FileReader to read file contents
    const fileReadPromises = mediaFiles.map(media => 
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => resolve({ data: e.target.result, delay: media.delay, type: media.file.type });
            reader.onerror = reject;
            reader.readAsArrayBuffer(media.file);
        })
    );

    if (pollVideoFile) {
        fileReadPromises.push(new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => resolve({ data: e.target.result, type: pollVideoFile.type });
            reader.onerror = reject;
            reader.readAsArrayBuffer(pollVideoFile);
        }));
    }

    Promise.all(fileReadPromises)
        .then(results => {
            newTrigger.media = results.slice(0, mediaFiles.length);
            if (pollVideoFile) {
                newTrigger.poll.video = results[results.length - 1];
            }
            saveTrigger(newTrigger);
            createForm.reset();
            messageOptions.style.display = 'none';
            mediaOptions.style.display = 'none';
            pollOptions.style.display = 'none';
            messageInputs.innerHTML = '';
            mediaUploads.innerHTML = '';
            pollButtons.innerHTML = '';
        })
        .catch(error => console.error("Error reading files:", error));
});

// Chat functionality
function scrollToBottom() {
    setTimeout(() => {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }, 0);
}

function addMessage(content, isSystem = true) {
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('message', isSystem ? 'system-message' : 'user-message');
    messageDiv.textContent = content;
    chatMessages.insertBefore(messageDiv, typingIndicator);
    scrollToBottom();

    // Save message to IndexedDB
    const message = { content, isSystem, timestamp: new Date() };
    const transaction = db.transaction(['chatMessages'], 'readwrite');
    const store = transaction.objectStore('chatMessages');
    store.add(message);
}

function addMedia(file, type) {
    const mediaDiv = document.createElement('div');
    if (type.startsWith('video/')) {
        mediaDiv.classList.add('video-message');
        const videoElement = document.createElement('video');
        videoElement.src = URL.createObjectURL(new Blob([file], { type }));
        videoElement.autoplay = true;
        videoElement.muted = false;
        videoElement.controls = false;
        videoElement.playsInline = true;
        videoElement.loop = false;
        videoElement.addEventListener('loadedmetadata', () => {
            videoElement.play().catch(error => console.error("Autoplay failed:", error));
            scrollToBottom();
        });
        mediaDiv.appendChild(videoElement);
    } else if (type.startsWith('image/')) {
        mediaDiv.classList.add('photo-message');
        const imgElement = document.createElement('img');
        imgElement.src = URL.createObjectURL(new Blob([file], { type }));
        imgElement.alt = 'Shared photo';
        imgElement.onload = scrollToBottom;
        mediaDiv.appendChild(imgElement);
    }
    chatMessages.insertBefore(mediaDiv, typingIndicator);
    scrollToBottom();

    // Save media to IndexedDB
    const mediaMessage = { file, type, timestamp: new Date() };
    const transaction = db.transaction(['chatMessages'], 'readwrite');
    const store = transaction.objectStore('chatMessages');
    store.add(mediaMessage);
}

function addPoll(poll) {
    const pollDiv = document.createElement('div');
    pollDiv.classList.add('poll-message');
    const videoElement = document.createElement('video');
    videoElement.src = URL.createObjectURL(new Blob([poll.video.data], { type: poll.video.type }));
    videoElement.autoplay = true;
    videoElement.muted = false;
    videoElement.controls = false;
    videoElement.playsInline = true;
    videoElement.loop = false;
    videoElement.addEventListener('loadedmetadata', () => {
        videoElement.play().catch(error => console.error("Autoplay failed:", error));
        scrollToBottom();
    });
    pollDiv.appendChild(videoElement);
    const buttonsDiv = document.createElement('div');
    buttonsDiv.classList.add('poll-buttons');
    poll.buttons.forEach(buttonText => {
        const button = document.createElement('button');
        button.textContent = buttonText;
        button.addEventListener('click', () => {
            chatMessageInput.value = buttonText;
            sendMessage();
        });
        buttonsDiv.appendChild(button);
    });
    pollDiv.appendChild(buttonsDiv);
    chatMessages.insertBefore(pollDiv, typingIndicator);
    scrollToBottom();

    // Save poll to IndexedDB
    const pollMessage = { poll, timestamp: new Date() };
    const transaction = db.transaction(['chatMessages'], 'readwrite');
    const store = transaction.objectStore('chatMessages');
    store.add(pollMessage);
}

function showTypingIndicator() {
    typingIndicator.style.display = 'block';
    scrollToBottom();
}

function hideTypingIndicator() {
    typingIndicator.style.display = 'none';
    scrollToBottom();
}

async function sendMessage() {
    const message = chatMessageInput.value.trim();
    if (message) {
        addMessage(message, false);
        chatMessageInput.value = '';
        const trigger = savedTriggers.find(t => t.trigger.toLowerCase() === message.toLowerCase());
        if (trigger) {
            if (trigger.hasMessage) {
                for (const msg of trigger.messages) {
                    showTypingIndicator();
                    await new Promise(resolve => setTimeout(resolve, msg.delay * 1000));
                    hideTypingIndicator();
                    addMessage(msg.text);
                }
            }
            if (trigger.hasMedia) {
                for (const media of trigger.media) {
                    showTypingIndicator();
                    await new Promise(resolve => setTimeout(resolve, media.delay * 1000));
                    hideTypingIndicator();
                    addMedia(media.data, media.type);
                }
            }
            if (trigger.hasPoll) {
                showTypingIndicator();
                await new Promise(resolve => setTimeout(resolve, trigger.poll.delay * 1000));
                hideTypingIndicator();
                addPoll(trigger.poll);
            }
        }
    }
}

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

createButton.addEventListener('click', function() {
    startupScreen.style.display = 'none';
    createContainer.style.display = 'flex';
});

enjoyButton.addEventListener('click', function() {
    startupScreen.style.display = 'none';
    chatContainer.style.display = 'flex';
});

createBackButton.addEventListener('click', function() {
    createContainer.style.display = 'none';
    startupScreen.style.display = 'block';
});

chatBackButton.addEventListener('click', function() {
    chatContainer.style.display = 'none';
    startupScreen.style.display = 'block';
});

// Load chat history from IndexedDB
function loadChatHistory() {
    const transaction = db.transaction(['chatMessages'], 'readonly');
    const store = transaction.objectStore('chatMessages');
    const request = store.getAll();

    request.onsuccess = function(event) {
        const messages = event.target.result;
        messages.sort((a, b) => a.timestamp - b.timestamp);
        
        messages.forEach(message => {
            if (message.content) {
                addMessage(message.content, message.isSystem);
            } else if (message.file) {
                addMedia(message.file, message.type);
            } else if (message.poll) {
                addPoll(message.poll);
            }
        });
    };

    request.onerror = function(event) {
        console.error("Error loading chat history:", event.target.error);
    };
}

// Clear chat history
function clearChatHistory() {
    const transaction = db.transaction(['chatMessages'], 'readwrite');
    const store = transaction.objectStore('chatMessages');
    const request = store.clear();

    request.onsuccess = function(event) {
        console.log("Chat history cleared");
        chatMessages.innerHTML = '';
    };

    request.onerror = function(event) {
        console.error("Error clearing chat history:", event.target.error);
    };
}

// Clear triggers
function clearTriggers() {
    const transaction = db.transaction(['triggers'], 'readwrite');
    const store = transaction.objectStore('triggers');
    const request = store.clear();

    request.onsuccess = function(event) {
        console.log("Triggers cleared");
        savedTriggers = [];
        updateTriggerList();
    };

    request.onerror = function(event) {
        console.error("Error clearing triggers:", event.target.error);
    };
}

// Export data
function exportData() {
    const data = {
        triggers: savedTriggers,
        chatMessages: []
    };

    const transaction = db.transaction(['chatMessages'], 'readonly');
    const store = transaction.objectStore('chatMessages');
    const request = store.getAll();

    request.onsuccess = function(event) {
        data.chatMessages = event.target.result;
        const dataStr = JSON.stringify(data);
        const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
        const exportFileDefaultName = 'chat_app_data.json';

        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();
    };

    request.onerror = function(event) {
        console.error("Error exporting data:", event.target.error);
    };
}

// Import data
function importData(file) {
    const reader = new FileReader();
    reader.onload = function(event) {
        try {
            const data = JSON.parse(event.target.result);
            
            // Clear existing data
            clearChatHistory();
            clearTriggers();

            // Import triggers
            data.triggers.forEach(trigger => saveTrigger(trigger));

            // Import chat messages
            const transaction = db.transaction(['chatMessages'], 'readwrite');
            const store = transaction.objectStore('chatMessages');
            data.chatMessages.forEach(message => store.add(message));

            transaction.oncomplete = function() {
                console.log("Data import completed");
                loadChatHistory();
            };
        } catch (error) {
            console.error("Error importing data:", error);
        }
    };
    reader.readAsText(file);
}

// Add event listeners for data management buttons
document.getElementById('clearHistoryButton').addEventListener('click', clearChatHistory);
document.getElementById('clearTriggersButton').addEventListener('click', clearTriggers);
document.getElementById('exportDataButton').addEventListener('click', exportData);

const importDataInput = document.getElementById('importDataInput');
importDataInput.addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        importData(file);
    }
});

document.getElementById('importDataButton').addEventListener('click', function() {
    importDataInput.click();
});

// Initialize the form
updateMessageInputs();
updateMediaUploads();
updatePollButtons();

// Service Worker Registration for PWA support
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}

// Add to Home Screen functionality
let deferredPrompt;
const addToHomeScreenButton = document.getElementById('addToHomeScreenButton');

window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferredPrompt = e;
    addToHomeScreenButton.style.display = 'block';
});

addToHomeScreenButton.addEventListener('click', (e) => {
    addToHomeScreenButton.style.display = 'none';
    deferredPrompt.prompt();
    deferredPrompt.userChoice.then((choiceResult) => {
        if (choiceResult.outcome === 'accepted') {
            console.log('User accepted the A2HS prompt');
        } else {
            console.log('User dismissed the A2HS prompt');
        }
        deferredPrompt = null;
    });
});

// Offline functionality
window.addEventListener('online', function() {
    console.log('App is online');
    document.body.classList.remove('offline');
});

window.addEventListener('offline', function() {
    console.log('App is offline');
    document.body.classList.add('offline');
});

// Check if the app is already offline
if (!navigator.onLine) {
    document.body.classList.add('offline');
}

// Implement lazy loading for chat messages
let isLoading = false;
let lastLoadedId = 0;
const messagesPerLoad = 20;

chatMessages.addEventListener('scroll', function() {
    if (chatMessages.scrollTop === 0 && !isLoading) {
        loadMoreMessages();
    }
});

function loadMoreMessages() {
    isLoading = true;
    const transaction = db.transaction(['chatMessages'], 'readonly');
    const store = transaction.objectStore('chatMessages');
    const request = store.openCursor(null, 'prev');
    let count = 0;

    request.onsuccess = function(event) {
        const cursor = event.target.result;
        if (cursor && count < messagesPerLoad) {
            if (cursor.value.id > lastLoadedId) {
                const message = cursor.value;
                if (message.content) {
                    prependMessage(message.content, message.isSystem);
                } else if (message.file) {
                    prependMedia(message.file, message.type);
                } else if (message.poll) {
                    prependPoll(message.poll);
                }
                lastLoadedId = message.id;
                count++;
                cursor.continue();
            } else {
                cursor.continue();
            }
        } else {
            isLoading = false;
        }
    };

    request.onerror = function(event) {
        console.error("Error loading more messages:", event.target.error);
        isLoading = false;
    };
}

function prependMessage(content, isSystem) {
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('message', isSystem ? 'system-message' : 'user-message');
    messageDiv.textContent = content;
    chatMessages.insertBefore(messageDiv, chatMessages.firstChild);
}

function prependMedia(file, type) {
    const mediaDiv = document.createElement('div');
    if (type.startsWith('video/')) {
        mediaDiv.classList.add('video-message');
        const videoElement = document.createElement('video');
        videoElement.src = URL.createObjectURL(new Blob([file], { type }));
        videoElement.controls = true;
        mediaDiv.appendChild(videoElement);
    } else if (type.startsWith('image/')) {
        mediaDiv.classList.add('photo-message');
        const imgElement = document.createElement('img');
        imgElement.src = URL.createObjectURL(new Blob([file], { type }));
        imgElement.alt = 'Shared photo';
        mediaDiv.appendChild(imgElement);
    }
    chatMessages.insertBefore(mediaDiv, chatMessages.firstChild);
}

function prependPoll(poll) {
    const pollDiv = document.createElement('div');
    pollDiv.classList.add('poll-message');
    const videoElement = document.createElement('video');
    videoElement.src = URL.createObjectURL(new Blob([poll.video.data], { type: poll.video.type }));
    videoElement.controls = true;
    pollDiv.appendChild(videoElement);
    const buttonsDiv = document.createElement('div');
    buttonsDiv.classList.add('poll-buttons');
    poll.buttons.forEach(buttonText => {
        const button = document.createElement('button');
        button.textContent = buttonText;
        button.addEventListener('click', () => {
            chatMessageInput.value = buttonText;
            sendMessage();
        });
        buttonsDiv.appendChild(button);
    });
    pollDiv.appendChild(buttonsDiv);
    chatMessages.insertBefore(pollDiv, chatMessages.firstChild);
}

// Implement search functionality
const searchInput = document.getElementById('searchInput');
const searchResults = document.getElementById('searchResults');

searchInput.addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase();
    if (searchTerm.length < 3) {
        searchResults.innerHTML = '';
        return;
    }

    const transaction = db.transaction(['chatMessages'], 'readonly');
    const store = transaction.objectStore('chatMessages');
    const request = store.openCursor();
    const results = [];

    request.onsuccess = function(event) {
        const cursor = event.target.result;
        if (cursor) {
            const message = cursor.value;
            if (message.content && message.content.toLowerCase().includes(searchTerm)) {
                results.push(message);
            }
            cursor.continue();
        } else {
            displaySearchResults(results);
        }
    };

    request.onerror = function(event) {
        console.error("Error searching messages:", event.target.error);
    };
});

function displaySearchResults(results) {
    searchResults.innerHTML = '';
    results.forEach(result => {
        const resultDiv = document.createElement('div');
        resultDiv.classList.add('search-result');
        resultDiv.textContent = result.content;
        resultDiv.addEventListener('click', () => {
            scrollToMessage(result.id);
        });
        searchResults.appendChild(resultDiv);
    });
}

function scrollToMessage(messageId) {
    const messageElements = chatMessages.querySelectorAll('.message');
    for (let i = 0; i < messageElements.length; i++) {
        if (messageElements[i].dataset.id === messageId.toString()) {
            messageElements[i].scrollIntoView({ behavior: 'smooth', block: 'center' });
            messageElements[i].classList.add('highlighted');
            setTimeout(() => {
                messageElements[i].classList.remove('highlighted');
            }, 2000);
            break;
        }
    }
}

// Implement message editing and deletion
function addContextMenu(messageElement, messageId) {
    messageElement.addEventListener('contextmenu', function(e) {
        e.preventDefault();
        const contextMenu = document.createElement('div');
        contextMenu.classList.add('context-menu');
        
        const editOption = document.createElement('div');
        editOption.textContent = 'Edit';
        editOption.addEventListener('click', () => editMessage(messageId));
        
        const deleteOption = document.createElement('div');
        deleteOption.textContent = 'Delete';
        deleteOption.addEventListener('click', () => deleteMessage(messageId));
        
        contextMenu.appendChild(editOption);
        contextMenu.appendChild(deleteOption);
        
        document.body.appendChild(contextMenu);
        
        contextMenu.style.top = `${e.clientY}px`;
        contextMenu.style.left = `${e.clientX}px`;
        
        document.addEventListener('click', function removeMenu() {
            contextMenu.remove();
            document.removeEventListener('click', removeMenu);
        });
    });
}

function editMessage(messageId) {
    const transaction = db.transaction(['chatMessages'], 'readwrite');
    const store = transaction.objectStore('chatMessages');
    const request = store.get(messageId);

    request.onsuccess = function(event) {
        const message = event.target.result;
        const newContent = prompt('Edit message:', message.content);
        if (newContent !== null) {
            message.content = newContent;
            store.put(message);
            updateMessageInUI(messageId, newContent);
        }
    };

    request.onerror = function(event) {
        console.error("Error editing message:", event.target.error);
    };
}

function deleteMessage(messageId) {
    if (confirm('Are you sure you want to delete this message?')) {
        const transaction = db.transaction(['chatMessages'], 'readwrite');
        const store = transaction.objectStore('chatMessages');
        const request = store.delete(messageId);

        request.onsuccess = function(event) {
            removeMessageFromUI(messageId);
        };

        request.onerror = function(event) {
            console.error("Error deleting message:", event.target.error);
        };
    }
}

function updateMessageInUI(messageId, newContent) {
    const messageElement = document.querySelector(`.message[data-id="${messageId}"]`);
    if (messageElement) {
        messageElement.textContent = newContent;
    }
}

function removeMessageFromUI(messageId) {
    const messageElement = document.querySelector(`.message[data-id="${messageId}"]`);
    if (messageElement) {
        messageElement.remove();
    }
}

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    // Open IndexedDB connection
    const dbOpenRequest = indexedDB.open(dbName, dbVersion);
    dbOpenRequest.onsuccess = function(event) {
        db = event.target.result;
        loadSavedTriggers();
        loadChatHistory();
    };

    // Set up event listeners
    sendButton.addEventListener('click', sendMessage);
    chatMessageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    createButton.addEventListener('click', function() {
        startupScreen.style.display = 'none';
        createContainer.style.display = 'flex';
    });

    enjoyButton.addEventListener('click', function() {
        startupScreen.style.display = 'none';
        chatContainer.style.display = 'flex';
    });

    createBackButton.addEventListener('click', function() {
        createContainer.style.display = 'none';
        startupScreen.style.display = 'block';
    });

    chatBackButton.addEventListener('click', function() {
        chatContainer.style.display = 'none';
        startupScreen.style.display = 'block';
    });

    // Initialize form elements
    updateMessageInputs();
    updateMediaUploads();
    updatePollButtons();
});

// Handle application cache updates for offline support
window.applicationCache.addEventListener('updateready', function() {
    if (window.applicationCache.status === window.applicationCache.UPDATEREADY) {
        if (confirm('A new version of this site is available. Load it?')) {
            window.location.reload();
        }
    }
});

// Implement push notifications (if supported by the browser)
if ('Notification' in window && 'PushManager' in window) {
    Notification.requestPermission().then(function(result) {
        if (result === 'granted') {
            console.log('Notification permission granted');
            subscribeToPushNotifications();
        }
    });
}

function subscribeToPushNotifications() {
    navigator.serviceWorker.ready.then(function(registration) {
        registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: urlBase64ToUint8Array('YOUR_PUBLIC_VAPID_KEY_HERE')
        }).then(function(subscription) {
            console.log('Push notification subscription successful', subscription);
            // Send the subscription details to your server
        }).catch(function(error) {
            console.error('Push notification subscription failed', error);
        });
    });
}

function urlBase64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}

// Final touch: Add a loading indicator
const loadingIndicator = document.createElement('div');
loadingIndicator.id = 'loadingIndicator';
loadingIndicator.textContent = 'Loading...';
document.body.appendChild(loadingIndicator);

window.addEventListener('load', function() {
    loadingIndicator.style.display = 'none';
});
</script>
</body>
</html>