{% extends 'base.html' %}
{% block content %}



<div class="container mx-auto px-4">
    <div class="flex justify-end mb-4">
        {% if request.session.mode == "learn" %}
        <button onclick="leaveGame()" class="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded">
            Spiel verlassen
        </button>
        {% endif %}
        <button onclick="this.onclick=null; advanceToScores();" class="mx-2 bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
            überspringen
        </button>
    </div>
    <div id="form_host" class="bg-white rounded-lg shadow-md p-4 mb-6 dark:bg-transparent dark:text-white">
        <div class="flex justify-between mb-2">
            <div class="flex gap-1 text-sm"><p class="text-sm">Frage</p>
                <p class="text-gray-700 font-bold text-sm dark:text-white">{{ question_index|add:1 }}</p>
                <p class="text-sm">von</p>
                <p class="text-gray-700 font-bold text-sm dark:text-white">{{ total_questions }}</p>
            </div>
        <div class="flex gap-1 mb-2"><p class="text-sm">Antworten:</p> <p id="answer-count" class="text-gray-700 font-bold text-sm dark:text-white"></p></div>
        </div>

        
        

        <h1 class="text-xl font-black mb-2 border-blue-500 border-4 p-4 text-center rounded-lg md:text-2xl lg:text-4xl">{{ question_data.question}}</h1>

        {% if question_image %}
            <div class="flex justify-center">
                <img class="m-4 max-h-[33vh] w-auto rounded-lg" src="{{ question_image.image.url }}" alt="Bild der Frage">
            </div>
        {% endif %}
            {% if request.session.mode != "learn" %}
           <div class="w-full bg-gray-300 rounded-full h-4">
           <div id="time-bar" class="bg-blue-600 h-4 rounded-full transition-all duration-100 linear" style="width: 100%;"></div>
           </div>
            {% endif %}
        
        {% if request.session.mode == "learn" %} 
        <div class="grid grid-cols-1 gap-4 mb-6">
        {% else %}
        <div class="grid grid-cols-2 gap-4 mb-6">
        {% endif %}


        </div>
        {% if question_data.type  != "input" %}
        <div class="grid grid-cols-2 gap-4" id="options-container">
            {% for option in question_data.options %}
                <button 
                    class="  
                    {% if forloop.counter0 == 0 %}
                    bg-green-500
                    hover:bg-green-600
                    {% elif forloop.counter0 == 1 %}
                    bg-red-500
                    hover:bg-red-600
                    {% elif forloop.counter0 == 2 %}
                    bg-blue-500
                    hover:bg-blue-600
                    {% elif forloop.counter0 == 3 %}
                    bg-purple-500
                    hover:bg-purple-600
                    {% elif forloop.counter0 == 4 %}
                    bg-orange-500
                    hover:bg-orange-600
                    {% elif forloop.counter0 == 5 %}
                    bg-yellow-500
                    hover:bg-yellow-600
                    {% else %}
                    bg-gray-500
                    hover:bg-gray-600
                    {% endif %}
                    p-4 rounded-lg text-white transition-colors duration-200 answer-option overflow-auto break-words hyphens-auto "
                    data-index="{{ forloop.counter0 }}"
                    {% if request.session.mode == "learn" %}
                    onclick="submitAnswer({{ forloop.counter0 }});" {% endif %}>
                    <p class="text-lg">{{ option.value }}</p>
                </button>
            {% endfor %}
        </div>
        {% else %}
        {% if request.session.mode == "learn" %}
        <form action="">
        <input id="textanswer" type="text" placeholder="DEINE ANTWORT" 
        class="answer-option text-center p-2 bg-gray-100 hover:bg-blue-100 rounded-lg transition-colors duration-200 answer-option lg:w-80 dark:bg-transparent dark:text-white dark:hover:bg-[#2a2f3a] ">
   
 <button {% if request.session.mode == "learn" %}
 onclick="submitAnswer( -1 );" {% endif %}
         class="mt-2 text-center p-2 bg-gray-100 hover:bg-blue-100 rounded-lg transition-colors duration-200 answer-option dark:bg-transparent dark:text-white dark:hover:bg-[#2a2f3a] ">
     abschicken
 </button>
</form>
  
        {% endif %}
        {% endif %}


    </div>
</div>
{% endblock %}



