{% extends "layouts/base.html" %}
{% load static %}

{% block content %}
<div class="min-h-screen bg-black text-white">
  <header class="relative py-16 px-4 text-center border-b border-amber-800/30">
    <div class="absolute inset-0 bg-gradient-to-b from-amber-900/20 to-transparent pointer-events-none"></div>
    <div class="relative z-10 max-w-4xl mx-auto">
      <h1 class="text-5xl md:text-7xl font-bold mb-4">
        <span class="bg-gradient-to-r from-amber-300 via-yellow-400 to-amber-300 bg-clip-text text-transparent">
          {{ event.titre }}
        </span>
      </h1>
      <p class="text-xl text-amber-200/80 font-light tracking-wide">
        CÉRÉMONIE DE CLÔTURE • {{ event.date_fin|date:"d F Y" }}
      </p>
      {% if event.description %}
        <p class="mt-6 text-gray-300 max-w-2xl mx-auto italic border-l-4 border-amber-500 pl-4">
          {{ event.description }}
        </p>
      {% endif %}
    </div>
  </header>

  <div class="max-w-7xl mx-auto px-4 sm:px-6 py-16 space-y-24">
    {% for categorie, podium_list in podiums.items %}
      {% with total_votes=0 %}
        {# Calcul du total des votes pour la catégorie #}
        {% for c in podium_list %}{% with total_votes=total_votes|add:c.nb_votes %}{% endwith %}{% endfor %}
        {# Note: la syntaxe Django pour accumuler est plus complexe, on utilisera plutôt une fonction custom ou un tag #}
        {# Dans un vrai projet, on passerait total_votes depuis la vue. Ici on suppose qu'une variable "total_votes" existe dans le contexte #}
        {# Pour ce template, on utilisera une approche avec regroupement par catégorie déjà calculé #}
      {% endwith %}
      
      <section class="category-section opacity-0 transition-opacity duration-1000">
        <div class="text-center mb-12">
          <h2 class="text-4xl md:text-5xl font-serif text-transparent bg-clip-text bg-gradient-to-r from-amber-200 to-yellow-400 inline-block">
            {{ categorie.nom }}
          </h2>
          <div class="h-px w-32 mx-auto mt-4 bg-gradient-to-r from-transparent via-amber-500 to-transparent"></div>
          {% if categorie.description %}
            <p class="mt-3 text-amber-100/60 text-sm uppercase tracking-widest">{{ categorie.description }}</p>
          {% endif %}
        </div>

        {# Calcul du total des votes pour cette catégorie (pour la barre de progression) #}
        {% with total_votes_category=0 %}
          {% for candidat in podium_list %}
            {% with total_votes_category=total_votes_category|add:candidat.nb_votes %}{% endwith %}
          {% endfor %}
          
          <!-- Podium Desktop -->
          <div class="hidden md:flex justify-center items-end gap-4 lg:gap-8">
            {% for candidat in podium_list %}
              {% with rank=forloop.counter0 %}
                {# Carte premier #}
                {% if rank == 0 %}
                <div class="podium-card flex flex-col items-center w-48 lg:w-64" data-position="first">
                  <div class="mb-2">
                    <span class="px-4 py-1 text-xs font-bold uppercase tracking-wider rounded-full bg-gradient-to-r from-yellow-400 to-amber-500 text-black shadow-lg shadow-yellow-500/30">
                      🏆 Lauréat
                    </span>
                  </div>
                  <div class="relative mb-4 winner-photo">
                    <div class="w-32 h-32 lg:w-40 lg:h-40 rounded-full overflow-hidden frame-gold">
                      <img src="{{ candidat.candidat__photo }}" alt="{{ candidat.candidat__nom_complet }}" class="w-full h-full object-cover">
                    </div>
                  </div>
                  <h3 class="text-xl lg:text-2xl font-bold text-white text-center mb-1">{{ candidat.candidat__nom_complet }}</h3>
                  <div class="flex items-center gap-2 text-amber-300 font-mono">
                    <span class="counter-up text-2xl lg:text-3xl font-light" data-target="{{ candidat.nb_votes }}">0</span>
                    <span class="text-sm uppercase tracking-wider text-amber-500/80">votes</span>
                  </div>
                  <div class="w-full mt-3 h-2 bg-amber-900/40 rounded-full overflow-hidden">
                    <div class="h-full bg-gradient-to-r from-amber-400 to-yellow-400 rounded-full progress-bar"
                         data-percent="{% widthratio candidat.nb_votes total_votes_category 100 %}"></div>
                  </div>
                  <p class="text-xs text-amber-400/70 mt-1">{% widthratio candidat.nb_votes total_votes_category 100 %}%</p>
                </div>
                {% elif rank == 1 %}
                <div class="podium-card flex flex-col items-center w-44 lg:w-56" data-position="second">
                  <div class="mb-2">
                    <span class="px-4 py-1 text-xs font-bold uppercase tracking-wider rounded-full bg-gradient-to-r from-gray-300 to-gray-400 text-black shadow-lg shadow-gray-400/30">
                      🥈 2ème place
                    </span>
                  </div>
                  <div class="relative mb-4">
                    <div class="w-28 h-28 lg:w-32 lg:h-32 rounded-full overflow-hidden frame-silver">
                      <img src="{{ candidat.candidat__photo }}" alt="{{ candidat.candidat__nom_complet }}" class="w-full h-full object-cover">
                    </div>
                  </div>
                  <h3 class="text-lg lg:text-xl font-bold text-white text-center mb-1">{{ candidat.candidat__nom_complet }}</h3>
                  <div class="flex items-center gap-2 text-amber-300 font-mono">
                    <span class="counter-up text-xl lg:text-2xl font-light" data-target="{{ candidat.nb_votes }}">0</span>
                    <span class="text-sm uppercase tracking-wider text-amber-500/80">votes</span>
                  </div>
                  <div class="w-full mt-3 h-2 bg-amber-900/40 rounded-full overflow-hidden">
                    <div class="h-full bg-gradient-to-r from-amber-400 to-yellow-400 rounded-full progress-bar"
                         data-percent="{% widthratio candidat.nb_votes total_votes_category 100 %}"></div>
                  </div>
                  <p class="text-xs text-amber-400/70 mt-1">{% widthratio candidat.nb_votes total_votes_category 100 %}%</p>
                </div>
                {% elif rank == 2 %}
                <div class="podium-card flex flex-col items-center w-40 lg:w-48" data-position="third">
                  <div class="mb-2">
                    <span class="px-4 py-1 text-xs font-bold uppercase tracking-wider rounded-full bg-gradient-to-r from-amber-700 to-amber-800 text-white shadow-lg shadow-amber-800/30">
                      🥉 3ème place
                    </span>
                  </div>
                  <div class="relative mb-4">
                    <div class="w-24 h-24 lg:w-28 lg:h-28 rounded-full overflow-hidden frame-bronze">
                      <img src="{{ candidat.candidat__photo }}" alt="{{ candidat.candidat__nom_complet }}" class="w-full h-full object-cover">
                    </div>
                  </div>
                  <h3 class="text-base lg:text-lg font-bold text-white text-center mb-1">{{ candidat.candidat__nom_complet }}</h3>
                  <div class="flex items-center gap-2 text-amber-300 font-mono">
                    <span class="counter-up text-lg lg:text-xl font-light" data-target="{{ candidat.nb_votes }}">0</span>
                    <span class="text-sm uppercase tracking-wider text-amber-500/80">votes</span>
                  </div>
                  <div class="w-full mt-3 h-2 bg-amber-900/40 rounded-full overflow-hidden">
                    <div class="h-full bg-gradient-to-r from-amber-400 to-yellow-400 rounded-full progress-bar"
                         data-percent="{% widthratio candidat.nb_votes total_votes_category 100 %}"></div>
                  </div>
                  <p class="text-xs text-amber-400/70 mt-1">{% widthratio candidat.nb_votes total_votes_category 100 %}%</p>
                </div>
                {% endif %}
              {% endwith %}
            {% empty %}
              <p class="text-amber-500/70 italic">Aucun candidat dans cette catégorie.</p>
            {% endfor %}
          </div>

          <!-- Podium Mobile (identique à la version précédente) -->
          <div class="md:hidden space-y-4">
            {% for candidat in podium_list %}
              {% with rank=forloop.counter0 %}
                <div class="mobile-card relative bg-black/40 backdrop-blur-sm border border-amber-800/40 rounded-2xl p-4 flex items-center gap-4 animate-slide-up"
                     style="animation-delay: {{ rank }}00ms;">
                  <div class="flex-shrink-0 w-12 h-12 rounded-full flex items-center justify-center text-lg font-bold
                              {% if rank == 0 %}bg-gradient-to-br from-yellow-400 to-amber-600 text-black shadow-lg shadow-yellow-500/30
                              {% elif rank == 1 %}bg-gradient-to-br from-gray-300 to-gray-500 text-black shadow-lg shadow-gray-400/30
                              {% else %}bg-gradient-to-br from-amber-700 to-amber-900 text-white shadow-lg shadow-amber-800/30{% endif %}">
                    {{ rank|add:1 }}
                  </div>
                  <div class="w-16 h-16 rounded-full border-2 {% if rank == 0 %}border-yellow-400 shadow-yellow-500/50{% elif rank == 1 %}border-gray-300 shadow-gray-400/50{% else %}border-amber-700 shadow-amber-800/50{% endif %} shadow-lg overflow-hidden">
                    <img src="{{ candidat.candidat__photo }}" alt="{{ candidat.candidat__nom_complet }}" class="w-full h-full object-cover">
                  </div>
                  <div class="flex-1 min-w-0">
                    <h3 class="font-semibold text-white text-lg truncate">{{ candidat.candidat__nom_complet }}</h3>
                    <div class="flex items-center gap-2 mt-1">
                      <span class="text-sm text-amber-300 font-mono counter-up" data-target="{{ candidat.nb_votes }}">0</span>
                      <span class="text-xs text-amber-500/70">votes</span>
                    </div>
                    <div class="w-full h-1.5 bg-amber-900/40 rounded-full mt-2 overflow-hidden">
                      <div class="h-full bg-gradient-to-r from-amber-400 to-yellow-400 rounded-full progress-bar"
                           data-percent="{% widthratio candidat.nb_votes total_votes_category 100 %}"></div>
                    </div>
                  </div>
                </div>
              {% endwith %}
            {% endfor %}
          </div>
        {% endwith %}
      </section>
    {% endfor %}
  </div>
</div>

<style>
  @keyframes float-up {
    0% { opacity: 0; transform: translateY(40px); }
    60% { opacity: 1; transform: translateY(-8px); }
    80% { transform: translateY(4px); }
    100% { opacity: 1; transform: translateY(0); }
  }
  @keyframes glow-pulse {
    0%, 100% { box-shadow: 0 0 15px theme('colors.amber.400'), 0 0 30px theme('colors.yellow.500'); }
    50% { box-shadow: 0 0 25px theme('colors.amber.300'), 0 0 50px theme('colors.yellow.400'); }
  }
  @keyframes sparkle {
    0% { opacity: 0; transform: scale(0) rotate(0deg); }
    50% { opacity: 1; }
    100% { opacity: 0; transform: scale(1.5) rotate(180deg); }
  }
  @keyframes slide-up {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
  }

  .animate-float-up {
    animation: float-up 0.8s cubic-bezier(0.2, 0.9, 0.3, 1.2) forwards;
  }
  .animate-slide-up {
    animation: slide-up 0.5s ease-out forwards;
    opacity: 0;
  }
  .podium-card {
    transition: transform 0.3s ease;
  }
  .podium-card:hover {
    transform: translateY(-8px);
  }
  .sparkle-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
  }
  .sparkle {
    position: absolute;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: radial-gradient(circle, #FFD966 0%, #FFB347 100%);
    box-shadow: 0 0 10px #FFD700;
    animation: sparkle 2s infinite ease-in-out;
  }
  .progress-bar {
    width: 0%;
    transition: width 1.5s cubic-bezier(0.22, 1, 0.36, 1);
  }
  .frame-gold {
    border: 3px solid;
    border-image: repeating-linear-gradient(45deg, #FFD700, #B8860B, #FFD700) 30;
    box-shadow: 0 0 30px rgba(255, 215, 0, 0.5), 0 8px 20px rgba(0,0,0,0.6);
  }
  .frame-silver {
    border: 3px solid #C0C0C0;
    box-shadow: 0 0 20px rgba(192,192,192,0.4), 0 6px 15px rgba(0,0,0,0.5);
  }
  .frame-bronze {
    border: 3px solid #CD7F32;
    box-shadow: 0 0 15px rgba(205,127,50,0.4), 0 4px 10px rgba(0,0,0,0.5);
  }
</style>

<script>
  (function() {
    "use strict";

    function animateCounter(element, target) {
      if (!element || element.dataset.animated === 'true') return;
      element.dataset.animated = 'true';
      const duration = 1500;
      const start = 0;
      const increment = target / (duration / 16);
      let current = start;
      const timer = setInterval(() => {
        current += increment;
        if (current >= target) {
          element.textContent = target;
          clearInterval(timer);
        } else {
          element.textContent = Math.floor(current);
        }
      }, 16);
    }

    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const section = entry.target;
          
          section.querySelectorAll('.counter-up').forEach(el => {
            const target = parseInt(el.dataset.target, 10);
            if (!isNaN(target)) animateCounter(el, target);
          });

          section.querySelectorAll('.progress-bar').forEach(bar => {
            const percent = bar.dataset.percent;
            if (percent) {
              setTimeout(() => bar.style.width = percent + '%', 200);
            }
          });

          section.querySelectorAll('.podium-card').forEach((card, idx) => {
            setTimeout(() => card.classList.add('animate-float-up'), idx * 100);
          });

          const firstPlaceCard = section.querySelector('[data-position="first"]');
          if (firstPlaceCard && !firstPlaceCard.dataset.particlesAdded) {
            firstPlaceCard.dataset.particlesAdded = 'true';
            addSparklesToWinner(firstPlaceCard);
          }

          observer.unobserve(section);
        }
      });
    }, { threshold: 0.3 });

    document.querySelectorAll('.category-section').forEach(section => observer.observe(section));

    function addSparklesToWinner(winnerElement) {
      const container = document.createElement('div');
      container.className = 'sparkle-container';
      winnerElement.style.position = 'relative';
      winnerElement.appendChild(container);

      const rect = winnerElement.getBoundingClientRect();
      const centerX = rect.width / 2;
      const centerY = rect.height / 2;
      const radius = Math.min(rect.width, rect.height) * 0.6;

      for (let i = 0; i < 18; i++) {
        const sparkle = document.createElement('div');
        sparkle.className = 'sparkle';
        const angle = (i / 18) * Math.PI * 2;
        const distance = radius * (0.7 + Math.random() * 0.6);
        const x = centerX + Math.cos(angle) * distance;
        const y = centerY + Math.sin(angle) * distance;
        sparkle.style.left = x + 'px';
        sparkle.style.top = y + 'px';
        sparkle.style.animationDelay = (Math.random() * 2) + 's';
        sparkle.style.width = (3 + Math.random() * 6) + 'px';
        sparkle.style.height = sparkle.style.width;
        container.appendChild(sparkle);
      }
    }
  })();
</script>
{% endblock %}