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

{% block title %}{{ event.titre }} - Golden Night Awards{% endblock %}

{% block extra_head %}
<!-- Google Fonts & Tailwind (si non inclus dans base) -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;600;700&family=Inter:wght@300;400;500&display=swap" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>
<style>
  /* Custom Golden Night Styles */
  body {
    background-color: #0A0A0A;
    font-family: 'Inter', sans-serif;
  }
  .font-cinzel {
    font-family: 'Cinzel', serif;
  }
  .gold-border {
    border-color: #D4AF37;
  }
  .gold-text {
    color: #D4AF37;
  }
  .gold-gradient {
    background: linear-gradient(145deg, #F9E076 0%, #D4AF37 50%, #B68B24 100%);
  }
  .card-hover {
    transition: transform 0.3s ease, box-shadow 0.3s ease, border-color 0.2s;
  }
  .card-hover:hover {
    transform: translateY(-4px);
    box-shadow: 0 20px 30px -10px rgba(0,0,0,0.8), 0 0 0 1px rgba(212, 175, 55, 0.5);
    border-color: #D4AF37 !important;
  }
  .sticky-nav {
    backdrop-filter: blur(12px);
    background-color: rgba(10, 10, 10, 0.8);
    border-bottom: 1px solid rgba(212, 175, 55, 0.3);
    border-top: 1px solid rgba(212, 175, 55, 0.15);
  }
  /* Scrollable category nav */
  .category-scroll::-webkit-scrollbar {
    height: 3px;
  }
  .category-scroll::-webkit-scrollbar-thumb {
    background: #D4AF37;
    border-radius: 10px;
  }
  /* Modal overlay */
  .modal-overlay {
    background: rgba(0, 0, 0, 0.85);
    backdrop-filter: blur(8px);
  }
  /* Touch target minimum 48px */
  .touch-target {
    min-height: 48px;
    min-width: 48px;
  }
  /* Countdown styling */
  .countdown-digit {
    background: #121212;
    border: 1px solid #D4AF37;
    box-shadow: 0 0 10px rgba(212, 175, 55, 0.2);
  }
</style>
{% endblock %}

{% block content %}
<div class="min-h-screen text-gray-100">
  
  {# -------------------- HERO SECTION -------------------- #}
  <section class="relative pt-8 pb-12 md:pt-12 md:pb-16 px-4">
    <div class="max-w-5xl mx-auto">
      <div class="flex flex-col md:flex-row items-center gap-8 md:gap-12">
        <!-- Logo événement -->
        <div class="w-40 h-40 md:w-48 md:h-48 rounded-full border-4 gold-border p-1.5 bg-[#121212] shadow-2xl flex-shrink-0">
          {% if event.logo %}
            <img src="{{ event.logo.url }}" alt="{{ event.titre }}" class="w-full h-full object-cover rounded-full">
          {% else %}
            <div class="w-full h-full rounded-full bg-gradient-to-br from-amber-900/40 to-stone-900 flex items-center justify-center">
              <span class="text-5xl font-cinzel gold-text">{{ event.titre|slice:":1"|upper }}</span>
            </div>
          {% endif %}
        </div>
        <!-- Titre & Dates -->
        <div class="text-center md:text-left flex-1">
          <h1 class="font-cinzel text-3xl md:text-4xl lg:text-5xl font-bold gold-text mb-3 drop-shadow-[0_4px_6px_rgba(212,175,55,0.3)]">
            {{ event.titre }}
          </h1>
          <p class="text-gray-300 text-lg mb-4">{{ event.description|truncatewords:30 }}</p>
          <div class="flex flex-wrap gap-6 justify-center md:justify-start text-sm">
            <div class="flex items-center gap-2">
              <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
              <span>Ouverture : {{ event.date_debut|date:"d M Y, H:i" }}</span>
            </div>
            <div class="flex items-center gap-2">
              <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
              <span>Clôture : {{ event.date_fin|date:"d M Y, H:i" }}</span>
            </div>
          </div>
        </div>
      </div>
      
      {# Compte à rebours #}
      <div class="mt-10 text-center">
        <p class="text-sm uppercase tracking-widest text-amber-300/80 mb-3">Temps restant avant clôture</p>
        <div class="flex justify-center gap-3 md:gap-5" id="countdownContainer">
          <!-- Rempli dynamiquement par JS -->
        </div>
      </div>
    </div>
  </section>

  {# -------------------- STICKY CATEGORY NAV -------------------- #}
  <div class="sticky top-0 z-30 sticky-nav py-3 px-2 shadow-lg">
    <div class="max-w-7xl mx-auto">
      <div class="flex items-center space-x-2 overflow-x-auto category-scroll pb-1" id="categoryNav">
        {% for cat in categories %}
          <a href="#cat-{{ cat.id }}" 
             class="category-link flex items-center gap-2 px-5 py-3 rounded-full whitespace-nowrap transition-all text-sm md:text-base font-medium border border-transparent hover:border-amber-500/50 hover:bg-white/5 touch-target"
             data-cat-id="{{ cat.id }}">
            <span class="font-cinzel">{{ cat.nom }}</span>
            {% if cat.id in user_voted_categories %}
              <svg class="w-4 h-4 text-amber-400" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
              </svg>
            {% endif %}
          </a>
        {% endfor %}
      </div>
    </div>
  </div>

  {# -------------------- CATEGORIES & CANDIDATS -------------------- #}
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 space-y-20">
    {% for categorie in categories %}
      <section id="cat-{{ categorie.id }}" class="scroll-mt-28">
        <!-- En-tête de catégorie -->
        <div class="mb-8 border-b border-amber-700/30 pb-3 flex items-end justify-between">
          <h2 class="font-cinzel text-2xl md:text-3xl gold-text tracking-wide">{{ categorie.nom }}</h2>
          {% if categorie.id in user_voted_categories %}
            <span class="text-xs bg-amber-900/30 text-amber-300 px-3 py-1.5 rounded-full border border-amber-500/40 flex items-center gap-1">
              <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>
              VOTE ENREGISTRÉ
            </span>
          {% endif %}
        </div>
        {% if categorie.description %}
          <p class="text-gray-400 mb-6 italic">{{ categorie.description }}</p>
        {% endif %}

        {# Grille candidats responsive #}
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8">
          {% for candidat in categorie.candidats.all %}
            <div class="bg-[#121212] border border-amber-700/30 rounded-xl overflow-hidden card-hover flex flex-col h-full">
              <!-- Photo avec zoom -->
              <div class="relative h-64 w-full overflow-hidden bg-black/40">
                {% if candidat.photo %}
                  <img src="{{ candidat.photo.url }}" alt="{{ candidat.nom_complet }}" 
                       class="w-full h-full object-cover transition-transform duration-700 hover:scale-105">
                {% else %}
                  <div class="w-full h-full flex items-center justify-center bg-gradient-to-b from-stone-800 to-stone-950">
                    <span class="text-5xl font-cinzel gold-text opacity-50">{{ candidat.nom_complet|slice:":1" }}</span>
                  </div>
                {% endif %}
                <!-- Overlay doré subtil -->
                <div class="absolute inset-0 bg-gradient-to-t from-black via-transparent to-transparent opacity-60"></div>
              </div>
              
              <div class="p-5 flex-1 flex flex-col">
                <h3 class="font-cinzel text-xl font-semibold text-white mb-2">{{ candidat.nom_complet }}</h3>
                <p class="text-gray-400 text-sm line-clamp-3 mb-4 flex-1">
                  {{ candidat.biographie|truncatewords:20|default:"Aucune biographie fournie." }}
                </p>
                
                <div class="flex gap-3 mt-2">
                  {# Bouton Détails (ouvre modale) #}
                  <button type="button" 
                          class="details-trigger flex-1 py-3 px-3 border border-amber-600/40 text-amber-300 hover:bg-amber-900/20 rounded-lg text-sm font-medium transition touch-target"
                          data-candidat-id="{{ candidat.id }}"
                          data-nom="{{ candidat.nom_complet|escapejs }}"
                          data-bio="{{ candidat.biographie|escapejs }}"
                          data-photo="{% if candidat.photo %}{{ candidat.photo.url }}{% else %}{% static 'img/placeholder.jpg' %}{% endif %}">
                    Détails
                  </button>
                  
                  {# Bouton Voter ou badge si déjà voté #}
                  {% if categorie.id in user_voted_categories %}
                    <div class="flex-1 py-3 px-3 bg-gray-800/50 text-gray-400 rounded-lg text-sm font-medium text-center border border-gray-600/30 touch-target flex items-center justify-center gap-1">
                      <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>
                      Voté
                    </div>
                  {% else %}
                    {% if user.is_authenticated %}
                      <form method="post" action="{% url 'awards_vitrine:vote_submit' %}" class="flex-1">
                        {% csrf_token %}
                        <input type="hidden" name="candidat_id" value="{{ candidat.id }}">
                        <button type="submit" 
                                class="w-full py-3 px-3 gold-gradient text-black font-bold rounded-lg text-sm hover:brightness-110 transition shadow-lg shadow-amber-900/30 touch-target">
                          VOTER
                        </button>
                      </form>
                    {% else %}
                      <a href="{% url 'account_login' %}?next={{ request.path }}" 
                         class="flex-1 py-3 px-3 gold-gradient text-black font-bold rounded-lg text-sm text-center hover:brightness-110 transition shadow-lg shadow-amber-900/30 touch-target">
                        VOTER
                      </a>
                    {% endif %}
                  {% endif %}
                </div>
              </div>
            </div>
          {% empty %}
            <p class="col-span-full text-center text-gray-500 py-10">Aucun candidat dans cette catégorie.</p>
          {% endfor %}
        </div>
      </section>
    {% empty %}
      <div class="text-center py-20">
        <p class="text-2xl font-cinzel text-amber-300/60">Aucune catégorie pour le moment.</p>
      </div>
    {% endfor %}
  </div>
</div>

{# -------------------- MODALE BIOGRAPHIE -------------------- #}
<div id="bioModal" class="fixed inset-0 z-50 hidden items-center justify-center p-4 modal-overlay transition-opacity duration-300">
  <div class="bg-[#1A1A1A] border border-amber-500/40 rounded-2xl max-w-2xl w-full max-h-[85vh] overflow-hidden shadow-2xl">
    <div class="p-5 border-b border-amber-800/30 flex justify-between items-center">
      <h3 class="font-cinzel text-2xl gold-text" id="modalCandidatNom"></h3>
      <button id="closeModalBtn" class="text-gray-400 hover:text-amber-400 transition touch-target p-2">
        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
      </button>
    </div>
    <div class="flex flex-col md:flex-row gap-5 p-6 overflow-y-auto">
      <div class="w-full md:w-1/3 flex-shrink-0">
        <img id="modalPhoto" src="" alt="" class="w-full h-48 md:h-64 object-cover rounded-lg border border-amber-700/40">
      </div>
      <div class="flex-1">
        <p id="modalBio" class="text-gray-300 leading-relaxed"></p>
      </div>
    </div>
    <div class="p-4 border-t border-amber-800/30 flex justify-end">
      <button id="modalCloseBtn2" class="px-6 py-2.5 bg-amber-800/30 hover:bg-amber-700/40 text-amber-200 rounded-lg transition touch-target">Fermer</button>
    </div>
  </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
  (function() {
    // ---------- COMPTE À REBOURS ----------
    const countdownContainer = document.getElementById('countdownContainer');
    const endDate = new Date("{{ event.date_fin|date:'c' }}").getTime();
    
    function updateCountdown() {
      const now = new Date().getTime();
      const distance = endDate - now;
      
      if (distance < 0) {
        countdownContainer.innerHTML = '<div class="text-2xl font-cinzel text-amber-400">Vote clos</div>';
        return;
      }
      
      const days = Math.floor(distance / (1000 * 60 * 60 * 24));
      const hours = Math.floor((distance % (86400000)) / (3600000));
      const minutes = Math.floor((distance % 3600000) / 60000);
      const seconds = Math.floor((distance % 60000) / 1000);
      
      const html = `
        <div class="countdown-digit rounded-xl px-4 py-2 md:px-6 md:py-3 text-center min-w-[70px]">
          <span class="block text-2xl md:text-3xl font-bold gold-text font-cinzel">${days}</span>
          <span class="text-xs uppercase tracking-wider text-gray-400">Jours</span>
        </div>
        <div class="countdown-digit rounded-xl px-4 py-2 md:px-6 md:py-3 text-center min-w-[70px]">
          <span class="block text-2xl md:text-3xl font-bold gold-text font-cinzel">${hours}</span>
          <span class="text-xs uppercase tracking-wider text-gray-400">Heures</span>
        </div>
        <div class="countdown-digit rounded-xl px-4 py-2 md:px-6 md:py-3 text-center min-w-[70px]">
          <span class="block text-2xl md:text-3xl font-bold gold-text font-cinzel">${minutes}</span>
          <span class="text-xs uppercase tracking-wider text-gray-400">Minutes</span>
        </div>
        <div class="countdown-digit rounded-xl px-4 py-2 md:px-6 md:py-3 text-center min-w-[70px]">
          <span class="block text-2xl md:text-3xl font-bold gold-text font-cinzel">${seconds}</span>
          <span class="text-xs uppercase tracking-wider text-gray-400">Secondes</span>
        </div>
      `;
      countdownContainer.innerHTML = html;
    }
    updateCountdown();
    setInterval(updateCountdown, 1000);
    
    // ---------- NAVIGATION SMOOTH SCROLL ----------
    document.querySelectorAll('.category-link').forEach(link => {
      link.addEventListener('click', (e) => {
        e.preventDefault();
        const targetId = link.getAttribute('href');
        const targetEl = document.querySelector(targetId);
        if (targetEl) {
          targetEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
      });
    });
    
    // ---------- MODALE BIOGRAPHIE ----------
    const modal = document.getElementById('bioModal');
    const modalNom = document.getElementById('modalCandidatNom');
    const modalBio = document.getElementById('modalBio');
    const modalPhoto = document.getElementById('modalPhoto');
    const closeBtns = [document.getElementById('closeModalBtn'), document.getElementById('modalCloseBtn2')];
    
    function openModal(candidat) {
      modalNom.textContent = candidat.nom;
      modalBio.textContent = candidat.bio || "Aucune biographie détaillée disponible.";
      modalPhoto.src = candidat.photo;
      modalPhoto.alt = candidat.nom;
      modal.classList.remove('hidden');
      modal.classList.add('flex');
      document.body.style.overflow = 'hidden';
    }
    
    function closeModal() {
      modal.classList.add('hidden');
      modal.classList.remove('flex');
      document.body.style.overflow = '';
    }
    
    document.querySelectorAll('.details-trigger').forEach(btn => {
      btn.addEventListener('click', () => {
        const candidat = {
          id: btn.dataset.candidatId,
          nom: btn.dataset.nom,
          bio: btn.dataset.bio,
          photo: btn.dataset.photo
        };
        openModal(candidat);
      });
    });
    
    closeBtns.forEach(btn => btn.addEventListener('click', closeModal));
    modal.addEventListener('click', (e) => {
      if (e.target === modal) closeModal();
    });
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
        closeModal();
      }
    });
    
    // ---------- HIGHLIGHT CATEGORY ACTIVE (scroll spy simple) ----------
    const sections = document.querySelectorAll('section[id^="cat-"]');
    const navLinks = document.querySelectorAll('.category-link');
    
    function updateActiveNav() {
      let current = '';
      const scrollPos = window.scrollY + 150; // offset for sticky nav
      
      sections.forEach(section => {
        const sectionTop = section.offsetTop;
        const sectionBottom = sectionTop + section.offsetHeight;
        if (scrollPos >= sectionTop && scrollPos < sectionBottom) {
          current = section.getAttribute('id');
        }
      });
      
      navLinks.forEach(link => {
        link.classList.remove('border-amber-500', 'bg-white/10');
        link.classList.add('border-transparent');
        const href = link.getAttribute('href').substring(1);
        if (href === current) {
          link.classList.add('border-amber-500', 'bg-white/10');
          link.classList.remove('border-transparent');
        }
      });
    }
    
    window.addEventListener('scroll', updateActiveNav);
    updateActiveNav(); // initial call
  })();
</script>
{% endblock %}