{% extends 'base.html' %}

{% block content %}
<div class="container mx-auto px-4">
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h1 class="text-3xl font-bold mb-6">Ergebnisse</h1>
        
        <div class="mb-6">
            <h2 class="text-xl font-bold mb-4">Aktuelle Frage</h2>
            <p class="text-lg mb-2">{{ question_data.question }}</p>
            <div class="grid grid-cols-2 gap-4">
                {% for option in question_data.options %}
                
            <div id="option-box-{{ forloop.counter0 }}" class="bg-gray-100 relative p-4 rounded-lg overflow-hidden {% if option.is_correct %} border-2 border-green-500{% else %}border-2 border-red-500{% endif %}">
            
            <div id="option-fill-{{ forloop.counter0 }}" class="absolute left-0 top-0 h-full {% if option.is_correct %}bg-green-300 {% else %}bg-red-300 {% endif %} opacity-50 z-0 transition-all duration-1500 " style="width: 0%;"></div>
            <div class="relative z-10">
            <p class="text-lg">{{ option.value }}</p>
            <p class="text-gray-600" id="option-count-{{ forloop.counter0 }}">0 Antworten</p>
             
            </div>
        </div>
                {% endfor %}
            </div>
        </div>


        <div class="mb-6">
            <h2 class="text-xl font-bold mb-4">Punktestand</h2>
            <div id="scoreboard" class="space-y-2">
                {% for participant in participants %}
                    {% if participant == my_participant or is_host %}
                        <div class="p-4 bg-gray-100 rounded-lg flex justify-between items-center border {% if forloop.counter <= 3 %}border-yellow-500{% else %}border-transparent{% endif %}">
                            <div>  
                                <p class="text-lg font-bold">
                                    {% if forloop.counter == 1 %}
                                        🥇 
                                    {% elif forloop.counter == 2 %}
                                        🥈 
                                    {% elif forloop.counter == 3 %}
                                        🥉 
                                    {% endif %}
                                    {{ participant.display_name }}
                                </p>
                                <p data-last-score="{{ participant.last_score }}" class="text-gray-600" id="score-{{ forloop.counter0 }}">{{ participant.score }} Punkte</p> 
                            </div>                     
                            {% if participant.last_answer_correct %}
                                <span class="text-green-500">✓</span>
                            {% elif participant.last_answer_correct == False %}
                                <span class="text-red-500">✗</span>
                            {% endif %}
                        </div>
                    {% endif %}
                {% endfor %}
            </div>
        </div>
 
    {% if is_host %}
        {% if is_last_question %}
            <button id="finish-button" class="w-full p-3 rounded-full bg-blue-600 text-white font-bold hover:bg-blue-700 transition-colors duration-200">
                Quiz beenden
            </button>
        {% else %}
            <button id="next-button" class="w-full p-3 rounded-full bg-blue-600 text-white font-bold hover:bg-blue-700 transition-colors duration-200">
                Nächste Frage
            </button>
        {% endif %}
    {% endif %}    
    </div>
</div>
{% endblock %}

{% block extra_js %}
{% if is_last_question %}

<script>
    // Hilfsfunktion für Pausen
    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
  
    document.addEventListener('DOMContentLoaded', async function() {
      const items = document.querySelectorAll('#scoreboard div');
      const top3 = Array.from(items).slice(0, 3); // Nur die ersten 3 animieren
  
      // Sofort Startzustände für Top3 setzen, die anderen sofort sichtbar
      items.forEach((el, index) => {
        if (index >= 3) {
          el.style.opacity = '1';
          el.style.transform = 'translateY(0)';
        } else {
          el.style.opacity = '0';
          el.style.transform = 'translateY(20px)';
        }
      });
  
      // Warten bevor Animation startet
      await sleep(1500);  // <<< hier die 5 Sekunden Pause
  
      // Transition-Eigenschaft setzen nach Render-Zyklus
      requestAnimationFrame(() => {
        top3.forEach(el => {
          el.style.transition = 'all 0.8s ease';
        });
  
        // Animation für Top 3 starten – von Platz 3 zu 1
        top3.reverse().forEach((el, index) => {
          setTimeout(() => {
            el.style.opacity = '1';
            el.style.transform = 'translateY(0)';
  
            if (index === top3.length - 1) {
              triggerConfetti();
            }
          }, index * 1500); // Zeitversetzt aufdecken
        });
      });
    });
  
    function triggerConfetti() {
      const end = Date.now() + 15 * 1000;
      (function frame() {
        confetti({ particleCount: 2, angle: 60, spread: 55, origin: { x: 0 } });
        confetti({ particleCount: 2, angle: 120, spread: 55, origin: { x: 1 } });
        if (Date.now() < end) requestAnimationFrame(frame);
      })();
    }
  </script>
{% endif %}  
{% include 'play/game/common_scripts.html' %}
{% if is_host %}
{% include 'play/game/sound.html' %}
{% endif %}
<script>
    const joinCode = '{{ quiz_game.join_code }}';
    const hostId = '{{ host_id }}';
    const wsScheme = window.location.protocol === 'https:' ? 'wss' : 'ws';
    const gameSocket = new WebSocket(
        `${wsScheme}://${window.location.host}/ws/game/${joinCode}/`
    );

    gameSocket.onmessage = function(e) {
        const data = JSON.parse(e.data);
        if (data.type === 'game_state_update' && 
            data.redirect_url && 
            (data.action === 'next_question' || data.action === 'finish_game')) {
            window.location.href = data.redirect_url;
        } else if (data.type === 'answer_stats') {
            updateAnswerStats(data.stats);
        }
    };

    gameSocket.onclose = function(e) {
        // Normal closure (code 1000) oder Navigation zu einer anderen Seite (code 1001)
        if (e.code === 1000 || e.code === 1001) {
            console.log('Game socket closed normally');
        } else {
            console.error('Game socket closed unexpectedly', e.code);
        }
    };

    {% if is_host %}
    // Add click handlers for host buttons
    {% if is_last_question %}
    var finishButton = document.getElementById('finish-button');
    if (finishButton) {
        finishButton.addEventListener('click', function() {
            gameSocket.send(JSON.stringify({
                'type': 'finish_game',
                'host_id': hostId
            }));
        });
    }
    {% else %}
    var nextButton = document.getElementById('next-button');
    if (nextButton) {
        nextButton.addEventListener('click', function() {
            gameSocket.send(JSON.stringify({
                'type': 'next_question',
                'host_id': hostId
            }));
        });
    }
    {% endif %}
    {% endif %}

function updateAnswerStats(stats) {
    const total = Object.values(stats).reduce((a, b) => a + b, 0) || 1;

    for (var optionIndex in stats) {
        if (stats.hasOwnProperty(optionIndex)) {
            var countElement = document.getElementById('option-count-' + optionIndex);
            var fillElement = document.getElementById('option-fill-' + optionIndex);

            if (countElement) {
                countElement.textContent = stats[optionIndex] + ' Antwort(en)';
            }

            if (fillElement) {
                const percentage = Math.round((stats[optionIndex] / total) * 100);
                fillElement.style.width = percentage + '%';
            }
        }
    }
}

    // Request answer stats when page loads
    gameSocket.onopen = function(e) {
        gameSocket.send(JSON.stringify({
            'type': 'get_answer_stats'
        }));
    };
</script>
{% endblock %}