home_page = """
<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.5/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="icon" type="image/x-icon" href="https://media.istockphoto.com/id/1032803298/vector/concept-of-sharing-ideas-between-a-social-network.jpg?s=1024x1024&w=is&k=20&c=flQycFZv11Squs6Q4u5H8Ml21V93bog2ZIm3wmBgnOI=">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <title>Ai Teacher</title>
    <style>
    body {
        font-family: 'Inter', sans-serif;
        background-color: #f4f6f9;
        color: #212529;
    }

        .main-container {
            display: flex;
            align-items: center;
            justify-content: center;
            height: calc(100vh - 150px); 
            
            
        }

        .output-part {
            min-width 850px;
            width: 850px;
            max-width: 900px;
            
            transition: all 0.3s ease;
            
        }

        #chat-container {
            flex-grow: 1;
            overflow-y: auto;
            padding-bottom: 150px;
            width: 850px;
            height: 600px;
            display: none;
            
            
        }

        #chat-container > div {
            display: flex;
            flex-direction: column;
            
        }

        .card {
            min-width 850px;
            width: 100%;
            max-width: 1000px;
            margin: 0 auto;
            border-radius: 16px;
            border: none;
            box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        }


        .user-card {
        
        background-color: #d1e7dd;
            align-self: flex-end;
            margin-left: auto;
            max-width: 80%;
        }

        .gemini-card {
            background-color: #f8d7da;
            align-self: flex-start;
            margin-right: auto;
            max-width: 80%;
        }

        .chat-message {
            margin-bottom: 10px;
            border-radius: 12px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        }

        .input-part {
        background-color: #ffffff;
            border-radius: 16px;
            padding: 16px;
            max-width: 900px;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            transition: box-shadow 0.3s ease;
            justify-content: center;
            width: 100%;
            max-width: 900px;
            position: fixed;
            bottom: 0;
            left: 2;
            right: 2;
            background-color: #ffffff;
            margin-bottom: 20px;
            margin-left: 100px;
            margin-right: 100px;
            z-index: 100;
        }
        .input-part select,
            .input-part textarea {
                border-radius: 8px;
            }
            #message-input {
                border-radius: 10px;
                padding-right: 40px;
                min-height: 50px;
                resize: none;
                box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
            }

            .input-part:hover {
                box-shadow: 0 -4px 16px rgba(0,0,0,0.15);
            }

            #file-upload + label i {
                color: #6c757d;
                transition: color 0.3s;
            }

            #file-upload + label:hover i {
                color: #495057;
            }

        .loading-animation {
            border: 4px solid #f3f3f3; /* Light grey */
            border-top: 4px solid #3498db; /* Blue */
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 2s linear infinite;
            display: inline-block; /* To be next to the message */
            margin-left: 5px;
        }

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

        .controls-container {
            margin-top: 12px;
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 10px;
            position: relative;
            align-items: center;
        }

        .controls-container button {
            flex-grow: 1;
            border-radius: 8px;
            min-width: 120px;
            font-weight: 500;
        }

        #loading-indicator {
            position: absolute;
            top: 0;
            right: 0;
            margin: 10px;
        }
        .loading-animation {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #007bff;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            animation: spin 1s linear infinite;
        }

        .premium-header {
    background: linear-gradient(90deg, #2c3e50, #4ca1af); /* Deep gradient */
    padding: 20px 0;
    color: #ffffff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    font-family: 'Poppins', sans-serif;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    z-index: 1000;
}

.premium-header .head-part {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 0;
    }

    .premium-header h1 {
        font-size: 28px;
        font-weight: 600;
        margin: 0;
        letter-spacing: 1px;
    }

    .image-popup {
        position: fixed;
        bottom: 100px; /* adjust based on input location */
        right: 30px;
        background-color: #ffffff;
        border-radius: 12px;
        padding: 12px;
        box-shadow: 0 4px 14px rgba(0, 0, 0, 0.15);
        z-index: 200;
        text-align: center;
        max-width: 180px;
    }
    .image-popup img {
        max-width: 100%;
        border-radius: 8px;
        object-fit: contain;
    }


</style>
</head>
<body class="container py-4">

<header class="fixed-top premium-header">
  <div class="container head-part">
    <h1 class="mb-0">Interactive Learning</h1>
  </div>
</header>
<div class="main-container">
    <div class="output-part">
        <div class="card" style="background-color: #FFFFED;">
            <div class="card-body" id="chat-container" style="height: 300px; overflow-y: auto;"></div>
        </div>
    </div>
    
    <div id="image-preview" class="mt-2"></div>
    
    <div class="input-part" id="draggable-input">
        <div class="mt-1 position-relative">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <div>
                    <label for="language-select" class="form-label mb-0 me-2">Select Language:</label>
                    <select id="language-select" class="form-select d-inline-block w-auto">
                        <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>
                    <button id="reset-button" class="btn btn-light" style="margin-left: 500px;" title="Reset">
                        <i class="fas fa-redo" style="font-size: 20px;"></i> </button>
                    <button id="settings-button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#settingsModal">
                        <i class="fas fa-cog" style="font-size: 20px;"></i>
                    </button>
            </div>
            <div style="position: relative; display: flex; align-items: center;">
                <textarea id="message-input" rows="2" class="form-control" placeholder="Type your message..." onkeydown="handleKeyDown(event)"></textarea>
                

                <!-- File input icon -->
                <label for="file-upload" style="position: absolute; right: 10px; bottom: 10px; cursor: pointer;" title="Supported Files(pdf, png, jpg and jpeg),\nMaximum File Size: 10MB")>
                    <i class="fas fa-paperclip" style="font-size: 30px;"></i>
                </label>

                <!-- Hidden file input -->
                <input type="file" id="file-upload" style="display: none;" accept=".pdf,image/*">
            </div>
            <div class="controls-container">
                <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()">Send</button>
                <div id="loading-indicator" style="display: none;">
                    <div class="loading-animation"></div>
                </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>

<div class="modal fade" id="settingsModal" tabindex="-1" aria-labelledby="settingsModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="settingsModalLabel">Settings</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Explanation Level:</label>
                    <div>
                        <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-3">
                    <label class="form-label">Voice Configuration:</label>
                    <div>
                        <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">AI Model:</label>
                    <select class="form-select" 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">Close</button>
                <button type="button" class="btn btn-primary" onclick="saveSettings()">Save changes</button>
                <button type="button" class="btn btn-primary" onclick="saveSettings()">Save changes</button>
                
            </div>
        </div>
    </div>
</div>

<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

    // 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('http://127.0.0.1:8000/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);
        

        


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

        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 > maxSize) {
                    //errorParagraph.textContent = `Error: File "${file.name}" is too large. Maximum size allowed is ${maxSizeMB} MB.`;
                    // Optionally clear the input, though it might be annoying for the user
                    event.target.value = ''; // Clears the selected file(s)
                    alert("File Size is too large");
                    return;
                }

        const reader = new FileReader();
        reader.onload = function(e) {
            const base64File = e.target.result.split(',')[1]; // remove the data:*/*;base64, part
            
            // Send to backend
            sendToBackend('file', base64File);
            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="max-width: 100%;">`, 'user');
                };
                reader.readAsDataURL(file);
                event.preventDefault();
            }
        }
    });
   

   // 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;
        }
        
    });
    

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