improve the UI with these features "1. Visual Design Improvements
Modern Color Scheme: Update the color palette to a more contemporary and appealing scheme. Consider using shades of blue or teal, which are often associated with trust and professionalism. Tools like Coolors can help generate harmonious color palettes.
Typography Enhancements: Replace Georgia with modern, web-friendly fonts like Roboto, Open Sans, or Lato from Google Fonts. Improved typography enhances readability and the overall aesthetic.
Consistent Iconography: Ensure all icons are from the same icon set and style for a cohesive look. Utilize Bootstrap Icons or Font Awesome.
Visual Hierarchy: Use heading sizes, font weights, and colors to establish a clear visual hierarchy, guiding users through the content naturally.
Dark Mode: Implement a dark mode option to reduce eye strain and cater to user preferences. This involves defining alternative color variables for dark backgrounds.
2. Layout and Responsiveness
Responsive Design: Enhance mobile compatibility by ensuring all elements adapt seamlessly to various screen sizes. Utilize Bootstrap's grid system and responsive utilities.
Collapsible Sidebar: Make the sidebar collapsible to provide more screen space when needed, especially on smaller devices.
Sticky Header and Footer: Keep navigation elements visible as users scroll for easier access to controls and information.
3. User Experience Enhancements
Improved Navigation: Add breadcrumbs or a progress indicator within multi-step processes to help users understand where they are.
Tooltips and Help Text: Provide tooltips or inline help text for buttons and features that may not be immediately obvious.
Keyboard Shortcuts: Implement keyboard shortcuts for common actions like sending messages or toggling between tabs to increase efficiency for power users.
Drag-and-Drop File Upload: Enhance the file upload feature by allowing users to drag and drop files directly into the upload area.
Loading Indicators: Add progress bars or spinners during long operations (e.g., generating templates) to keep users informed.
Confirmation Dialogues: Use modals for confirming critical actions like deleting a session, with clear options to proceed or cancel.
4. Accessibility Improvements
Semantic HTML: Use appropriate HTML tags (e.g., <nav>, <main>, <footer>, <button>) to improve accessibility and SEO.
ARIA Labels: Incorporate ARIA attributes to improve screen reader support, ensuring all interactive elements are accessible.
Contrast Ratios: Ensure text and interactive elements have sufficient contrast against backgrounds for readability, adhering to WCAG guidelines.
Focus States: Design visible focus states for keyboard navigation, helping users who rely on the keyboard to navigate the interface.
5. Code Organization and Best Practices
External CSS and JS Files: Move inline styles and scripts to external files. This improves maintainability and leverages browser caching.

<!-- Link to external CSS -->
<link rel="stylesheet" href="styles.css">

