<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Learning - Premium</title>
    <link rel="icon" type="image/x-icon" href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRXH01KD_9TMda5AESIluex5Jg2BDv71A07hA&s">
    <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">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --accent-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            --dark-gradient: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            --light-bg: #f8fafc;
            --card-bg: #ffffff;
            --text-primary: #2d3748;
            --text-secondary: #718096;
            --border-color: #e2e8f0;
            --shadow-sm: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--light-bg);
            color: var(--text-primary);
            line-height: 1.6;
            overflow-x: hidden;
        }

        .premium-header {
            background: var(--primary-gradient);
            backdrop-filter: blur(20px);
            border: none;
            box-shadow: var(--shadow-lg);
            z-index: 1050;
            padding: 1rem 0;
        }

        .head-part {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .premium-header h1 {
            color: white;
            font-weight: 700;
            font-size: clamp(1.5rem, 4vw, 2.5rem);
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin: 0;
        }

        .premium-header h5 {
            color: rgba(255, 255, 255, 0.9);
            font-weight: 500;
            font-size: clamp(0.9rem, 2.5vw, 1.1rem);
            margin: 0;
        }

        .main-container {
            margin-top: 120px;
            padding: 0 1rem;
            max-width: 1200px;
            margin-left: auto;
            margin-right: auto;
        }

        .output-part {
            margin-bottom: 2rem;
        }

        .output-part .card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            box-shadow: var(--shadow-md);
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .output-part .card:hover {
            box-shadow: var(--shadow-lg);
            transform: translateY(-2px);
        }

        .card-body {
            padding: 2rem;
            background: linear-gradient(135deg, #fffef7 0%, #fff9e6 100%);
        }

        #chat-container {
            height: clamp(200px, 70vh, 500px);
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: #cbd5e0 transparent;
            display : none;
        }

        #chat-container::-webkit-scrollbar {
            width: 6px;
        }

        #chat-container::-webkit-scrollbar-track {
            background: transparent;
        }

        #chat-container::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 3px;
        }

        #chat-container::-webkit-scrollbar-thumb:hover {
            background: #a0aec0;
        }

        .input-part {
            background: var(--card-bg);
            border-radius: 24px;
            padding: 1.5rem;
            box-shadow: var(--shadow-xl);
            border: 1px solid var(--border-color);
            position: bottom;
            bottom: 1rem;
            z-index: 100;
        }

        .language-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .language-section {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            flex-wrap: wrap;
        }

        .form-label {
            font-weight: 600;
            color: var(--text-primary);
            margin: 0;
            font-size: 0.9rem;
        }

        .form-select {
            border: 2px solid var(--border-color);
            border-radius: 12px;
            padding: 0.5rem 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            min-width: 140px;
        }

        .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
            align-items: center;
            flex-wrap: wrap;
        }

        .btn-icon {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid var(--border-color);
            background: var(--card-bg);
            color: var(--text-secondary);
            transition: all 0.3s ease;
            text-decoration: none;
        }

        .btn-icon:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .btn-icon.btn-light:hover {
            background: var(--accent-gradient);
            color: white;
            border-color: transparent;
        }

        .btn-icon.btn-danger:hover {
            background: var(--secondary-gradient);
            color: white;
            border-color: transparent;
        }

        .message-input-container {
            position: relative;
            margin-bottom: 1rem;
        }

        #message-input {
            border: 2px solid var(--border-color);
            border-radius: 16px;
            padding: 1rem 3.5rem 1rem 1rem;
            font-size: 1rem;
            transition: all 0.3s ease;
            resize: vertical;
            min-height: 60px;
        }

        #message-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .file-upload-icon {
            position: absolute;
            right: 12px;
            bottom: 12px;
            cursor: pointer;
            color: var(--text-secondary);
            transition: all 0.3s ease;
            padding: 8px;
            border-radius: 8px;
        }

        .file-upload-icon:hover {
            color: #667eea;
            background: rgba(102, 126, 234, 0.1);
        }

        .controls-container {
            display: flex;
            gap: 0.75rem;
            align-items: center;
            flex-wrap: wrap;
            justify-content: space-between;
        }

        .control-buttons {
            display: flex;
            gap: 0.75rem;
            flex-wrap: wrap;
        }

        .btn {
            border-radius: 12px;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
            transition: all 0.3s ease;
            border: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .btn-primary {
            background: var(--primary-gradient);
            color: white;
        }

        .btn-secondary {
            background: var(--dark-gradient);
            color: white;
        }

        .btn-danger {
            background: var(--secondary-gradient);
            color: white;
        }

        .btn-info {
            background: var(--accent-gradient);
            color: white;
        }

        .loading-animation {
            width: 24px;
            height: 24px;
            border: 3px solid var(--border-color);
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .image-popup {
            position: absolute;
            top: -120px;
            left: 50%;
            transform: translateX(-50%);
            background: var(--card-bg);
            border: 2px solid var(--border-color);
            border-radius: 16px;
            padding: 1rem;
            z-index: 1000;
            max-width: 300px;
        }

        .image-popup img {
            width: 100%;
            height: auto;
            border-radius: 8px;
            margin-bottom: 0.5rem;
        }

        .popup-buttons {
            display: flex;
            gap: 0.5rem;
            justify-content: center;
        }

        .modal-content {
            border-radius: 20px;
            border: none;
            box-shadow: var(--shadow-xl);
        }

        .modal-header {
            background: var(--primary-gradient);
            color: white;
            border-radius: 20px 20px 0 0;
            padding: 1.5rem;
        }

        .modal-title {
            font-weight: 700;
        }

        .btn-close {
            filter: invert(1);
        }

        .modal-body {
            padding: 2rem;
        }

        .form-check-input:checked {
            background-color: #667eea;
            border-color: #667eea;
        }

        .form-check-label {
            font-weight: 500;
            color: var(--text-primary);
        }

        #image-preview {
            margin-bottom: 1rem;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .main-container {
                margin-top: 140px;
                padding: 0 0.5rem;
            }

            .head-part {
                flex-direction: column;
                text-align: center;
                gap: 0.5rem;
            }

            .language-controls {
                flex-direction: column;
                align-items: stretch;
                gap: 1rem;
            }

            .language-section {
                justify-content: center;
            }

            .action-buttons {
                justify-content: center;
            }

            .controls-container {
                flex-direction: column;
                gap: 1rem;
            }

            .control-buttons {
                justify-content: center;
                width: 100%;
            }

            .btn {
                flex: 1;
                min-width: 120px;
                justify-content: center;
            }

            .input-part {
                padding: 1rem;
                border-radius: 20px;
            }

            #message-input {
                padding: 0.75rem 3rem 0.75rem 0.75rem;
            }

            .card-body {
                padding: 1rem;
            }
        }

        @media (max-width: 480px) {
            .premium-header h1 {
                font-size: 1.5rem;
            }

            .premium-header h5 {
                font-size: 0.9rem;
            }

            .btn {
                padding: 0.6rem 1rem;
                font-size: 0.9rem;
            }

            .btn-icon {
                width: 40px;
                height: 40px;
            }

            .control-buttons {
                flex-direction: column;
                width: 100%;
            }

            .btn {
                width: 100%;
            }
        }

        /* Animation for smooth transitions */
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Enhanced focus states for accessibility */
        .btn:focus,
        .form-select:focus,
        .form-control:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }

        /* Improved scrollbar for webkit browsers */
        * {
            scrollbar-width: thin;
            scrollbar-color: #cbd5e0 transparent;
        }

        *::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        *::-webkit-scrollbar-track {
            background: transparent;
        }

        *::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 4px;
        }

        *::-webkit-scrollbar-thumb:hover {
            background: #a0aec0;
        }
    </style>
