{% extends 'base.html' %}
{% load static %}

{% block extra_css %}
<style>
    .quiz-container {
        max-width: 800px;
        margin: 50px auto;
        padding: 40px;
        background: white;
        border-radius: 20px;
        box-shadow: 0 15px 50px rgba(0,0,0,0.1);
        position: relative;
        overflow: hidden;
    }
    .progress-bar {
        background-color: var(--am-blue);
        height: 8px;
        position: absolute;
        top: 0;
        left: 0;
        transition: width 0.3s ease;
    }
    .timer-circle {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        border: 4px solid var(--am-orange);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        font-weight: 700;
        margin: 0 auto 30px;
        color: var(--am-orange);
    }
    .option-btn {
        width: 100%;
        text-align: left;
        padding: 20px;
        margin-bottom: 15px;
        border: 2px solid #eee;
        border-radius: 12px;
        background: transparent;
        font-size: 1.1rem;
        transition: all 0.2s;
        cursor: pointer;
    }
    .option-btn:hover {
        border-color: var(--am-blue);
        background-color: rgba(0, 51, 160, 0.05);
    }
    .option-btn.correct {
        border-color: #28a745;
        background-color: rgba(40, 167, 69, 0.1);
        color: #28a745;
    }
    .option-btn.wrong {
        border-color: var(--am-red);
        background-color: rgba(217, 0, 18, 0.1);
        color: var(--am-red);
    }
    .score-badge {
        font-size: 1.2rem;
        font-weight: 700;
        color: var(--am-blue);
    }
    .result-view { display: none; text-align: center; }
    .quiz-view { display: block; }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="quiz-container">
        <div id="progress" class="progress-bar" style="width: 0%"></div>
        
        <!-- Quiz Play View -->
        <div id="quiz-view" class="quiz-view">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <span id="question-count" class="text-muted">Հարց 1 / 10</span>
                <span class="score-badge">Միավորներ: <span id="current-score">0</span></span>
            </div>
            
            <div class="timer-circle" id="timer">30</div>
            
            <h2 id="question-text" class="text-center mb-5 h3 fw-bold">Բեռնում...</h2>
            
            <div id="options-container" class="row">
                <!-- Options will be injected here -->
            </div>
        </div>

        <!-- Result View -->
        <div id="result-view" class="result-view">
            <h2 class="display-4 fw-bold mb-4">Խաղն ավարտվեց:</h2>
            <div class="my-5">
                <p class="h4 mb-2">Շնորհավորում ենք, <span id="final-player-name"></span>:</p>
                <p class="display-1 fw-bold text-primary mb-2" id="final-score">0</p>
                <p class="h4 text-muted">ընդհանուր միավոր</p>
            </div>
            <div class="d-grid gap-3 d-sm-flex justify-content-center">
                <a href="{% url 'index' %}" class="btn btn-outline-secondary btn-lg px-5">Նորից խաղալ</a>
                <a href="{% url 'leaderboard' %}" class="btn btn-accent btn-lg px-5">Տեսնել արդյունքները</a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    const questions = {{ questions_json|safe }};
    const levelId = {{ level.id }};
    const playerName = localStorage.getItem('playerName') || 'Անանուն';
    
    let currentQuestionIndex = 0;
    let score = 0;
    let timer;
    let timeLeft;

    function initQuiz() {
        if (questions.length === 0) {
            document.getElementById('question-text').innerText = 'Այս մակարդակում հարցեր չկան:';
            return;
        }
        showQuestion();
    }

    function showQuestion() {
        const question = questions[currentQuestionIndex];
        document.getElementById('question-text').innerText = question.text;
        document.getElementById('question-count').innerText = `Հարց ${currentQuestionIndex + 1} / ${questions.length}`;
        document.getElementById('progress').style.width = `${((currentQuestionIndex + 1) / questions.length) * 100}%`;
        
        const optionsContainer = document.getElementById('options-container');
        optionsContainer.innerHTML = '';
        
        question.options.forEach(option => {
            const btn = document.createElement('button');
            btn.className = 'option-btn';
            btn.innerText = option.text;
            btn.onclick = () => selectOption(option, btn);
            optionsContainer.appendChild(btn);
        });

        startTimer(question.time_limit);
    }

    function startTimer(seconds) {
        clearInterval(timer);
        timeLeft = seconds;
        document.getElementById('timer').innerText = timeLeft;
        
        timer = setInterval(() => {
            timeLeft--;
            document.getElementById('timer').innerText = timeLeft;
            if (timeLeft <= 0) {
                clearInterval(timer);
                nextQuestion();
            }
        }, 1000);
    }

    function selectOption(option, btn) {
        clearInterval(timer);
        const options = document.querySelectorAll('.option-btn');
        options.forEach(opt => opt.disabled = true);

        if (option.is_correct) {
            btn.classList.add('correct');
            score += questions[currentQuestionIndex].points;
            document.getElementById('current-score').innerText = score;
        } else {
            btn.classList.add('wrong');
            // Show the correct one
            options.forEach((opt, idx) => {
                if (questions[currentQuestionIndex].options[idx].is_correct) {
                    opt.classList.add('correct');
                }
            });
        }

        setTimeout(nextQuestion, 1500);
    }

    function nextQuestion() {
        currentQuestionIndex++;
        if (currentQuestionIndex < questions.length) {
            showQuestion();
        } else {
            finishQuiz();
        }
    }

    function finishQuiz() {
        document.getElementById('quiz-view').style.display = 'none';
        document.getElementById('result-view').style.display = 'block';
        document.getElementById('final-score').innerText = score;
        document.getElementById('final-player-name').innerText = playerName;

        // Submit score to server
        fetch('/submit_score/', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                player_name: playerName,
                score: score,
                level_id: levelId
            })
        });
    }

    window.onload = initQuiz;
</script>
{% endblock %}
