<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cortexa Dictation Assistant</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link
        href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Inter:wght@300;400;500;600&display=swap"
        rel="stylesheet">
    <style>
        :root {
            --primary: #4facfe;
            --secondary: #00f2fe;
            --dark: #2c3e50;
            --light: #f8fafc;
            --accent: #667eea;
            --success: #00b894;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--light);
            color: var(--dark);
        }

        .premium-header {
            background: linear-gradient(135deg, var(--dark) 0%, #34495e 100%);
            padding: 1.5rem 0;
            color: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .main-container {
            max-width: 900px;
            margin: 40px auto;
            padding: 0 20px;
        }

        .card {
            border: none;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
            background: white;
            margin-bottom: 30px;
            overflow: hidden;
        }

        .step-card {
            display: none;
            animation: fadeIn 0.5s ease;
        }

        .active {
            display: block;
        }

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

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .btn-premium {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            border: none;
            border-radius: 12px;
            color: white;
            padding: 12px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-premium:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
            color: white;
        }

        .btn-secondary-custom {
            background: #e2e8f0;
            color: var(--dark);
            border-radius: 12px;
            padding: 12px 25px;
            font-weight: 600;
        }

        .form-select,
        .form-control {
            border-radius: 12px;
            border: 2px solid #e2e8f0;
            padding: 12px;
        }

        .dictation-player {
            text-align: center;
            padding: 40px;
        }

        .player-controls {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 30px;
        }

        .control-btn {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
            background: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .control-btn:hover {
            transform: scale(1.1);
            background: var(--primary);
            color: white;
        }

        .play-btn {
            width: 90px;
            height: 90px;
            font-size: 32px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
        }

        .progress-container {
            margin-top: 30px;
        }

        .progress {
            height: 10px;
            border-radius: 5px;
        }

        .status-badge {
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
            background: rgba(79, 172, 254, 0.1);
            color: var(--primary);
        }

        #extracted-text-preview {
            max-height: 200px;
            overflow-y: auto;
            background: var(--light);
            padding: 15px;
            border-radius: 12px;
            margin-top: 15px;
            font-style: italic;
        }

        .loader {
            border: 4px solid #f3f3f3;
            border-top: 4px solid var(--primary);
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
        }

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

            100% {
                transform: rotate(360deg);
            }
        }

        .step-circle {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #e2e8f0;
            color: var(--dark);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            border: 2px solid white;
            z-index: 2;
            position: relative;
        }

        .active-step .step-circle {
            background: var(--primary);
            color: white;
            box-shadow: 0 0 0 4px rgba(79, 172, 254, 0.2);
        }

        .completed-step .step-circle {
            background: var(--success);
            color: white;
        }

        .step-item {
            flex: 1;
        }
    </style>
</head>

<body>

    <header class="premium-header text-center">
        <div class="container d-flex justify-content-between align-items-center">
            <a href="/home" class="btn text-white"><i class="fas fa-arrow-left"></i> Back</a>
            <h1 class="h3 mb-0 fw-bold">✍️ Cortexa Dictation Assistant</h1>
            <div style="width: 80px;"></div>
        </div>
    </header>

    <div class="main-container">

        <!-- Progress Indicator -->
        <div
            class="step-indicator d-flex justify-content-between text-center small fw-bold text-muted position-relative mb-4">
            <div class="progress position-absolute" style="height: 4px; top: 13px; left: 10%; right: 10%; z-index: 1;">
                <div class="progress-bar bg-success" id="main-progress-bar" role="progressbar" style="width: 0%"></div>
            </div>
            <div class="step-item active-step" id="ind-step-1">
                <div class="step-circle mx-auto mb-1">1</div><span class="d-none d-sm-block">Add Text</span>
            </div>
            <div class="step-item" id="ind-step-2">
                <div class="step-circle mx-auto mb-1">2</div><span class="d-none d-sm-block">Settings</span>
            </div>
            <div class="step-item" id="ind-step-3">
                <div class="step-circle mx-auto mb-1">3</div><span class="d-none d-sm-block">Listen & Write</span>
            </div>
            <div class="step-item" id="ind-step-4">
                <div class="step-circle mx-auto mb-1">4</div><span class="d-none d-sm-block">Upload Answer</span>
            </div>
            <div class="step-item" id="ind-step-5">
                <div class="step-circle mx-auto mb-1">5</div><span class="d-none d-sm-block">Results</span>
            </div>
        </div>

        <!-- Step 1: Welcome & Setup -->
        <div id="step-1" class="step-card active">
            <div class="card p-4">
                <h4 class="fw-bold mb-3">Welcome, {{user.name}}!</h4>
                <p class="text-muted">Cortexa helps you improve your spelling and comprehension through guided
                    dictation. Let's get started.</p>

                <hr>

                <h5 class="fw-bold mb-3">1. Content Selection</h5>
                <div class="mb-3">
                    <label class="form-label">How would you like to provide the content?</label>
                    <div class="d-flex gap-2">
                        <button class="btn btn-outline-primary flex-fill active"
                            onclick="setContentType('text')">Text</button>
                        <button class="btn btn-outline-primary flex-fill" onclick="setContentType('file')">Image /
                            PDF</button>
                    </div>
                </div>

                <div id="text-input-area">
                    <textarea id="raw-text" class="form-control" rows="5"
                        placeholder="Paste your text here..."></textarea>
                </div>

                <div id="file-input-area" style="display:none;">
                    <input type="file" id="content-file" class="form-control" accept="image/*,.pdf">
                    <small class="text-muted">Upload a photo of your book page or a PDF.</small>
                </div>

                <div class="mt-4">
                    <button id="process-btn" class="btn btn-premium w-100" onclick="processContent()">
                        Prepare Dictation <i class="fas fa-magic"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Step 2: Confirmation & Settings -->
        <div id="step-2" class="step-card">
            <div class="card p-4">
                <h4 class="fw-bold mb-3">Confirm Your Dictation Text</h4>
                <p class="text-muted">This is the text that will be read aloud. Please check once before we start.</p>

                <div class="position-relative">
                    <div id="extracted-text-preview" contenteditable="true" onblur="updateExtractedText()"></div>
                    <div class="mt-2 d-flex gap-2">
                        <button class="btn btn-sm btn-outline-secondary"
                            onclick="document.getElementById('extracted-text-preview').focus()">✏️ Edit</button>
                        <button class="btn btn-sm btn-outline-info" onclick="previewAudio()">🔊 Preview Audio</button>
                    </div>
                </div>

                <hr class="my-4">

                <h5 class="fw-bold mb-3">2. Dictation Settings</h5>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Language</label>
                        <select id="language" class="form-select">
                            <option value="english">English</option>
                            <option value="hindi">Hindi</option>
                            <option value="malayalam">Malayalam</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Speed</label>
                        <select id="speed" class="form-select" style="font-size: 16px; padding: 12px;">
                            <option value="slow">Slow 🐢</option>
                            <option value="normal" selected>Normal 🚶</option>
                            <option value="fast">Fast 🏃</option>
                        </select>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label">How should we pause?</label>
                        <select id="chunk-mode" class="form-select" style="font-size: 16px; padding: 12px;">
                            <option value="sentence" selected>After every sentence</option>
                            <option value="phrase">After every few words</option>
                            <option value="none">No pauses</option>
                        </select>
                    </div>
                </div>

                <div class="mt-4 d-flex gap-2">
                    <button class="btn btn-secondary-custom flex-fill" onclick="goToStep(1)">Back</button>
                    <button class="btn btn-premium flex-fill" onclick="startDictation()">▶️ Start Listening</button>
                </div>
                <p class="text-center text-muted mt-3 mb-0 small">
                    <i class="fas fa-camera"></i> After writing, you will upload your notebook photo to check your
                    score.
                </p>
            </div>
        </div>

        <!-- Step 3: Live Dictation Mode -->
        <div id="step-3" class="step-card">
            <div class="card p-4 text-center">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <span class="status-badge">Live Dictation Mode</span>
                    <span id="progress-text" class="fw-bold text-muted">0 / 0</span>
                </div>

                <div class="dictation-player">
                    <div id="welcome-message" class="alert alert-info py-3 mb-4">
                        “Hello! Don't worry, write slowly. You can do this!”
                    </div>

                    <div class="player-controls">
                        <button class="control-btn" id="repeat-btn" onclick="playCurrentChunk()"><i
                                class="fas fa-redo"></i></button>
                        <button class="control-btn play-btn" id="play-pause-btn" onclick="togglePlay()"><i
                                class="fas fa-play"></i></button>
                        <button class="control-btn" id="next-btn" onclick="nextChunk()"><i
                                class="fas fa-forward"></i></button>
                    </div>

                    <div class="progress-container">
                        <div class="progress">
                            <div id="player-progress" class="progress-bar progress-bar-striped progress-bar-animated"
                                role="progressbar" style="width: 0%"></div>
                        </div>
                    </div>

                    <div class="mt-5">
                        <button class="btn btn-success btn-lg px-5 shadow-sm" onclick="completeDictation()">
                            I have completed my writing <i class="fas fa-check-circle"></i>
                        </button>
                    </div>
                </div>

                <div id="hidden-chunk-text" style="display:none;"></div>
            </div>
        </div>

        <!-- Step 4: Completion & Evaluation Input -->
        <div id="step-4" class="step-card">
            <div class="card p-5 text-center">
                <div class="mb-4">
                    <i class="fas fa-award text-warning" style="font-size: 80px;"></i>
                </div>
                <h2 class="fw-bold">Excellent Job!</h2>
                <p class="lead mb-4">You have finished your dictation. Now it's time to check your writing.</p>

                <div class="alert alert-success mb-4">
                    Take a photo of your handwritten work and upload it for AI correction.
                </div>

                <div class="mb-4 text-start">
                    <label class="form-label fw-bold">Upload Your Writing (Photo/Image)</label>
                    <input type="file" id="handwritten-image" class="form-control" accept="image/*">
                </div>

                <div class="mt-4">
                    <button id="evaluate-btn" class="btn btn-premium btn-lg w-100" onclick="performEvaluation()">
                        Evaluate My Work <i class="fas fa-magic"></i>
                    </button>
                    <a href="/home" class="btn btn-link mt-2">Finish without checking</a>
                </div>
            </div>
        </div>

        <!-- Step 5: Scoring Results -->
        <div id="step-5" class="step-card">
            <div class="card p-4">
                <div class="text-center mb-4">
                    <div class="display-1 fw-bold text-primary" id="final-score">0</div>
                    <div class="h4 text-muted">Total Score</div>
                </div>

                <div class="feedback-box alert alert-info p-4 mb-4">
                    <h5 class="fw-bold"><i class="fas fa-comment-dots"></i> Teacher's Feedback</h5>
                    <p id="evaluation-feedback" class="mb-0"></p>
                </div>

                <div class="comparison-view mb-4">
                    <h5 class="fw-bold mb-3">Text Comparison</h5>
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="p-3 border rounded bg-light">
                                <h6 class="fw-bold text-muted">Original Text</h6>
                                <p id="eval-original-text" class="small mb-0"></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="p-3 border rounded bg-white">
                                <h6 class="fw-bold text-muted">What I Wrote</h6>
                                <p id="eval-transcribed-text" class="small mb-0"></p>
                            </div>
                        </div>
                    </div>
                </div>

                <div id="mistakes-section" class="mb-4" style="display:none;">
                    <h5 class="fw-bold text-danger mb-3">Points to Improve</h5>
                    <ul id="mistakes-list" class="list-group list-group-flush"></ul>
                </div>

                <div class="mt-4">
                    <button class="btn btn-premium w-100" onclick="location.reload()">Try Another One <i
                            class="fas fa-redo"></i></button>
                    <a href="/home" class="btn btn-link w-100 mt-2">Back to Home</a>
                </div>
            </div>
        </div>
    </div>

    </div>

    <script>
        let currentStep = 1;
        let contentType = 'text';
        let extractedText = '';
        let clientId = 'dictate_' + Math.random().toString(36).substr(2, 9);
        let sessionData = null;
        let currentChunkIndex = 0;
        let audioPlayer = new Audio();
        let isPlaying = false;

        function setContentType(type) {
            contentType = type;
            const textBtn = document.querySelectorAll('.btn-outline-primary')[0];
            const fileBtn = document.querySelectorAll('.btn-outline-primary')[1];

            if (type === 'text') {
                textBtn.classList.add('active');
                fileBtn.classList.remove('active');
                document.getElementById('text-input-area').style.display = 'block';
                document.getElementById('file-input-area').style.display = 'none';
            } else {
                textBtn.classList.remove('active');
                fileBtn.classList.add('active');
                document.getElementById('text-input-area').style.display = 'none';
                document.getElementById('file-input-area').style.display = 'block';
            }
        }

        function goToStep(step) {
            document.getElementById(`step-${currentStep}`).classList.remove('active');
            document.getElementById(`step-${step}`).classList.add('active');
            currentStep = step;
            window.scrollTo(0, 0);

            // Update progress indicator
            for (let i = 1; i <= 5; i++) {
                const ind = document.getElementById(`ind-step-${i}`);
                if (i < step) {
                    ind.classList.add('completed-step');
                    ind.classList.remove('active-step');
                } else if (i === step) {
                    ind.classList.add('active-step');
                    ind.classList.remove('completed-step');
                } else {
                    ind.classList.remove('active-step');
                    ind.classList.remove('completed-step');
                }
            }
            document.getElementById('main-progress-bar').style.width = ((step - 1) * 25) + "%";
        }

        function updateExtractedText() {
            extractedText = document.getElementById('extracted-text-preview').innerText;
        }

        function previewAudio() {
            const textCtx = document.getElementById('extracted-text-preview').innerText;
            if (!textCtx) return;
            if ('speechSynthesis' in window) {
                window.speechSynthesis.cancel();
                const speed = document.getElementById('speed').value;
                const utterance = new SpeechSynthesisUtterance(textCtx.substring(0, 100) + (textCtx.length > 100 ? "..." : ""));
                utterance.rate = speed === 'slow' ? 0.75 : speed === 'fast' ? 1.5 : 1.0;
                const lang = document.getElementById('language').value;
                if (lang === 'hindi') utterance.lang = 'hi-IN';
                else if (lang === 'malayalam') utterance.lang = 'ml-IN';
                else utterance.lang = 'en-US';
                window.speechSynthesis.speak(utterance);
            } else {
                alert("Preview audio requires a modern browser.");
            }
        }

        async function processContent() {
            const btn = document.getElementById('process-btn');
            const originalContent = btn.innerHTML;
            btn.innerHTML = '<span class="loader"></span> Processing...';
            btn.disabled = true;

            const formData = new FormData();
            formData.append('content_type', contentType);

            if (contentType === 'text') {
                const text = document.getElementById('raw-text').value;
                if (!text) {
                    alert('Please enter some text.');
                    btn.innerHTML = originalContent;
                    btn.disabled = false;
                    return;
                }
                formData.append('text', text);
            } else {
                const file = document.getElementById('content-file').files[0];
                if (!file) {
                    alert('Please select an image or PDF file.');
                    btn.innerHTML = originalContent;
                    btn.disabled = false;
                    return;
                }
                formData.append('file', file);
            }

            try {
                const response = await fetch('/dictation/process-content', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': 'Bearer ' + '{{access_token}}'
                    }
                });

                const data = await response.json();
                if (response.ok) {
                    extractedText = data.text;
                    document.getElementById('extracted-text-preview').innerText = extractedText;
                    goToStep(2);
                } else {
                    alert('Error: ' + data.detail);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Failed to connect to server.');
            } finally {
                btn.innerHTML = originalContent;
                btn.disabled = false;
            }
        }

        async function startDictation() {
            const formData = new FormData();
            formData.append('client_id', clientId);
            formData.append('text', extractedText);
            formData.append('language', document.getElementById('language').value);
            formData.append('speed', document.getElementById('speed').value);
            formData.append('chunk_mode', document.getElementById('chunk-mode').value);

            try {
                const response = await fetch('/dictation/start', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': 'Bearer ' + '{{access_token}}'
                    }
                });

                const data = await response.json();
                if (response.ok) {
                    sessionData = data;
                    currentChunkIndex = 0;
                    document.getElementById('progress-text').innerText = `Progress: 1 / ${data.total_chunks}`;
                    document.getElementById('welcome-message').innerText = data.welcome_message;

                    goToStep(3);

                    // Play welcome message then first chunk
                    await playWelcomeAndStart();
                } else {
                    alert('Error: ' + data.detail);
                }
            } catch (error) {
                alert('Failed to start session.');
            }
        }

        async function playWelcomeAndStart() {
            // Welcome message logic could be TTS too, but for simplicity let's just speak it if possible or skip to content
            // In the requirement: "Cortexa welcomes the student in a calm, friendly voice"
            // I'll fetch the first chunk immediately
            await fetchAndPlayChunk(0);
        }

        async function fetchAndPlayChunk(index) {
            const formData = new FormData();
            formData.append('client_id', clientId);
            formData.append('index', index);

            try {
                const response = await fetch('/dictation/get-chunk', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': 'Bearer ' + '{{access_token}}'
                    }
                });

                const data = await response.json();
                if (response.ok) {
                    document.getElementById('hidden-chunk-text').innerText = data.chunk_text;
                    if (data.audio_base64) {
                        audioPlayer.src = 'data:audio/mpeg;base64,' + data.audio_base64;
                        audioPlayer.playbackRate = getPlaybackRate();
                        audioPlayer.play();
                        isPlaying = true;
                        document.getElementById('play-pause-btn').innerHTML = '<i class="fas fa-pause"></i>';
                    }

                    // Update progress
                    const progress = ((index + 1) / sessionData.total_chunks) * 100;
                    document.getElementById('player-progress').style.width = progress + '%';
                    document.getElementById('progress-text').innerText = `Progress: ${index + 1} / ${sessionData.total_chunks}`;

                    audioPlayer.onended = () => {
                        isPlaying = false;
                        document.getElementById('play-pause-btn').innerHTML = '<i class="fas fa-play"></i>';
                    };
                }
            } catch (error) {
                console.error('Fetch chunk error:', error);
            }
        }

        function togglePlay() {
            if (isPlaying) {
                audioPlayer.pause();
                isPlaying = false;
                document.getElementById('play-pause-btn').innerHTML = '<i class="fas fa-play"></i>';
            } else {
                if (audioPlayer.src) {
                    audioPlayer.playbackRate = getPlaybackRate();
                    audioPlayer.play();
                    isPlaying = true;
                    document.getElementById('play-pause-btn').innerHTML = '<i class="fas fa-pause"></i>';
                } else {
                    fetchAndPlayChunk(currentChunkIndex);
                }
            }
        }

        function playCurrentChunk() {
            if (audioPlayer.src) {
                audioPlayer.currentTime = 0;
                audioPlayer.playbackRate = getPlaybackRate();
                audioPlayer.play();
                isPlaying = true;
                document.getElementById('play-pause-btn').innerHTML = '<i class="fas fa-pause"></i>';
            }
        }

        function nextChunk() {
            if (currentChunkIndex < sessionData.total_chunks - 1) {
                currentChunkIndex++;
                fetchAndPlayChunk(currentChunkIndex);
            } else {
                alert('You have reached the end of the dictation.');
            }
        }

        async function completeDictation() {
            const formData = new FormData();
            formData.append('client_id', clientId);

            try {
                const response = await fetch('/dictation/complete', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': 'Bearer ' + '{{access_token}}'
                    }
                });

                if (response.ok) {
                    goToStep(4);
                }
            } catch (error) {
                alert('Error completing session.');
            }
        }

        async function performEvaluation() {
            const fileInput = document.getElementById('handwritten-image');
            const file = fileInput.files[0];
            if (!file) {
                alert('Please upload a photo of your writing first.');
                return;
            }

            const btn = document.getElementById('evaluate-btn');
            const originalContent = btn.innerHTML;
            btn.innerHTML = '<span class="loader"></span> Evaluating...';
            btn.disabled = true;

            const formData = new FormData();
            formData.append('client_id', clientId);
            formData.append('file', file);

            try {
                const response = await fetch('/dictation/evaluate', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': 'Bearer ' + '{{access_token}}'
                    }
                });

                const data = await response.json();
                if (response.ok) {
                    // Update results page
                    document.getElementById('final-score').innerText = data.score;
                    document.getElementById('evaluation-feedback').innerText = data.feedback;
                    document.getElementById('eval-original-text').innerText = data.original_text;
                    document.getElementById('eval-transcribed-text').innerText = data.transcribed_text;

                    const mistakesList = document.getElementById('mistakes-list');
                    mistakesList.innerHTML = '';
                    if (data.mistakes && data.mistakes.length > 0) {
                        data.mistakes.forEach(m => {
                            const li = document.createElement('li');
                            li.className = 'list-group-item text-danger small py-2';
                            li.innerHTML = `<i class="fas fa-times-circle me-2"></i> ${m}`;
                            mistakesList.appendChild(li);
                        });
                        document.getElementById('mistakes-section').style.display = 'block';
                    } else {
                        document.getElementById('mistakes-section').style.display = 'none';
                    }

                    goToStep(5);
                } else {
                    alert('Evaluation failed: ' + data.detail);
                }
            } catch (error) {
                alert('Connection error during evaluation.');
            } finally {
                btn.innerHTML = originalContent;
                btn.disabled = false;
            }
        }

        function getPlaybackRate() {
            const speed = document.getElementById('speed').value;
            if (speed === 'slow') return 0.75;
            if (speed === 'fast') return 1.5;
            return 1.0; // normal
        }
    </script>

</body>

</html>