</head>
<body class="container-fluid py-4">
    <header class="fixed-top premium-header">
        <div class="container head-part">
            <h1 class="mb-0">Interactive Learning</h1>
            {% if user %}
            <h5>Welcome: {{user.name}}</h5>
            {% endif %}
        </div>
    </header>

    <div class="main-container">
        <div class="output-part">
            <div class="card">
                <div class="card-body" id="chat-container"></div>
            </div>
        </div>

        <div id="image-preview" class="mt-2"></div>

        <div class="input-part fade-in" id="draggable-input">
            <div class="language-controls">
                <div class="language-section">
                    <label for="language-select" class="form-label">Select Language:</label>
                    <select id="language-select" class="form-select">
                        <option value="english" selected>English</option>
                        <option value="hindi">Hindi</option>
                        <option value="telugu">Telugu</option>
                        <option value="bengali">Bengali</option>
                        <option value="tamil">Tamil</option>
                        <option value="marathi">Marathi</option>
                        <option value="gujarati">Gujarati</option>
                        <option value="kannada">Kannada</option>
                        <option value="malayalam">Malayalam</option>
                        <option value="odia">Odia</option>
                        <option value="punjabi">Punjabi</option>
                        <option value="assamese">Assamese</option>
                        <option value="urdu">Urdu</option>
                        <option value="sanskrit">Sanskrit</option>
                    </select>
                </div>
                
                <div class="action-buttons">
                    <button id="reset-button" class="btn-icon btn-light" title="Reset">
                        <i class="fas fa-redo"></i>
                    </button>
                    <button id="settings-button" class="btn-icon btn-light" title="Settings" data-bs-toggle="modal" data-bs-target="#settingsModal">
                        <i class="fas fa-cog"></i>
                    </button>
                    <a class="btn-icon btn-danger logout-btn" onclick="logOut()" title="Logout">
                        <i class="fas fa-sign-out-alt"></i>
                    </a>
                </div>
            </div>

            <div class="message-input-container">
                <textarea id="message-input" rows="2" class="form-control" placeholder="Type your message..." onkeydown="handleKeyDown(event)"></textarea>
                <label for="file-upload" class="file-upload-icon" title="Supported Files(pdf, png, jpg and jpeg), Maximum File Size: 10MB">
                    <i class="fas fa-paperclip" style="font-size: 20px;"></i>
                </label>
                <input type="file" id="file-upload" style="display: none;" accept=".pdf,image/*">
            </div>

            <div class="controls-container">
                <div class="control-buttons">
                    <button class="btn btn-secondary" id="pause-resume-button" onclick="toggleSpeech()" style="display: none;">
                        <i class="fas fa-pause"></i> Pause
                    </button>
                    <button class="btn btn-danger" id="stop-button" onclick="stopSpeech()" style="display: none;">
                        <i class="fas fa-stop"></i> Stop
                    </button>
                    <button class="btn btn-info" id="start-speech-button" onclick="handleSpeechButtonClick()">
                        <i class="fas fa-microphone"></i> Start Speech
                    </button>
                    <button class="btn btn-primary" onclick="sendMessage()">
                        <i class="fas fa-paper-plane"></i> Send
                    </button>
                </div>
                
                <div id="loading-indicator" style="display: none;">
                    <div class="loading-animation"></div>
                </div>
            </div>

            <div id="pasted-image-popup" style="display: none;" class="image-popup shadow-sm">
                <img id="preview-img" src="" alt="Pasted Preview" />
                <div class="popup-buttons mt-2">
                    <button class="btn btn-sm btn-primary me-2" onclick="sendPastedImage()">Send</button>
                    <button class="btn btn-sm btn-outline-secondary" onclick="removePastedImage()">Remove</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Modal -->
    <div class="modal fade" id="settingsModal" tabindex="-1" aria-labelledby="settingsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="settingsModalLabel">
                        <i class="fas fa-cog me-2"></i>Settings
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-4">
                        <label class="form-label">
                            <i class="fas fa-layer-group me-2"></i>Explanation Level:
                        </label>
                        <div class="mt-2">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="classMode" id="classModeBrief" value="brief">
                                <label class="form-check-label" for="classModeBrief">Brief</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="classMode" id="classModeStandard" value="standard" checked>
                                <label class="form-check-label" for="classModeStandard">Standard</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="classMode" id="classModeDetailed" value="detailed">
                                <label class="form-check-label" for="classModeDetailed">Detailed</label>
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">
                            <i class="fas fa-volume-up me-2"></i>Voice Configuration:
                        </label>
                        <div class="mt-2">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="voiceConfig" id="voiceConfigMale" value="male" checked>
                                <label class="form-check-label" for="voiceConfigMale">Male Voice</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="voiceConfig" id="voiceConfigFemale" value="female">
                                <label class="form-check-label" for="voiceConfigFemale">Female Voice</label>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label" for="aiModelSelect">
                            <i class="fas fa-robot me-2"></i>AI Model:
                        </label>
                        <select class="form-select mt-2" id="aiModelSelect">
                            <option value="gemini" selected>Gemini</option>
                            <option value="deepseek">DeepSeek</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Close
                    </button>
                    <button type="button" class="btn btn-primary" onclick="saveSettings()">
                        <i class="fas fa-save me-2"></i>Save changes
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const chatContainer = document.getElementById('chat-container');
        const audioPlayer = new Audio();
        const loadingIndicator = document.getElementById('loading-indicator');
        const pauseResumeButton = document.getElementById('pause-resume-button');
        const stopButton = document.getElementById('stop-button');
        const startSpeechButton = document.getElementById('start-speech-button');

        document.getElementById('reset-button').addEventListener('click', function () {
            location.reload();
        });

        function saveSettings() {
            const classMode = document.querySelector('input[name="classMode"]:checked').value;
            const voiceConfig = document.querySelector('input[name="voiceConfig"]:checked').value;
            const aiModel = document.getElementById('aiModelSelect').value;

            // Store settings (e.g., in localStorage)
            localStorage.setItem('classMode', classMode);
            localStorage.setItem('voiceConfig', voiceConfig);
            localStorage.setItem('aiModel', aiModel);

            // You can also update a global JS object if needed
            // appSettings.classMode = classMode;
            // appSettings.voiceConfig = voiceConfig;
            // appSettings.aiModel = aiModel;

            console.log("Settings saved:", { classMode, voiceConfig, aiModel });

            // Close the modal
            const settingsModal = bootstrap.Modal.getInstance(document.getElementById('settingsModal'));
            settingsModal.hide();

            // Here you would typically re-initialize or adjust your application's behavior
            // based on the new settings.
        }

        // Function to load settings when the page loads (optional, but good for persistence)
        document.addEventListener('DOMContentLoaded', (event) => {
            // --- Set default values if not found in localStorage ---
            const defaultClassMode = 'standard'; // Matches your HTML default 'standard'
            const defaultVoiceConfig = 'male';   // Matches your HTML default 'male'
            const defaultAiModel = 'gemini';     // Matches your HTML default 'gemini'

            let savedClassMode = localStorage.getItem('classMode');
            if (savedClassMode) {
                document.querySelector(`input[name="classMode"][value="${savedClassMode}"]`).checked = true;
            } else {
                // Set default in localStorage and check the corresponding radio button
                localStorage.setItem('classMode', defaultClassMode);
                document.querySelector(`input[name="classMode"][value="${defaultClassMode}"]`).checked = true;
            }

            let savedVoiceConfig = localStorage.getItem('voiceConfig');
            if (savedVoiceConfig) {
                document.querySelector(`input[name="voiceConfig"][value="${savedVoiceConfig}"]`).checked = true;
            } else {
                // Set default in localStorage and check the corresponding radio button
                localStorage.setItem('voiceConfig', defaultVoiceConfig);
                document.querySelector(`input[name="voiceConfig"][value="${defaultVoiceConfig}"]`).checked = true;
            }

            let savedAiModel = localStorage.getItem('aiModel');
            if (savedAiModel) {
                document.getElementById('aiModelSelect').value = savedAiModel;
            } else {
                // Set default in localStorage and set the corresponding select option
                localStorage.setItem('aiModel', defaultAiModel);
                document.getElementById('aiModelSelect').value = defaultAiModel;
            }

            // You could also initialize a global settings object here if you prefer
            // window.appSettings = {
            //     classMode: localStorage.getItem('classMode'),
            //     voiceConfig: localStorage.getItem('voiceConfig'),
            //     aiModel: localStorage.getItem('aiModel')
            // };
        });



        let isSpeaking = false;
        let shouldResume = false;
        let isRecording = false;
        let mediaRecorder;
        let recordedChunks;
        let speechRecognitionActive = false;
        let speechStartTimeout;
        let accessToken = localStorage.getItem('access_token');
        let clientId = generateClientId(); // Generate unique client ID
        let pendingPastedImage;

        // Generate a unique client ID
        function generateClientId() {
            return 'client_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
        }

        // Helper function to convert base64 to Blob
        function base64toBlob(base64Data, contentType = '') {
            const byteCharacters = atob(base64Data);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            return new Blob([byteArray], { type: contentType });
        }

        // Send data to FastAPI backend
        async function sendToBackend(messageType, content) {
            const selectedLanguage = document.getElementById("language-select").value;
            const savedClassMode = localStorage.getItem('classMode');
            const savedVoiceConfig = localStorage.getItem('voiceConfig');
            const savedAiModel = localStorage.getItem('aiModel');
            

            const formData = new FormData();
            formData.append('client_id', clientId);
            formData.append('language', selectedLanguage);
            formData.append('message_type', messageType);
            formData.append('content', content);
            formData.append('mode', savedClassMode);
            formData.append('voice', savedVoiceConfig);
            formData.append('model', savedAiModel);
            


            if (accessToken) {
                formData.append('access_token', accessToken);
            }

            try {
                showLoadingAnimation();
                const response = await fetch('https://lm.warals.codetorise.com/chat/', {
                    method: 'POST',
                    body: formData
                });
                

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                

                // Handle the response
                if (data.message) {
                    // Handle simple message response (for trial limits, errors, etc.)
                    addMessage(data.message, 'gemini');
                } else if (data.gemini_response) {
                    // Handle normal Gemini response
                    addMessage(`Gemini: ${data.gemini_response}`, 'gemini');

                    // Handle audio if present
                    if (data.audio_base64 && !speechRecognitionActive) {
                        const audioBlob = base64toBlob(data.audio_base64, 'audio/mpeg');
                        const audioURL = URL.createObjectURL(audioBlob);
                        audioPlayer.src = audioURL;
                        audioPlayer.play();
                        isSpeaking = true;
                        document.getElementById('pause-resume-button').style.display = 'inline-block';
                        document.getElementById('stop-button').style.display = 'inline-block';
                        pauseResumeButton.innerHTML = '<i class="fas fa-pause"></i> Pause';

                        audioPlayer.onended = () => {
                            isSpeaking = false;
                            pauseResumeButton.innerHTML = '<i class="fas fa-play"></i> Play';
                            URL.revokeObjectURL(audioURL);
                        };
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                addMessage('Error: Failed to connect to server', 'gemini');
            } finally {
                hideLoadingAnimation();
            }
        }

        function toggleSpeech() {
            if (isSpeaking) {
                audioPlayer.pause();
                isSpeaking = false;
                pauseResumeButton.innerHTML = '<i class="fas fa-play"></i> Play';
            } else if (audioPlayer.src) {
                audioPlayer.play();
                isSpeaking = true;
                pauseResumeButton.innerHTML = '<i class="fas fa-pause"></i> Pause';
            }
        }

        function stopSpeech() {
            if (isSpeaking) {
                audioPlayer.pause();
                audioPlayer.currentTime = 0;
                isSpeaking = false;
                pauseResumeButton.innerHTML = '<i class="fas fa-play"></i> Play';
            }
        }

        function handleSpeechButtonClick() {
            if (!speechRecognitionActive) {
                speechRecognitionActive = true;
                startSpeechListening();
                startSpeechButton.innerHTML = '<i class="fas fa-microphone-slash"></i> Listening...';
            } else {
                stopSpeechListening();
                speechRecognitionActive = false;
                startSpeechButton.innerHTML = '<i class="fas fa-microphone"></i> Start Speech';
            }
        }

        async function startSpeechListening() {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const source = audioContext.createMediaStreamSource(stream);
                const analyser = audioContext.createAnalyser();
                const processor = audioContext.createScriptProcessor(2048, 1, 1);
                source.connect(analyser);
                analyser.connect(processor);
                processor.connect(audioContext.destination);

                recordedChunks = [];
                mediaRecorder = new MediaRecorder(stream);
                let silenceStart = null;
                const SILENCE_DELAY = 3000; // 3 seconds

                mediaRecorder.ondataavailable = event => {
                    if (event.data.size > 0) {
                        recordedChunks.push(event.data);
                    }
                };

                mediaRecorder.onstop = () => {
                    processor.disconnect();
                    analyser.disconnect();
                    source.disconnect();
                    if (recordedChunks.length > 0) {
                        const audioBlob = new Blob(recordedChunks, { type: 'audio/webm' });
                        const reader = new FileReader();
                        reader.onloadend = () => {
                            const base64Audio = btoa(reader.result);
                            sendToBackend('audio', base64Audio);
                            addMessage('You sent a voice message', 'user');
                        };
                        reader.readAsBinaryString(audioBlob);
                    }
                    isRecording = false;
                    speechRecognitionActive = false;
                    startSpeechButton.innerHTML = '<i class="fas fa-microphone"></i> Start Speech';
                };

                processor.onaudioprocess = function () {
                    const data = new Uint8Array(analyser.frequencyBinCount);
                    analyser.getByteFrequencyData(data);
                    const volume = data.reduce((a, b) => a + b) / data.length;

                    const THRESHOLD = 10; // adjust this for sensitivity
                    if (volume > THRESHOLD) {
                        if (!isRecording) {
                            mediaRecorder.start();
                            isRecording = true;
                            console.log("Speech detected, recording started");
                        }
                        silenceStart = null; // reset silence timer
                        if (isSpeaking) {
                            audioPlayer.pause();
                            shouldResume = true;
                        }
                    } else {
                        if (isRecording) {
                            if (!silenceStart) {
                                silenceStart = Date.now();
                            } else if (Date.now() - silenceStart > SILENCE_DELAY) {
                                mediaRecorder.stop();
                                stream.getTracks().forEach(track => track.stop());
                                console.log("Silence detected, recording stopped");
                            }
                        }
                    }
                };
            } catch (err) {
                console.error("Microphone error:", err);
                speechRecognitionActive = false;
                startSpeechButton.innerHTML = '<i class="fas fa-microphone"></i> Start Speech';
            }
        }

        function stopSpeechListening() {
            if (isRecording && mediaRecorder && mediaRecorder.state === 'recording') {
                mediaRecorder.stop();
                isRecording = false;
            }
            speechRecognitionActive = false;
            startSpeechButton.innerHTML = '<i class="fas fa-microphone"></i> Start Speech';
        }

        // Handle Enter key press
        function handleKeyDown(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault(); // Prevent newline
                sendMessage();
            }
        }

        // Send text message function
        function sendMessage() {
            const input = document.getElementById('message-input');
            const text = input.value.trim();

            const savedClassMode = localStorage.getItem('classMode');
            const savedVoiceConfig = localStorage.getItem('voiceConfig');
            const savedAiModel = localStorage.getItem('aiModel');
            console.log('Class Mode', savedClassMode);
            console.log('Voice Selected', savedVoiceConfig);
            console.log('Selected AI Model', savedAiModel);

            if (text !== "") {
                // Add user message to the chat
                addMessage(`You: ${text}`, 'user');


                // Send to backend
                sendToBackend('text', text);

                // Clear the input field
                input.value = '';
            }
            if (pendingPastedImage) {
                sendToBackend('file', pendingPastedImage);
                pendingPastedImage = null;
                document.getElementById('image-preview').innerHTML = ""; // Clear preview
            }

        }

        // Add message to chat container
        function addMessage(message, sender) {
            const messageCard = document.createElement('div');
            messageCard.classList.add('card', 'chat-message');
            messageCard.classList.add(sender === 'user' ? 'user-card' : 'gemini-card');
            document.getElementById('chat-container').style.display = 'block';
            const cardBody = document.createElement('div');
            cardBody.classList.add('card-body');
            cardBody.innerHTML = message;

            messageCard.appendChild(cardBody);
            chatContainer.appendChild(messageCard);
            chatContainer.scrollTop = chatContainer.scrollHeight; // Scroll to bottom
        }

        // Loading animation functions
        function showLoadingAnimation() {
            loadingIndicator.style.display = 'block';
        }

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

        // Handle file input change event
        document.getElementById('file-upload').addEventListener('change', handleFileSelected);





        async function handleFileSelected(event) {
            var file = event.target.files[0];
            const files = event.target.files;
            const maxSizeMB = .9; // Set your desired max size in MB
            const maxSize = maxSizeMB * 1024 * 1024; // Convert to bytes
            const TARGET_KB = 850;
            const TARGET_BYTES = TARGET_KB * 1024;


            if (!file) return;

            const allowedTypes = ['application/pdf', 'image/png', 'image/jpeg', 'image/jpg'];
            if (!allowedTypes.includes(file.type)) {
                alert("Only PDF and image files are allowed.");
                return;
            }
            if (file.size > 2*1024*1024) {
                
                event.target.value = ''; // Clears the selected file(s)
                alert("File Size is too large");
                return;
            }
            
            if (file.type.startsWith('image/') && file.size > maxSize) {
        try {
            const compressedFile = await compressImage(file, TARGET_BYTES);
            file = compressedFile;
            
            
            console.log('File compressed and ready for upload:', compressedFile);
            
            
        } catch (error) {
            console.error('Image compression failed:', error);
            
            // sendFileToBackend(file);
        }
        }
        
            

            const reader = new FileReader();
            reader.onload = function (e) {
                const base64File = e.target.result.split(',')[1];

                // Send to backend
                sendToBackend('file', base64File);
                addMessage(`<img src="${e.target.result}" style="width: 100px; height: 120px;">`, 'user');
                addMessage(`You sent a file: ${file.name}`, 'user');
            };

            reader.readAsDataURL(file); // read as base64
        }

        document.getElementById('message-input').addEventListener('paste', function (event) {
            const items = event.clipboardData.items;
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") !== -1) {
                    const file = items[i].getAsFile();
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        pendingPastedImage = e.target.result.split(',')[1]; // Save for later
                        addMessage(`<img src="${e.target.result}" style="width: 100px; height: 120px;">`, 'user');
                    };
                    reader.readAsDataURL(file);
                    event.preventDefault();
                }
            }
        });


        // Function to compress image using Canvas API