<!-- Link to external JS -->
<script src="scripts.js" defer></script>
Modular JavaScript: Organize JS code using modules or classes to encapsulate functionality, making the codebase scalable and easier to debug.
Use CSS Preprocessors: Implement Sass or LESS for more efficient and organized styling, enabling variables, nesting, and mixins.
Naming Conventions: Adopt consistent naming conventions for classes and IDs (e.g., BEM methodology) to enhance code readability.
6. Performance Optimizations
Minification and Bundling: Use tools like Webpack, Gulp, or Grunt to minify and bundle CSS and JS files, reducing load times.
Deferred Script Loading: Use defer or async attributes on script tags to prevent render-blocking.
Image Optimization: Compress images and use modern formats like WebP. Implement responsive images with srcset to serve appropriate sizes.
Lazy Loading: Apply lazy loading for images and components that are not immediately visible on page load.
7. Feature Enhancements
Autosave Feature: Implement autosave in the editor to prevent data loss, with indicators showing when content is saved.
Version History: Allow users to view and revert to previous versions of their documents or chat sessions.
Template Previews: Provide live previews of templates before generating them to ensure they meet user expectations.
Customization Options: Let users customize the UI, such as choosing themes, adjusting font sizes, or rearranging panels.
Notifications Center: Create a centralized place for users to view alerts, updates, and messages from the application.
8. Enhanced Chat Functionality
Message Editing and Deletion: Allow users to edit or delete their messages within a certain timeframe.
Typing Indicators: Show when Athena is typing or processing a response to improve engagement.
Message Reactions: Enable users to react to messages with emojis or predefined responses.
Search in Chat: Implement a search function within chat sessions to help users find past messages.
9. Security Improvements
Content Security Policy (CSP): Define a robust CSP header to mitigate Cross-Site Scripting (XSS) and data injection attacks.
Input Validation and Sanitization: Ensure all user inputs are properly validated and sanitized on both client and server sides.
HTTPS Enforcement: Serve the application over HTTPS to encrypt data in transit and enhance user trust.
Authentication and Authorization: If applicable, integrate secure authentication mechanisms and manage user roles and permissions.
" "<!DOCTYPE html>
<html lang="en">
<head>
    <!-- ... existing head content ... -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enhanced Analytics Application</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- Include CKEditor 5 -->
    <script src="https://cdn.ckeditor.com/ckeditor5/35.3.2/classic/ckeditor.js"></script>
    <style>

    :root {
        --primary-color: rgb(244, 243, 238);  /* Light beige */
        --secondary-color: rgb(243, 242, 236); /* Another light beige */
        --text-color: #333;                   /* Dark gray for contrast */
        --bg-color: rgb(240, 238, 230);       /* Light off-white */
        --card-bg: rgb(240, 239, 231);        /* Very light gray/beige for card backgrounds */
        --border-color: rgb(241, 239, 232);   /* Subtle off-white for borders */
        --active-tab-color: #ae6040;          /* Shade of brown for active tabs */
        --sidebar-bg: #f8f9fa;                 /* Light gray for sidebar background */
        --sidebar-width: 250px;                /* Width of the sidebar */
    }

    body {
        font-family: Georgia, 'Times New Roman', Times, serif;
        background-color: var(--bg-color);
        color: var(--text-color);
    }

    /* Sidebar styling */
    #sidebar {
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        width: var(--sidebar-width);
        background-color: #F0EEE6;
        border-right: 1px solid #dee2e6;
        padding: 20px;
        overflow-y: auto;
    }

    #sidebar h3 {
        margin-bottom: 20px;
    }

    #chatSessions {
        list-style: none;
        padding: 0;
    }

    #chatSessions li {
        padding: 10px;
        margin-bottom: 10px;
        background-color: #F0EEE6; 
        border: 1px solid #dee2e6;
        border-radius: 5px;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    #chatSessions li.active {
        background-color: var(--active-tab-color);
        color: white;
    }

    #chatSessions li:hover {
        background-color: #e9ecef;
    }

    #chatSessions .delete-session {
        color: #dc3545;
        cursor: pointer;
        display: none;
    }

    #chatSessions li:hover .delete-session {
        display: block;
    }

    /* Main content adjustment to accommodate sidebar */
    .main-content {
        margin-left: var(--sidebar-width);
        padding: 20px;
    }

    .card {
        background-color: var(--card-bg);
        border: none;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .card-header {
        background-color: var(--primary-color);
        color: var(--text-color);
        font-weight: bold;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
    }

    #chatBox, #editorText {
        min-height: 400px;
        overflow-y: auto;
        background-color: var(--bg-color);
        border: 1px solid var(--border-color);
        border-radius: 5px;
        padding: 10px;
        font-family: Georgia, 'Times New Roman', Times, serif;
    }

    .user-message, .assistant-message {
        margin-bottom: 15px;
        max-width: 80%;
    }

    .user-message {
        margin-left: auto;
        background-color: white;
        color: var(--text-color);
        border-radius: 15px 15px 0 15px;
        padding: 10px 15px;
    }

    .assistant-message {
        background-color: white;
        border-radius: 15px 15px 15px 0;
        padding: 10px 15px;
        color: var(--text-color);
        white-space: pre-wrap; /* Preserves white space and line breaks */
    }

    .btn-primary {
        background-color: var(--primary-color);
        border:none;
        color: var(--text-color);
    }

    .btn-primary:hover {
        background-color: #ae6040;
        color: white;
    }

    .form-control {
        font-family: Georgia, 'Times New Roman', Times, serif;
    }

    .form-control:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.2rem rgba(74, 144, 226, 0.25);
    }

    .nav-tabs .nav-link {
        color: var(--text-color);
        font-family: Georgia, 'Times New Roman', Times, serif;
    }

    .nav-tabs .nav-link.active {
        color: white;
        background-color: var(--active-tab-color);
        font-weight: bold;
        border-color: var(--active-tab-color);
    }

    #improvementStatus {
        font-style: italic;
        color: #ae6040;
    }

    footer {
        margin-top: 30px;
        text-align: center;
        color: #666;
        font-size: 0.9em;
    }

    h1, h2, h3, h4, h5, h6 {
        font-family: Georgia, 'Times New Roman', Times, serif;
    }

    /* Styles for the Improve button */
    .improve-button {
        position: absolute;
        z-index: 1000;
    }

    .editor-toolbar {
        margin-bottom: 10px;
    }

    .editor-toolbar .btn {
        margin-right: 5px;
    }

    /* Styles for Inline Template Generator */
    #templateResult {
        display: none;
    }

    /* Ensure generated template messages match ATHENA's assistant messages */
    #generatedTemplateMessage {
        background-color: white;
        border-radius: 15px 15px 15px 0;
        padding: 10px 15px;
        color: var(--text-color);
        margin-top: 15px;
        white-space: pre-wrap; /* Preserves white space and line breaks */
    }

    /* Custom Modal Styles */
    #customModal .modal-content {
        background-color: var(--card-bg);
        color: var(--text-color);
        border: 1px solid var(--border-color);
        border-radius: 10px;
    }

    #customModal .modal-header {
        background-color: var(--primary-color);
        border-bottom: 1px solid var(--border-color);
    }

    #customModal .modal-footer {
        background-color: var(--secondary-color);
        border-top: 1px solid var(--border-color);
    }

    #customModal .btn-primary {
        background-color: var(--active-tab-color);
        border: none;
    }

    #customModal .btn-primary:hover {
        background-color: #ae6040;
        color: white;
    }

    </style>