{% block extra_js %}
{% include 'play/game/common_scripts.html' %}
{% include 'play/game/sound.html' %}
<script>
    const joinCode = '{{ quiz_game.join_code }}';
    const hostId = '{{ host_id }}';
    const questionStartTime = {{ start_time }};
    const questionDuration = '{{ current_question.time_per_question }}'*1000; //Zeit pro Frage (indviduell eingestellt)
    const gameSocket = initializeGameSocket(joinCode);
    let answeredParticipants = 0;
    let totalParticipants = 0;
    const optionCounts = {};
    
    gameSocket.onmessage = function(e) {
        const data = JSON.parse(e.data);
        if (data.type === 'participant_answer') {
            answeredParticipants++;
            updateAnswerCount();
            updateOptionCount(data.answer);
        } else if (data.type === 'participant_list_update') {
            totalParticipants = data.participants.length;
            updateAnswerCount();
        } else if (data.type === 'game_state_update' && 
                   data.action === 'show_scores' && 
                   data.redirect_url) {
            window.location.href = data.redirect_url;
            submitAnswer( -1 );
        }
    };

    gameSocket.onclose = function(e) {
        wsUtil.handleClose(e);
    };

    function updateAnswerCount() {
        const answerCountElement = document.getElementById('answer-count');
        if (answerCountElement) {
            answerCountElement.textContent = `${answeredParticipants}/${totalParticipants}`;
        }

        // If everyone has answered, advance to scores
        if (answeredParticipants === totalParticipants && totalParticipants > 0) {
            advanceToScores();
        }
    }

    function updateOptionCount(optionIndex) {
        optionCounts[optionIndex] = (optionCounts[optionIndex] || 0) + 1;
        const optionElement = document.getElementById(`option-count-${optionIndex}`);
        if (optionElement) {
            optionElement.textContent = `${optionCounts[optionIndex]} Antworten`;
        }
    }
    

    function advanceToScores() {
        // Show correct answers and answer counts
        var correctOptions = document.querySelectorAll('[data-correct="True"]');
        for (var i = 0; i < correctOptions.length; i++) {
            correctOptions[i].classList.add('border-2', 'border-blue-500');
        }
        
        // Show answer counts
        var countElements = document.querySelectorAll('[id^="option-count-"]');
        for (var j = 0; j < countElements.length; j++) {
            countElements[j].classList.remove('hidden');
        }
        
        // Wait a moment to show the correct answer and counts
        setTimeout(function() {
            gameSocket.send(JSON.stringify({
                'type': 'advance_to_scores',
                'host_id': hostId
            }));
        }, 2000);
    }

    // Timer
    {% if request.session.mode != "learn" %}
    function updateTimer() {
        const now = Date.now();
        const elapsed = now - questionStartTime;
        const remaining = Math.max(0, (questionDuration - elapsed) / 1000);

        
        //document.getElementById('remaining-time').textContent = remaining;

        document.getElementById('time-bar').style.width = ((remaining * 1000) / questionDuration * 100) + '%';
                if (remaining<3){
        document.getElementById('time-bar').style.backgroundColor="red";}else if(remaining<5){document.getElementById('time-bar').style.backgroundColor="orange";}
   
        if (remaining === 0) {
            advanceToScores();
        } else {
            requestAnimationFrame(updateTimer);
        }
    }

    
    {% endif %}

    // Request initial participants list
    gameSocket.onopen = function(e) {
        gameSocket.send(JSON.stringify({
            'type': 'update_participants'
        }));
        {% if request.session.mode != "learn" %} 
        updateTimer();
        {% endif %}
    };

    
    let hasAnswered = false;
    const participantId = '{{ host_id }}'; // HIER IST DER HOST DER SPIELER

    function leaveGame() {
        if (confirm('Möchtest du das Spiel wirklich verlassen?')) {
            gameSocket.send(JSON.stringify({
                type: 'leave_game',
                participant_id: participantId
            }));
            window.location.href = '/';
            gameSocket.close();
        }
    }

    

    function submitAnswer(optionIndex) {
        if (hasAnswered) return;
        let input = ""; // Declare input here

        try {
       input = document.getElementById("textanswer").value;
      } catch (e) {
       input = "";
       }
        hasAnswered = true;
        const now = Date.now();
        let timeRemaining = Math.max(0, questionDuration - (now - questionStartTime));
        {% if request.session.mode == "learn" %} 
         timeRemaining = questionDuration;
        {% endif %}
        

        // Disable all options and highlight selected
        const options = document.getElementsByClassName('answer-option');
        for (let option of options) {
            option.disabled = true;
            option.classList.remove('hover:bg-blue-100');
            if (parseInt(option.dataset.index) === optionIndex) {
                option.classList.remove('bg-gray-100');
                option.classList.add('bg-blue-600', 'text-white');
            } else {
                option.classList.add('opacity-50');
            }
        }
        if(input!=""){
        // Send answer to server
        gameSocket.send(JSON.stringify({
            type: 'submit_answer',
            participant_id: participantId,
            answer:input, 
            time_remaining: timeRemaining
        }));
    }
    else{
        gameSocket.send(JSON.stringify({
            type: 'submit_answer',
            participant_id: participantId,
            answer:optionIndex,
            time_remaining: timeRemaining
        }));
    }
    }
</script>
{% endblock %}