<?php $__env->startSection('content'); ?>
    <?php
        // Fallbacks so this view works for both practice & exam flows
        $isExam  = $isExam  ?? false;
        $current = isset($current) ? (int)$current : (int)($attempt->total_items ?? 0);
        $max     = isset($max) ? (int)$max : (int)($attempt->max_items ?? 15);
        $urls    = $urls ?? [
            'next'      => route('attempts.next',   $attempt->id),
            'answer'    => route('attempts.answer', $attempt->id),
            'finish'    => route('attempts.finish', $attempt->id),                 // practice default
            'results'   => route('attempts.results', $attempt->id),
            'submitted' => route('exams.attempts.submitted', $attempt->id),        // exam-only
        ];
    ?>

    <div class="row justify-content-center">
        <div class="col-12 col-xl-10 col-xxl-8">
            <div class="card shadow-sm">
                <div class="card-header bg-white d-flex flex-wrap justify-content-between align-items-center gap-2">
                    <div class="d-flex align-items-center gap-2">
          <span class="badge text-bg-primary px-3 py-2" id="counterBadge">
            <span id="answeredCount"><?php echo e($current); ?></span> / <span id="totalCount"><?php echo e($max); ?></span>
          </span>
                        <span class="text-muted small">
            <?php echo e(__('table.items')); ?>

          </span>
                        <span class="ms-3 text-muted small" id="levelBadge" style="display:none;">
            <?php echo e(__('level')); ?>: <span id="levelValue">—</span>
          </span>
                    </div>

                    <div class="d-flex align-items-center gap-2">
                        <div class="btn-group" role="group" aria-label="Font size">
                            <button id="fontMinus" type="button" class="btn btn-outline-secondary btn-sm" title="A−">−</button>
                            <button id="fontReset" type="button" class="btn btn-outline-secondary btn-sm" title="100%">100%</button>
                            <button id="fontPlus"  type="button" class="btn btn-outline-secondary btn-sm" title="A+">+</button>
                        </div>
                    </div>
                </div>

                <div class="card-body">

                    
                    <div id="loadingView" class="text-center py-5">
                        <div class="spinner-border" role="status"></div>
                        <div class="mt-3 text-muted"><?php echo e(__('loading')); ?></div>
                    </div>

                    
                    <div id="questionView" class="d-none">
                        <div id="questionContainer" class="mb-4 adaptive-font-size">
                            <div id="questionStem" class="fs-5 fw-semibold mb-3"></div>
                        </div>

                        <div class="row g-3" id="optionsGrid">
                            
                        </div>

                        <div class="d-flex justify-content-between align-items-center mt-4">
                            <div class="text-muted small" id="langBadge" style="display:none;"></div>
                            <button id="nextBtn" class="btn btn-primary">
                                <?php echo e(__('quiz.next')); ?>

                            </button>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>

    
    <style>
        .option-card { cursor: pointer; border: 1px solid rgba(0,0,0,.1); border-radius: .75rem; padding: .85rem; transition: box-shadow .15s, transform .05s; }
        .option-card:hover { box-shadow: 0 .25rem .75rem rgba(0,0,0,.06); }
        .option-card.selected { border-color: rgba(13,110,253,.5); box-shadow: 0 0 0 .2rem rgba(13,110,253,.15); }
        .option-letter { display: inline-flex; align-items: center; justify-content: center; width: 2rem; height: 2rem; border-radius: 999px; border: 1px solid rgba(0,0,0,.2); margin-inline-end: .5rem; font-weight: 600; }
        .option-text { line-height: 1.5; }
        .adaptive-font-size { font-size: 1rem; } /* base 100% */
        #questionStem { margin-top: .5rem; margin-bottom: 1.25rem; font-size: 1.2em; }
    </style>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const URLS    = <?php echo json_encode($urls, 15, 512) ?>;
            const IS_EXAM = <?php echo json_encode($isExam, 15, 512) ?>;
            const csrf    = <?php echo json_encode(csrf_token(), 15, 512) ?>;

            // Elements
            const loadingView   = document.getElementById('loadingView');
            const questionView  = document.getElementById('questionView');
            const questionStem  = document.getElementById('questionStem');
            const optionsGrid   = document.getElementById('optionsGrid');
            const nextBtn       = document.getElementById('nextBtn');
            const answeredEl    = document.getElementById('answeredCount');
            const totalEl       = document.getElementById('totalCount');
            const levelBadge    = document.getElementById('levelBadge');
            const levelValue    = document.getElementById('levelValue');
            const langBadge     = document.getElementById('langBadge');

            // Font scaling (with cookie)
            const fontContainer = document.querySelector('.adaptive-font-size');
            const FONT_COOKIE = 'quizFontScale';
            const clamp = (v,min,max)=>Math.max(min,Math.min(max,v));
            function getCookie(name){
                return document.cookie.split('; ').find(r => r.startsWith(name+'='))?.split('=')[1] || '';
            }
            function setCookie(name, value, days=180){
                const d = new Date(); d.setTime(d.getTime()+days*24*60*60*1000);
                document.cookie = `${name}=${value};expires=${d.toUTCString()};path=/`;
            }
            let fontScale = parseFloat(getCookie(FONT_COOKIE) || '1.0');
            function applyFont(){
                if (fontContainer) fontContainer.style.fontSize = (fontScale*100).toFixed(0) + '%';
            }
            applyFont();
            document.getElementById('fontMinus').addEventListener('click', () => { fontScale = clamp(fontScale - 0.1, 0.7, 1.8); applyFont(); setCookie(FONT_COOKIE, fontScale); });
            document.getElementById('fontPlus').addEventListener('click',  () => { fontScale = clamp(fontScale + 0.1, 0.7, 1.8); applyFont(); setCookie(FONT_COOKIE, fontScale); });
            document.getElementById('fontReset').addEventListener('click', () => { fontScale = 1.0; applyFont(); setCookie(FONT_COOKIE, fontScale); });

            // State
            let selectedOptionId = null;
            let currentQuestionId = null;
            let lastProgress = { answered: <?php echo json_encode($current, 15, 512) ?>, total: <?php echo json_encode($max, 15, 512) ?> };

            function setLoading(on=true){
                loadingView.classList.toggle('d-none', !on);
                questionView.classList.toggle('d-none', on);
            }

            function renderQuestionPayload(payload){
                currentQuestionId = payload.question.id;
                selectedOptionId  = null;

                // Stem
                questionStem.innerHTML = payload.question.stem || '';

                // Level / language badges (optional)
                if (payload.target_level) {
                    levelValue.textContent = payload.target_level;
                    levelBadge.style.display = '';
                } else {
                    levelBadge.style.display = 'none';
                }
                if (payload.question.lang) {
                    langBadge.textContent = '<?php echo e(__('language')); ?>: ' + (payload.question.lang || '').toUpperCase();
                    langBadge.style.display = '';
                } else {
                    langBadge.style.display = 'none';
                }

                // Options (2x2)
                optionsGrid.innerHTML = '';
                const opts = payload.question.options || [];
                opts.forEach(opt => {
                    const col = document.createElement('div');
                    col.className = 'col-12 col-md-6';
                    col.innerHTML = `
        <div class="option-card adaptive-font-size" data-id="${opt.id}">
          <div class="d-flex align-items-start">
            <span class="option-letter">${opt.label || '?'}</span>
            <div class="option-text flex-grow-1">${opt.text || ''}</div>
          </div>
        </div>
      `;
                    optionsGrid.appendChild(col);
                });

                // Selection
                Array.from(optionsGrid.querySelectorAll('.option-card')).forEach(card => {
                    card.addEventListener('click', () => {
                        Array.from(optionsGrid.querySelectorAll('.option-card')).forEach(c => c.classList.remove('selected'));
                        card.classList.add('selected');
                        selectedOptionId = parseInt(card.getAttribute('data-id'), 10);
                    });
                });

                // Progress & button label
                lastProgress = payload.progress || lastProgress;
                answeredEl.textContent = lastProgress.answered;
                totalEl.textContent    = lastProgress.total;

                const isLast = (lastProgress.answered + 1) >= lastProgress.total;
                nextBtn.textContent = isLast ? <?php echo json_encode(__('quiz.submit'), 15, 512) ?> : <?php echo json_encode(__('quiz.next'), 15, 512) ?>;
            }

            async function fetchNext(){
                setLoading(true);
                try {
                    const res = await fetch(URLS.next, { headers: { 'Accept':'application/json' }});
                    const data = await res.json();
                    if (data.status === 'ok') {
                        renderQuestionPayload(data);
                        setLoading(false);
                    } else if (data.status === 'no_question') {
                        await finalizeAttempt();
                    } else {
                        throw new Error(data.message || 'Unexpected response');
                    }
                } catch (e) {
                    console.error(e);
                    alert('Failed to load.');
                    setLoading(false);
                }
            }

            async function submitAnswer(){
                if (!currentQuestionId || !selectedOptionId) {
                    alert('Please select an option.');
                    return;
                }
                setLoading(true);
                try {
                    const res = await fetch(URLS.answer, {
                        method: 'POST',
                        headers: {
                            'Content-Type':'application/json',
                            'Accept':'application/json',
                            'X-CSRF-TOKEN': csrf,
                        },
                        body: JSON.stringify({
                            question_id: currentQuestionId,
                            option_id: selectedOptionId
                        })
                    });
                    const data = await res.json();
                    if (data.status === 'continue') {
                        lastProgress.answered = (lastProgress.answered || 0) + 1;
                        answeredEl.textContent = lastProgress.answered;
                        await fetchNext();
                    } else if (data.status === 'complete') {
                        lastProgress.answered = lastProgress.total;
                        answeredEl.textContent = lastProgress.answered;
                        await finalizeAttempt();
                    } else {
                        throw new Error('Unexpected status');
                    }
                } catch (e) {
                    console.error(e);
                    alert('Failed to submit.');
                    setLoading(false);
                }
            }

            async function finalizeAttempt(){
                try {
                    await fetch(URLS.finish, { method: 'POST', headers: { 'X-CSRF-TOKEN': csrf, 'Accept':'application/json' } });
                } catch (e) { /* ignore */ }
                window.location = IS_EXAM ? URLS.submitted : URLS.results;
            }

            nextBtn.addEventListener('click', submitAnswer);

            // Kick off
            fetchNext();
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH E:\wamp64\www\cat\resources\views/attempts/show.blade.php ENDPATH**/ ?>