<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SmartLearn - PDF Q&A</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
         .audio-container {
        display: none;
    }
    .audio-list {
        display: block;
        margin-top: 1rem;
    }
    .audio-list ul {
        list-style-type: none;
        padding: 0;
    }
    .audio-list li {
        padding: 0.5rem;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }
    .audio-list li:hover {
        background-color: #f0f2f5;
    }
        .audio-list {
            display: block;
            margin-top: 1rem;
        }
        .audio-container {
            display: none;
        }

        .audio-list ul {
            list-style-type: none;
            padding: 0;
        }
        .audio-list li {
            padding: 0.5rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .audio-list li:hover {
            background-color: #f0f2f5;
        }
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f0f2f5;
            margin: 0;
            padding: 0;
            color: #333;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        video#background-video {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            z-index: -1;
        }
        .container {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 1200px;
            margin: 2rem auto;
            padding: 2rem;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .content-wrapper {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        .pdf-container, .chat-container,.audio-container {
            flex: 1;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        .pdf-container {
            margin-right: 1rem;
        }
        .chat-container {
            margin-left: 1rem;
        }
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 2rem;
        }
        .back-button {
            align-self: flex-start;
            background-color: #3498db;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            margin-bottom: 1rem;
        }
        .back-button:hover {
            background-color: #2980b9;
        }
        .pdf-upload {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 1rem;
            background-color: #f8f9fa;
            border-radius: 10px 10px 0 0;
        }
        .pdf-upload input[type="file"] {
            display: none;
        }
        .pdf-upload label {
            background-color: #3498db;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .pdf-upload label:hover {
            background-color: #2980b9;
        }
        .pdf-upload button {
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 5px;
            cursor: pointer;
            margin-left: 1rem;
            transition: background-color 0.3s ease;
        }
        .pdf-upload button:hover {
            background-color: #27ae60;
        }
        .pdf-status {
            text-align: center;
            padding: 0.5rem;
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }
        .pdf-content {
            flex: 1;
            padding: 1rem;
            overflow-y: auto;
            font-size: 0.9rem;
            line-height: 1.5;
        }
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
        }
        .message {
            margin-bottom: 1rem;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            max-width: 80%;
        }
        .user-message {
            background-color: #3498db;
            color: white;
            align-self: flex-end;
            margin-left: auto;
        }
        .ai-message {
            background-color: #ecf0f1;
            color: #333;
        }
        .chat-input {
            display: flex;
            padding: 1rem;
            background-color: #f8f9fa;
            border-top: 1px solid #e9ecef;
        }
        .chat-input input {
            flex-grow: 1;
            padding: 0.5rem;
            border: 1px solid #ced4da;
            border-radius: 20px;
            margin-right: 1rem;
        }
        .chat-input button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .chat-input button:hover {
            background-color: #2980b9;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .loading-icon {
            animation: spin 2s linear infinite;
            display: inline-block;
            margin-right: 0.5rem;
        }
        .button-container {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 1rem;
        }
        .mode-button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-left: 0.5rem;
            font-weight: 500;
            display: flex;
            align-items: center;
        }
        .mode-button:hover {
            background-color: #2980b9;
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .mode-button i {
            margin-right: 0.5rem;
        }
        .active {
            background-color: #2ecc71;
        }
        .active:hover {
            background-color: #27ae60;
        }
        .audio-player {
            display: none;
            width: 100%;
            margin-top: 1rem;
        }
        .audio-player audio {
            width: 100%;
            border-radius: 10px;
        }
        .audio-list {
            display: none;
            margin-top: 1rem;
        }
        .audio-list ul {
            list-style-type: none;
            padding: 0;
        }
        .audio-list li {
            padding: 0.5rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .audio-list li:hover {
            background-color: #f0f2f5;
        }
    </style>
</head>
<body>
    <video id="background-video" autoplay loop muted>
        <source src="../static/pdf.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>
    <div class="container">
        <button class="back-button" onclick="goBack()"><i class="fas fa-arrow-left"></i> Back</button>
        <h1><i class="fas fa-file-pdf"></i> PDF Q&A</h1>
        <div class="button-container">
            <button id="text-mode" class="mode-button active" onclick="switchMode('text')">
                <i class="fas fa-keyboard"></i> Ask questions
            </button>
            <button id="audio-mode" class="mode-button" onclick="switchMode('audio')">
                <i class="fas fa-microphone"></i> Audio book
            </button>
        </div>
        <div class="content-wrapper">
            <div class="pdf-container">
                <div class="pdf-upload">
                    <label for="pdf-file">
                        <i class="fas fa-upload"></i> Choose PDF
                    </label>
                    <input type="file" id="pdf-file" accept=".pdf">
                    <button onclick="uploadPDF()"><i class="fas fa-cloud-upload-alt"></i> Upload PDF</button>
                </div>
                <div id="pdf-status" class="pdf-status"></div>
                <div id="pdf-content" class="pdf-content"></div>
            </div>
            <div class="chat-container">
                <div id="chat-messages" class="chat-messages"></div>
                <div id="text-input" class="chat-input">
                    <input type="text" id="user-input" placeholder="Ask a question about the PDF...">
                    <button onclick="sendMessage()"><i class="fas fa-paper-plane"></i> Send</button>
                </div>
            </div>
            <div id="audio-container" class="audio-container">
                <h3>Get your audio book for all chapters here</h3>
                <audio id="uploaded-audio" controls>
                    Your browser does not support the audio tag.
                </audio>
                <div id="audio-list" class="audio-list">
                    <ul>
                        <!-- Audio files will be dynamically inserted here -->
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <script>
        document.getElementById('audio-mode').addEventListener('click', function() {
    switchMode('audio');
});
        const chatMessages = document.getElementById('chat-messages');
        const userInput = document.getElementById('user-input');
        const pdfStatus = document.getElementById('pdf-status');
        const pdfContent = document.getElementById('pdf-content');
        let pdfText = '';

        function uploadPDF() {
            const fileInput = document.getElementById('pdf-file');
            const file = fileInput.files[0];
            if (file) {
                const formData = new FormData();
                formData.append('pdf-file', file);

                pdfStatus.innerHTML = '<i class="fas fa-spinner loading-icon"></i> Uploading and processing PDF...';

                fetch('/student_pdfqa', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.pdf_text) {
                        pdfText = data.pdf_text;
                        pdfStatus.innerHTML = `<i class="fas fa-check-circle"></i> PDF "${file.name}" uploaded and processed. You can now ask questions.`;
                        displayPDFContent(pdfText);
                        addMessage("PDF uploaded successfully. What would you like to know about its contents?", false);
                    } else {
                        pdfStatus.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${data.message}`;
                    }
                })
                .catch(error => {
                    pdfStatus.innerHTML = '<i class="fas fa-times-circle"></i> Error uploading the PDF. Please try again.';
                    console.error('Error:', error);
                });
            } else {
                pdfStatus.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Please select a PDF file first.';
            }
        }

        function displayPDFContent(text) {
            pdfContent.innerHTML = '';
            const paragraphs = text.split('\n\n');
            paragraphs.forEach(paragraph => {
                if (paragraph.trim()) {
                    const p = document.createElement('p');
                    p.textContent = paragraph;
                    pdfContent.appendChild(p);
                }
            });
        }

        function addMessage(content, isUser) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
            messageDiv.textContent = content;
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function sendMessage() {
            const message = userInput.value.trim();
            if (message) {
                if (!pdfText) {
                    addMessage("Please upload a PDF first before asking questions.", false);
                    return;
                }
                addMessage(message, true);
                userInput.value = '';

                const loadingMessage = document.createElement('div');
                loadingMessage.className = 'message ai-message';
                loadingMessage.innerHTML = '<i class="fas fa-spinner loading-icon"></i> Thinking...';
                chatMessages.appendChild(loadingMessage);
                chatMessages.scrollTop = chatMessages.scrollHeight;

                fetch('/ask_pdf_question', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        query: message,
                        pdf_text: pdfText
                    })
                })
                .then(response => response.json())
                .then(data => {
                    chatMessages.removeChild(loadingMessage);
                    addMessage(data.response, false);
                })
                .catch(error => {
                    chatMessages.removeChild(loadingMessage);
                    addMessage('Error getting the response. Please try again.', false);
                    console.error('Error:', error);
                });
            }
        }

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

    function goBack() {
        window.history.back();
    }

    function switchMode(mode) {
        const textButton = document.getElementById('text-mode');
        const audioButton = document.getElementById('audio-mode');
        const chatContainer = document.querySelector('.chat-container');
        const audioContainer = document.getElementById('audio-container');
        const audioList = document.getElementById('audio-list');

        if (mode === 'text') {
            textButton.classList.add('active');
            audioButton.classList.remove('active');
            chatContainer.style.display = 'flex';
            audioContainer.style.display = 'none';
        } else if (mode === 'audio') {
            audioButton.classList.add('active');
            textButton.classList.remove('active');
            chatContainer.style.display = 'none';
            audioContainer.style.display = 'flex';
            audioList.style.display = 'block';
            loadAudioList();
        }
    }

    function loadAudioList() {
        const audioList = document.getElementById('audio-list').querySelector('ul');
        audioList.innerHTML = '<li>Loading audio files...</li>';

        fetch('/get_audio_files')
            .then(response => response.json())
            .then(data => {
                console.log('Audio files data:', data);
                audioList.innerHTML = '';
                if (data.audio_files && data.audio_files.length > 0) {
                    data.audio_files.forEach(file => {
                        console.log('Adding file:', file);
                        const listItem = document.createElement('li');
                        listItem.textContent = file.name;
                        listItem.onclick = () => playAudio(file.url);
                        audioList.appendChild(listItem);
                    });
                } else {
                    audioList.innerHTML = '<li>No audio files available</li>';
                }
            })
            .catch(error => {
                console.error('Error loading audio files:', error);
                audioList.innerHTML = '<li>Error loading audio files</li>';
            });
    }

    function playAudio(url) {
        const audio = document.getElementById('uploaded-audio');
        audio.src = url;
        audio.load();
        audio.play();
    }

    // Initialize the page in text mode
    switchMode('text');
</script>
</body>
</html>