</head>
<body>
    <!-- Sidebar -->
    <div id="sidebar">
        <h3>Chat Sessions</h3>
        <ul id="chatSessions">
            <!-- Chat sessions will be dynamically populated here -->
        </ul>
        <button class="btn btn-primary w-100" id="newSessionButton">
            <i class="fas fa-plus"></i> New Session
        </button>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <h1 class="text-center mb-4">ATHENA</h1>
        
        <ul class="nav nav-tabs mb-3" id="mainTab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="chat-tab" data-bs-toggle="tab" data-bs-target="#chat" type="button" role="tab" aria-controls="chat" aria-selected="true">
                    <i class="fas fa-comments"></i> Chat
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="editor-tab" data-bs-toggle="tab" data-bs-target="#editor" type="button" role="tab" aria-controls="editor" aria-selected="false">
                    <i class="fas fa-edit"></i> Editor
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="template-tab" data-bs-toggle="tab" data-bs-target="#template" type="button" role="tab" aria-controls="template" aria-selected="false">
                    <i class="fas fa-file-alt"></i> Template Generator
                </button>
            </li>
        </ul>
        
        <div class="tab-content" id="mainTabContent">
            <!-- Chat Tab Content -->
            <div class="tab-pane fade show active" id="chat" role="tabpanel" aria-labelledby="chat-tab">
                <div class="card mb-3">
                    <div class="card-header">Chat with ATHENA</div>
                    <div class="card-body">
                        <div id="chatBox" class="mb-3"></div>
                        <div class="input-group">
                            <input type="text" id="userMessage" class="form-control" placeholder="Type your message here...">
                            <button class="btn btn-primary" type="button" id="sendButton">
                                <i class="fas fa-paper-plane"></i> Send
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="input-group">
                            <input type="file" class="form-control" id="fileInput" accept=".pdf,.docx,.txt">
                            <button class="btn btn-primary" type="button" id="uploadButton">
                                <i class="fas fa-upload"></i>
                            </button>
                        </div>
                        <!-- Uploaded File Container -->
                        <div id="uploadedFileContainer" class="mt-2"></div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <button class="btn btn-primary w-100" id="clearChatButton">
                            <i class="fas fa-trash-alt"></i> Clear Chat
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- Editor Tab Content -->
            <div class="tab-pane fade" id="editor" role="tabpanel" aria-labelledby="editor-tab">
                <div class="card mb-3">
                    <div class="card-header">Editor</div>
                    <div class="card-body" style="position: relative;">
                        <!-- Writing Style Selection -->
                        <div class="mb-3">
                            <label for="writingStyle" class="form-label">Writing Style</label>
                            <select class="form-select" id="writingStyle">
                                <option value="formal" selected>Formal</option>
                                <option value="informal">Informal</option>
                                <option value="academic">Academic</option>
                                <option value="creative">Creative</option>
                                <option value="persuasive">Persuasive</option>
                                <option value="descriptive">Descriptive</option>
                                <!-- Add more styles as needed -->
                            </select>
                        </div>

                        <!-- Additional Instructions -->
                        <div class="mb-3">
                            <label for="additionalInstructions" class="form-label">Additional Instructions</label>
                            <textarea class="form-control" id="additionalInstructions" rows="2" placeholder="Specify any additional instructions..."></textarea>
                        </div>
                        
                        <!-- Tone Consistency Checkbox -->
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="toneConsistencyCheck">
                            <label class="form-check-label" for="toneConsistencyCheck">
                                Ensure tone consistency with the rest of the text
                            </label>
                        </div>

                        <!-- Editor Toolbar -->
                        <div class="editor-toolbar">
                            <button class="btn btn-primary btn-sm" id="undoButton" disabled>
                                <i class="fas fa-undo"></i> Undo
                            </button>
                            <button class="btn btn-primary btn-sm" id="redoButton" disabled>
                                <i class="fas fa-redo"></i> Redo
                            </button>
                        </div>
                        <!-- CKEditor Textarea -->
                        <textarea class="form-control mb-3" id="editorText" placeholder="Write or paste your text here..."></textarea>
                        <!-- Improve Button -->
                        <div id="improveButton" class="improve-button" style="display: none;">
                            <button class="btn btn-primary btn-sm">
                                <i class="fas fa-magic"></i> Improve
                            </button>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <button class="btn btn-primary" id="resetEditorButton">
                                <i class="fas fa-trash-alt"></i> Clear Editor
                            </button>
                            <button class="btn btn-primary" id="analyticsButton">
                                <i class="fas fa-chart-line"></i> View Analytics
                            </button>
                            <span id="improvementStatus"></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Template Generator Tab Content -->
            <div class="tab-pane fade" id="template" role="tabpanel" aria-labelledby="template-tab">
                <div class="card mb-3">
                    <div class="card-header">Inline Template Generator</div>
                    <div class="card-body">
                        <form id="templateForm">
                            <div class="mb-3">
                                <label for="templateType" class="form-label">Template Type</label>
                                <select class="form-select" id="templateType" required>
                                    <option value="" selected disabled>Select Template Type</option>
                                    <option value="fundraising_letter">Fundraising Letter</option>
                                    <option value="grant_proposal">Grant Proposal</option>
                                    <option value="newsletter">Newsletter</option>
                                    <option value="event_invitation">Event Invitation</option>
                                    <option value="annual_report">Annual Report</option>
                                    <!-- Add more template types as needed -->
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="templateTopic" class="form-label">Topic</label>
                                <input type="text" class="form-control" id="templateTopic" placeholder="Enter the topic" required>
                            </div>
                            <div class="mb-3">
                                <label for="templateStructure" class="form-label">Structure (Optional)</label>
                                <input type="text" class="form-control" id="templateStructure" placeholder="e.g., Introduction, Body, Conclusion">
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-file-alt"></i> Generate Template
                            </button>
                        </form>
                        <div class="mt-4" id="templateResult">
                            <h5>Generated Template:</h5>
                            <!-- Styled Generated Template Message -->
                            <div id="generatedTemplateMessage" class="assistant-message">
                                <!-- Template content will be injected here -->
                            </div>
                            <button class="btn btn-secondary mt-2" id="copyTemplateButton">
                                <i class="fas fa-copy"></i> Copy Template
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="sessionSummary" style="display: none;">
            <h5>Session Summary</h5>
            <pre id="summaryContent" class="bg-light p-3 rounded"></pre>
        </div>
        
        <footer>
            © 2024 Enhanced Analytics Application. All rights reserved.
        </footer>
    </div>
    
    <!-- Bootstrap Modal -->
    <div class="modal fade" id="customModal" tabindex="-1" aria-labelledby="customModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="customModalLabel">Modal Title</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <!-- Modal message will be injected here -->
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary" id="modalConfirmButton">OK</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Embedded JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.3.0/marked.min.js"></script>
    <!-- Include Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const sendButton = document.getElementById('sendButton');
            const userMessageInput = document.getElementById('userMessage');
            const chatBox = document.getElementById('chatBox');
            const fileInput = document.getElementById('fileInput');
            const uploadButton = document.getElementById('uploadButton');
            const uploadedFileContainer = document.getElementById('uploadedFileContainer');
            const clearChatButton = document.getElementById('clearChatButton');
            const improveButtonDiv = document.getElementById('improveButton');
            const improveButton = improveButtonDiv.querySelector('button');
            const resetEditorButton = document.getElementById('resetEditorButton');
            const improvementStatus = document.getElementById('improvementStatus');
            const sessionSummary = document.getElementById('sessionSummary');
            const summaryContent = document.getElementById('summaryContent');
            const undoButton = document.getElementById('undoButton');
            const redoButton = document.getElementById('redoButton');
            const analyticsButton = document.getElementById('analyticsButton');
            
            // Template Generator Elements
            const templateForm = document.getElementById('templateForm');
            const templateType = document.getElementById('templateType');
            const templateTopic = document.getElementById('templateTopic');
            const templateStructure = document.getElementById('templateStructure');
            const templateResult = document.getElementById('templateResult');
            const generatedTemplateMessage = document.getElementById('generatedTemplateMessage');
            const copyTemplateButton = document.getElementById('copyTemplateButton');

            // Sidebar Elements
            const chatSessionsList = document.getElementById('chatSessions');
            const newSessionButton = document.getElementById('newSessionButton');

            let currentSessionId = null;
            let chatHistory = [];

            // Initialize CKEditor
            let editor;
            ClassicEditor
                .create(document.querySelector('#editorText'))
                .then(newEditor => {
                    editor = newEditor;

                    // Update Undo/Redo button states based on editor commands
                    undoButton.addEventListener('click', () => {
                        editor.execute('undo');
                    });

                    redoButton.addEventListener('click', () => {
                        editor.execute('redo');
                    });

                    editor.commands.get('undo').on('change:isEnabled', (evt, propertyName, newValue) => {
                        undoButton.disabled = !newValue;
                    });

                    editor.commands.get('redo').on('change:isEnabled', (evt, propertyName, newValue) => {
                        redoButton.disabled = !newValue;
                    });

                    // Show or hide Improve button based on selection
                    editor.model.document.selection.on('change:range', () => {
                        const selection = editor.model.document.selection;
                        if (selection && !selection.isCollapsed) {
                            improveButtonDiv.style.display = 'block';

                            // Position the Improve button near the selection
                            // Get the view range from the selection
                            const viewRange = editor.editing.mapper.toViewRange(selection.getFirstRange());

                            // Convert the view range to a DOM range
                            const domRange = editor.editing.view.domConverter.viewRangeToDom(viewRange);

                            // Get the bounding rectangle of the DOM range
                            const rect = domRange.getBoundingClientRect();

                            // Get the bounding rectangle of the editable element within the editor
                            const editorRect = editor.ui.getEditableElement().getBoundingClientRect();

                            // Calculate the position of the improveButtonDiv
                            const leftPosition = rect.left - editorRect.left + (rect.width / 2) - (improveButtonDiv.offsetWidth / 2);

                            // Reduce the vertical gap so the button is closer to the highlighted text
                            const topPosition = rect.top - editorRect.top - improveButtonDiv.offsetHeight + 280;  // Adjusted the vertical gap

                            // Apply the calculated position to the improveButtonDiv
                            improveButtonDiv.style.left = `${leftPosition}px`;
                            improveButtonDiv.style.top = `${topPosition}px`;

                        } else {
                            improveButtonDiv.style.display = 'none';
                        }
                    });
                })
                .catch(error => {
                    console.error(error);
                });

            // Function to append messages to the chatBox with Markdown support
            function appendMessage(role, content) {
                const messageDiv = document.createElement('div');
                messageDiv.classList.add(role === 'user' ? 'user-message' : 'assistant-message');

                const messageContent = document.createElement('div');
                messageContent.classList.add('message-content');
                
                if (role === 'assistant') {
                    // Use marked.js to parse Markdown
                    messageContent.innerHTML = marked.parse(content);
                } else {
                    // For user messages, escape HTML to prevent XSS
                    messageContent.textContent = content;
                }

                messageDiv.appendChild(messageContent);
                chatBox.appendChild(messageDiv);
                chatBox.scrollTop = chatBox.scrollHeight;
            }

            // Function to append a spinner message to the chatBox
            function appendSpinner() {
                const spinnerDiv = document.createElement('div');
                spinnerDiv.classList.add('assistant-message');
                spinnerDiv.id = 'spinnerMessage';

                const spinnerContent = document.createElement('div');
                spinnerContent.classList.add('d-flex', 'align-items-center');

                const spinner = document.createElement('div');
                spinner.classList.add('spinner-border', 'spinner-sm', 'me-2');
                spinner.setAttribute('role', 'status');
                spinner.setAttribute('aria-hidden', 'true');

                const spinnerText = document.createElement('span');
                spinnerText.textContent = 'ATHENA is typing...';

                spinnerContent.appendChild(spinner);
                spinnerContent.appendChild(spinnerText);
                spinnerDiv.appendChild(spinnerContent);
                chatBox.appendChild(spinnerDiv);
                chatBox.scrollTop = chatBox.scrollHeight;

                return spinnerDiv;
            }

            // Function to remove the spinner message
            function removeSpinner() {
                const spinnerDiv = document.getElementById('spinnerMessage');
                if (spinnerDiv) {
                    spinnerDiv.remove();
                }
            }

            // Function to show the modal with a custom message and title
            function showModal(title, message) {
                const modalTitle = document.getElementById('customModalLabel');
                const modalBody = document.querySelector('#customModal .modal-body');
                const modalFooter = document.querySelector('#customModal .modal-footer');
                const confirmButton = document.getElementById('modalConfirmButton');
                const cancelButton = modalFooter.querySelector('.btn-secondary');
                const okButton = modalFooter.querySelector('.btn-primary');

                modalTitle.textContent = title;
                modalBody.innerHTML = message;

                // Determine if it's a simple alert or a confirmation
                if (typeof message === 'string' && !message.includes('Are you sure')) {
                    // Simple Alert
                    cancelButton.style.display = 'none';
                    confirmButton.style.display = 'none';
                    
                    okButton.style.display = 'block';
                    okButton.textContent = 'OK';

                    // Remove any existing event listeners
                    okButton.replaceWith(okButton.cloneNode(true));
                    const newOkButton = modalFooter.querySelector('.btn-primary');

                    newOkButton.addEventListener('click', () => {
                        const customModal = bootstrap.Modal.getInstance(document.getElementById('customModal'));
                        customModal.hide();
                    });
                } else {
                    // Confirmation Dialog
                    cancelButton.style.display = 'block';
                    confirmButton.style.display = 'block';

                    // Reset button texts
                    okButton.textContent = 'OK';

                    // Remove existing event listeners
                    confirmButton.replaceWith(confirmButton.cloneNode(true));
                    const newConfirmButton = modalFooter.querySelector('.btn-primary');

                    // Event listener will be added in showConfirmModal
                }

                // Initialize and show the Bootstrap modal
                const customModal = new bootstrap.Modal(document.getElementById('customModal'));
                customModal.show();
            }

            // Function to show confirmation modal with callback
            function showConfirmModal(title, message, callback) {
                const modalTitle = document.getElementById('customModalLabel');
                const modalBody = document.querySelector('#customModal .modal-body');
                const modalFooter = document.querySelector('#customModal .modal-footer');
                const confirmButton = document.getElementById('modalConfirmButton');
                const cancelButton = modalFooter.querySelector('.btn-secondary');
                const okButton = modalFooter.querySelector('.btn-primary');

                modalTitle.textContent = title;
                modalBody.innerHTML = message;

                // Show both Cancel and Confirm buttons
                cancelButton.style.display = 'block';
                confirmButton.style.display = 'block';

                // Reset button texts
                okButton.textContent = 'OK';

                // Remove any existing event listeners
                okButton.replaceWith(okButton.cloneNode(true));
                const newOkButton = modalFooter.querySelector('.btn-primary');

                newOkButton.addEventListener('click', () => {
                    callback();
                    const customModal = bootstrap.Modal.getInstance(document.getElementById('customModal'));
                    customModal.hide();
                });

                // Initialize and show the Bootstrap modal
                const customModal = new bootstrap.Modal(document.getElementById('customModal'));
                customModal.show();
            }

            // Handle Upload Button Click
            uploadButton.addEventListener('click', () => {
                const files = fileInput.files;
                if (files.length > 0) {
                    const file = files[0];
                    console.log("Selected File:", file.name);
                    // Check if the file is already displayed
                    if (!uploadedFileContainer.querySelector('.uploaded-file')) {
                        // Create a new div to display the uploaded file
                        const fileDiv = document.createElement('div');
                        fileDiv.classList.add('uploaded-file', 'alert', 'alert-secondary', 'd-flex', 'justify-content-between', 'align-items-center');
                        fileDiv.setAttribute('role', 'alert');
                        
                        // Add file name
                        const fileNameSpan = document.createElement('span');
                        fileNameSpan.textContent = file.name;
                        fileDiv.appendChild(fileNameSpan);
                        
                        // Add the remove (X) button
                        const removeButton = document.createElement('button');
                        removeButton.type = 'button';
                        removeButton.classList.add('btn-close');
                        removeButton.setAttribute('aria-label', 'Remove');
                        fileDiv.appendChild(removeButton);
                        
                        uploadedFileContainer.appendChild(fileDiv);
                        
                        // Add event listener to the remove button
                        removeButton.addEventListener('click', () => {
                            showConfirmModal('Remove File', 'Are you sure you want to remove the uploaded file?', () => {
                                uploadedFileContainer.innerHTML = '';
                                fileInput.value = ''; // Clear the file input
                                console.log("File removed");
                                showModal('File Removed', 'The uploaded file has been removed.');
                            });
                        });
                    } else {
                        showModal('Upload Limit', 'A file is already uploaded. Please remove it before uploading another.');
                    }
                } else {
                    showModal('No File Selected', 'Please select a file to upload.');
                }
            });

            // Function to send chat message
            async function sendMessage() {
                const userMessage = userMessageInput.value.trim();
                let fileData = null;

                // Check if a file has been uploaded
                const uploadedFile = uploadedFileContainer.querySelector('.uploaded-file span');
                if (uploadedFile) {
                    const fileName = uploadedFile.textContent;
                    const file = fileInput.files[0];
                    if (file) {
                        console.log("Selected File for Upload:", file.name);
                        const reader = new FileReader();
                        reader.readAsDataURL(file);
                        await new Promise((resolve) => {
                            reader.onload = () => {
                                const base64Content = reader.result.split(',')[1];
                                fileData = {
                                    filename: file.name,
                                    content: base64Content,
                                    mimetype: file.type
                                };
                                console.log("File Data Prepared:", fileData);
                                resolve();
                            };
                            reader.onerror = () => {
                                console.error('Error reading file');
                                resolve();
                            };
                        });
                    }
                }

                if (!userMessage && !fileData) {
                    showModal('Input Required', 'Please enter a message or upload a file.');
                    return;
                }

                // Append user's message to chat if present
                if (userMessage) {
                    appendMessage('user', userMessage);
                    chatHistory.push({ role: 'user', content: userMessage });
                    userMessageInput.value = '';
                }

                // Append spinner to indicate loading
                const spinnerDiv = appendSpinner();

                // Send POST request to /chat
                try {
                    const response = await fetch('/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            user_message: userMessage || '',
                            consent: true,
                            file: fileData,
                            chat_history: chatHistory
                        })
                    });

                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }

                    const data = await response.json();
                    chatHistory = data.chat_history;

                    // Remove spinner
                    removeSpinner();

                    // Append assistant's response
                    const assistantMessage = chatHistory[chatHistory.length - 1].content;
                    appendMessage('assistant', assistantMessage);

                    // Clear the uploaded file after sending
                    uploadedFileContainer.innerHTML = '';
                    fileInput.value = '';
                    console.log("File Upload Cleared");

                    // Save the updated chat history to current session
                    saveCurrentSession();

                } catch (error) {
                    console.error('Error:', error);
                    removeSpinner();
                    showModal('Error', "I'm sorry, something went wrong while processing your request.");
                }
            }

            // Event listener for Send button
            sendButton.addEventListener('click', sendMessage);

            // Event listener for Enter key in user message input
            userMessageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            // Function to clear the chat
            async function clearChat() {
                try {
                    const response = await fetch('/reset_chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({})
                    });

                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }

                    const data = await response.json();
                    chatHistory = data.chat_history;
                    chatBox.innerHTML = '';

                    // Append the reset message
                    const resetMessage = chatHistory[0].content;
                    appendMessage('assistant', resetMessage);
                    console.log("Chat cleared successfully.");

                    // Save the cleared chat history to current session
                    saveCurrentSession();

                } catch (error) {
                    console.error('Error:', error);
                    showModal('Error', 'Failed to clear chat.');
                }
            }

            // Event listener for Clear Chat button
            clearChatButton.addEventListener('click', () => {
                showConfirmModal('Clear Chat', 'Are you sure you want to clear the chat?', clearChat);
            });

            function improveSelectedText() {
                const selection = editor.model.document.selection;

                if (selection && !selection.isCollapsed) {
                    const range = selection.getFirstRange();
                    let selectedText = '';

                    for (const item of range.getItems()) {
                        if (item.is('textProxy')) {
                            selectedText += item.data;
                        }
                    }

                    // Get the writing style and additional instructions from the UI
                    const writingStyle = document.getElementById('writingStyle').value;
                    const additionalInstructions = document.getElementById('additionalInstructions').value.trim();

                    // Get the tone consistency checkbox state
                    const toneConsistency = document.getElementById('toneConsistencyCheck').checked;

                    // Show loading status
                    improvementStatus.innerHTML = '<div class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></div> Improving...';
                    improveButton.disabled = true;
                    improveButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Improving...';

                    // Send the selected text and additional parameters to the server
                    fetch('/improve_text', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            selected_text: selectedText,
                            writing_style: writingStyle,
                            additional_instructions: additionalInstructions,
                            tone_consistency: toneConsistency
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.improved_text && data.status && data.status.toLowerCase().includes('text improved')) {
                            const improvedText = data.improved_text;

                            // Replace the selected text with the improved text
                            editor.model.change(writer => {
                                writer.remove(range);
                                writer.insertText(improvedText, range.start);

                                // Move the selection to the end of the inserted text
                                const newPosition = writer.createPositionAt(range.start.parent, range.start.offset + improvedText.length);
                                writer.setSelection(newPosition);
                            });

                            // Force editor to update
                            editor.editing.view.focus();

                            improvementStatus.textContent = data.status;
                        } else {
                            improvementStatus.textContent = data.status || 'Improvement failed.';
                        }

                        // Reset the Improve button
                        improveButton.disabled = false;
                        improveButton.innerHTML = '<i class="fas fa-magic"></i> Improve';
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        improvementStatus.textContent = 'An error occurred while improving the text.';
                        improveButton.disabled = false;
                        improveButton.innerHTML = '<i class="fas fa-magic"></i> Improve';
                    });
                } else {
                    showModal('Selection Required', 'Please select text to improve.');
                }
            }

            // Event listener for the Improve button
            improveButton.addEventListener('click', improveSelectedText);

            // Function to reset editor
            function resetEditor() {
                editor.setData('');
                improvementStatus.textContent = 'Editor cleared successfully.';
                showModal('Editor Cleared', 'The editor has been cleared.');
                console.log("Editor cleared successfully.");
            }

            // Event listener for Reset Editor button
            resetEditorButton.addEventListener('click', resetEditor);

            // Function to send text from the editor to the analytics dashboard
            function sendTextForAnalytics() {
                const htmlText = editor.getData();
                if (htmlText.trim() === '') {
                    showModal('No Content', 'Please enter some text in the editor.');
                    return;
                }
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '/analytics';
                const hiddenField = document.createElement('input');
                hiddenField.type = 'hidden';
                hiddenField.name = 'text';
                hiddenField.value = htmlText;
                form.appendChild(hiddenField);
                document.body.appendChild(form);
                form.submit();
            }

            // Add an event listener to the analytics button
            analyticsButton.addEventListener('click', sendTextForAnalytics);

            // Function to show session summary (optional)
            async function showSummary() {
                try {
                    const response = await fetch('/show_summary', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            chat_history: chatHistory
                        })
                    });

                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }

                    const data = await response.json();
                    summaryContent.textContent = data.summary;
                    sessionSummary.style.display = 'block';
                    console.log("Session summary displayed.");
                } catch (error) {
                    console.error('Error:', error);
                    showModal('Error', 'Failed to retrieve session summary.');
                }
            }

            // Handle Template Generator Form Submission
            templateForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const type = templateType.value.trim();
                const topic = templateTopic.value.trim();
                const structure = templateStructure.value.trim();

                if (!type || !topic) {
                    showModal('Input Required', 'Please select a template type and enter a topic.');
                    return;
                }

                // Show loading status
                templateResult.style.display = 'block';
                generatedTemplateMessage.innerHTML = '<div class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></div> Generating template...';

                try {
                    const response = await fetch('/generate_template', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            template_type: type,
                            topic: topic,
                            structure: structure
                        })
                    });

                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }

                    const data = await response.json();

                    if (data.status === "Template generated successfully.") {
                        // Insert the template as plain text to preserve formatting
                        generatedTemplateMessage.textContent = data.template;
                    } else {
                        generatedTemplateMessage.textContent = 'Failed to generate template: ' + data.status;
                    }
                } catch (error) {
                    console.error('Error:', error);
                    generatedTemplateMessage.textContent = 'An error occurred while generating the template.';
                }
            });

            // Handle Copy Template Button Click
            copyTemplateButton.addEventListener('click', () => {
                const text = generatedTemplateMessage.textContent;
                if (!text) {
                    showModal('No Template', 'No template to copy.');
                    return;
                }

                // Create a temporary textarea to copy the text
                const textarea = document.createElement('textarea');
                textarea.value = text;
                document.body.appendChild(textarea);
                textarea.select();
                textarea.setSelectionRange(0, 99999); // For mobile devices

                try {
                    document.execCommand('copy');
                    showModal('Copied', 'Template copied to clipboard!');
                } catch (err) {
                    console.error('Failed to copy text: ', err);
                    showModal('Copy Failed', 'Failed to copy template.');
                }

                // Remove the temporary textarea
                document.body.removeChild(textarea);
            });

            /* Sidebar and Chat Session Management */

            // Function to generate a unique session ID
            function generateSessionId() {
                return 'session-' + Date.now();
            }

            // Function to load chat sessions from localStorage
            function loadChatSessions() {
                const sessions = JSON.parse(localStorage.getItem('chat_sessions')) || [];
                return sessions;
            }

            // Function to save chat sessions to localStorage
            function saveChatSessions(sessions) {
                localStorage.setItem('chat_sessions', JSON.stringify(sessions));
            }

            // Function to render the sidebar chat sessions
            function renderChatSessions() {
                const sessions = loadChatSessions();
                chatSessionsList.innerHTML = '';

                sessions.forEach(session => {
                    const li = document.createElement('li');
                    li.dataset.sessionId = session.id;
                    li.classList.toggle('active', session.id === currentSessionId);
                    li.innerHTML = `
                        <span>${session.name}</span>
                        <i class="fas fa-trash delete-session" title="Delete Session"></i>
                    `;
                    chatSessionsList.appendChild(li);
                });
            }

            // Function to create a new chat session
            function createNewSession() {
                showModal('New Session', 'Enter a name for the new chat session:', (sessionName) => {
                    if (sessionName) {
                        const sessions = loadChatSessions();
                        const newSession = {
                            id: generateSessionId(),
                            name: sessionName,
                            chat_history: []
                        };
                        sessions.push(newSession);
                        saveChatSessions(sessions);
                        setCurrentSession(newSession.id);
                        renderChatSessions();
                        showModal('Session Created', `Chat session "${sessionName}" has been created.`);
                    }
                }, true); // 'true' indicates that a callback is expected for input
            }

            // Modified showModal to handle input if required
            function showModal(title, message, callback = null, isInput = false) {
                const modalTitle = document.getElementById('customModalLabel');
                const modalBody = document.querySelector('#customModal .modal-body');
                const modalFooter = document.querySelector('#customModal .modal-footer');
                const confirmButton = document.getElementById('modalConfirmButton');
                const cancelButton = modalFooter.querySelector('.btn-secondary');
                const okButton = modalFooter.querySelector('.btn-primary');

                modalTitle.textContent = title;
                modalBody.innerHTML = message;

                if (isInput) {
                    // Create an input field inside the modal
                    const inputField = document.createElement('input');
                    inputField.type = 'text';
                    inputField.classList.add('form-control', 'mt-3');
                    inputField.id = 'modalInput';
                    modalBody.appendChild(inputField);
                }

                if (callback && isInput) {
                    // Show both Cancel and Confirm buttons
                    cancelButton.style.display = 'block';
                    confirmButton.style.display = 'block';
                    okButton.style.display = 'none';

                    // Remove existing event listeners
                    confirmButton.replaceWith(confirmButton.cloneNode(true));
                    const newConfirmButton = modalFooter.querySelector('.btn-primary');

                    newConfirmButton.addEventListener('click', () => {
                        const userInput = document.getElementById('modalInput').value.trim();
                        callback(userInput);
                        const customModal = bootstrap.Modal.getInstance(document.getElementById('customModal'));
                        customModal.hide();
                    });
                } else if (callback && !isInput) {
                    // Confirmation without input
                    cancelButton.style.display = 'block';
                    confirmButton.style.display = 'block';
                    okButton.style.display = 'none';

                    // Remove existing event listeners
                    confirmButton.replaceWith(confirmButton.cloneNode(true));
                    const newConfirmButton = modalFooter.querySelector('.btn-primary');

                    newConfirmButton.addEventListener('click', () => {
                        callback();
                        const customModal = bootstrap.Modal.getInstance(document.getElementById('customModal'));
                        customModal.hide();
                    });
                } else {
                    // Simple alert
                    cancelButton.style.display = 'none';
                    confirmButton.style.display = 'none';
                    
                    okButton.style.display = 'block';
                    okButton.textContent = 'OK';

                    // Remove any existing event listeners
                    okButton.replaceWith(okButton.cloneNode(true));
                    const newOkButton = modalFooter.querySelector('.btn-primary');

                    newOkButton.addEventListener('click', () => {
                        const customModal = bootstrap.Modal.getInstance(document.getElementById('customModal'));
                        customModal.hide();
                    });
                }

                // Initialize and show the Bootstrap modal
                const customModal = new bootstrap.Modal(document.getElementById('customModal'));
                customModal.show();
            }

            // Function to set the current session
            function setCurrentSession(sessionId) {
                currentSessionId = sessionId;
                const sessions = loadChatSessions();
                const session = sessions.find(s => s.id === sessionId);
                if (session) {
                    chatHistory = session.chat_history;
                    chatBox.innerHTML = '';
                    chatHistory.forEach(msg => {
                        appendMessage(msg.role, msg.content);
                    });
                }
                renderChatSessions();
            }

            // Function to delete a chat session
            function deleteSession(sessionId) {
                let sessions = loadChatSessions();
                const session = sessions.find(s => s.id === sessionId);
                if (session) {
                    const sessionName = session.name;
                    sessions = sessions.filter(s => s.id !== sessionId);
                    saveChatSessions(sessions);
                    if (currentSessionId === sessionId) {
                        if (sessions.length > 0) {
                            setCurrentSession(sessions[0].id);
                        } else {
                            // If no sessions left, create a default one
                            const defaultSession = {
                                id: generateSessionId(),
                                name: 'Default Chat',
                                chat_history: []
                            };
                            sessions.push(defaultSession);
                            saveChatSessions(sessions);
                            setCurrentSession(defaultSession.id);
                        }
                    }
                    renderChatSessions();
                    showModal('Session Deleted', `Chat session "${sessionName}" has been deleted.`);
                }
            }

            // Function to save the current chat history to the current session
            function saveCurrentSession() {
                const sessions = loadChatSessions();
                const sessionIndex = sessions.findIndex(s => s.id === currentSessionId);
                if (sessionIndex !== -1) {
                    sessions[sessionIndex].chat_history = chatHistory;
                    saveChatSessions(sessions);
                }
            }

            // Event listener for New Session button
            newSessionButton.addEventListener('click', () => {
                showModal('New Session', 'Enter a name for the new chat session:', (sessionName) => {
                    if (sessionName) {
                        const sessions = loadChatSessions();
                        const newSession = {
                            id: generateSessionId(),
                            name: sessionName,
                            chat_history: []
                        };
                        sessions.push(newSession);
                        saveChatSessions(sessions);
                        setCurrentSession(newSession.id);
                        renderChatSessions();
                        showModal('Session Created', `Chat session "${sessionName}" has been created.`);
                    }
                }, true); // 'true' indicates that a callback is expected for input
            });

            // Event listener for clicking on a chat session
            chatSessionsList.addEventListener('click', (e) => {
                const li = e.target.closest('li');
                if (li) {
                    const sessionId = li.dataset.sessionId;
                    if (e.target.classList.contains('delete-session')) {
                        // Delete the session
                        showConfirmModal('Delete Session', 'Are you sure you want to delete this session?', () => {
                            deleteSession(sessionId);
                        });
                    } else {
                        // Switch to the selected session
                        setCurrentSession(sessionId);
                    }
                }
            });

            // Initialize the sidebar with existing sessions or create a default one
            function initializeSidebar() {
                let sessions = loadChatSessions();
                if (sessions.length === 0) {
                    const defaultSession = {
                        id: generateSessionId(),
                        name: 'Default Chat',
                        chat_history: []
                    };
                    sessions.push(defaultSession);
                    saveChatSessions(sessions);
                }
                currentSessionId = sessions[0].id;
                setCurrentSession(currentSessionId);
                renderChatSessions();
            }

            // Initialize on page load
            initializeSidebar();

            // Save the current session before unloading the page
            window.addEventListener('beforeunload', () => {
                saveCurrentSession();
            });
        });
    </script>
</body>
</html>
"