function compressImage(file, targetSizeInBytes, quality = 0.8) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
            const img = new Image();
            img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                // Set initial canvas dimensions to image dimensions
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0, img.width, img.height);

                // Function to try and compress
                const tryCompress = (currentQuality) => {
                    // For JPEG, quality ranges from 0 to 1
                    // For PNG, quality is ignored (it's lossless unless resized)
                    // If you need PNG transparency and size reduction, you typically only resize.
                    const mimeType = 'image/jpeg'; // Or file.type if you want to keep original type (beware of PNG size)

                    canvas.toBlob((blob) => {
                        if (!blob) {
                            reject(new Error('Canvas toBlob failed.'));
                            return;
                        }

                        if (blob.size <= targetSizeInBytes || currentQuality <= 0.1) { // Stop if target reached or quality too low
                            resolve(new File([blob], file.name, { type: mimeType, lastModified: Date.now() }));
                        } else {
                            // Reduce quality and try again
                            const newQuality = Math.max(0.1, currentQuality - 0.1); // Decrease quality by 0.1
                            tryCompress(newQuality);
                        }
                    }, mimeType, currentQuality);
                };

                tryCompress(quality); // Start compression attempt
            };
            img.onerror = reject; // Handle image loading errors
            img.src = event.target.result;
        };
        reader.onerror = reject; // Handle file reading errors
        reader.readAsDataURL(file); // Read file as Data URL
    });
}



        // Function to save settings
        function saveSettings() {
            const classMode = document.querySelector('input[name="classMode"]:checked').value;
            const voiceConfig = document.querySelector('input[name="voiceConfig"]:checked').value;
            const aiModel = document.getElementById('aiModelSelect').value;

            // Store settings (e.g., in localStorage)
            localStorage.setItem('classMode', classMode);
            localStorage.setItem('voiceConfig', voiceConfig);
            localStorage.setItem('aiModel', aiModel);

            // You can also update a global JS object if needed
            // appSettings.classMode = classMode;
            // appSettings.voiceConfig = voiceConfig;
            // appSettings.aiModel = aiModel;

            console.log("Settings saved:", { classMode, voiceConfig, aiModel });

            // Close the modal
            const settingsModal = bootstrap.Modal.getInstance(document.getElementById('settingsModal'));
            settingsModal.hide();

            // Here you would typically re-initialize or adjust your application's behavior
            // based on the new settings.
        }

        // Function to load settings when the page loads (optional, but good for persistence)
        document.addEventListener('DOMContentLoaded', (event) => {
            const savedClassMode = localStorage.getItem('classMode');
            if (savedClassMode) {
                document.querySelector(`input[name="classMode"][value="${savedClassMode}"]`).checked = true;
            }

            const savedVoiceConfig = localStorage.getItem('voiceConfig');
            if (savedVoiceConfig) {
                document.querySelector(`input[name="voiceConfig"][value="${savedVoiceConfig}"]`).checked = true;
            }

            const savedAiModel = localStorage.getItem('aiModel');
            if (savedAiModel) {
                document.getElementById('aiModelSelect').value = savedAiModel;
            }

        });
        
        function logOut() {
            window.location.href = "/logout";
        }


    </script>
</body>
</body>
</html>

