{% load shop_extras %}
<div class="small-12 medium-6 large-3 my-block">
    <div class="bubble">
        {% if product.image %}
        <div class="slider-container" id="slider-{{ product.id }}">
            {% color_images_url product.image product.colors.all.0.name product.sku as images %}
            <div class="slides">
                {% for image_url in images %}
                <img src="{{ image_url }}"
                     alt="{{ product.title }}"
                     class="product-image {% if forloop.first %}active{% endif %}"
                     id="product-image-{{ product.id }}-{{ forloop.counter0 }}">
                {% endfor %}
            </div>
            {% if images|length > 1 %}
            <button class="prev" onclick="changeSlide({{ product.id }}, -1)">❮</button>
            <button class="next" onclick="changeSlide({{ product.id }}, 1)">❯</button>
            {% endif %}
        </div>
        {% else %}
        <div class="no-image">No Image Available</div>
        {% endif %}
        <form method="post" action="{% url 'shop:add_to_cart' product.id %}" class="add-to-cart-form" id="cart-form-{{ product.id }}">
            {% csrf_token %}
            <div class="options-container">
                <div class="option-element product-title">
                    {{ product.title }}
                </div>
                {% if product.description %}
                <div class="option-element product-description">
                    {{ product.description }}
                </div>
                {% endif %}

                <div class="option-element product-price">{{ product.price }} €</div>
                <div class="option-element color-label"><span id="selected-color-name-{{ product.id }}">{{ product.colors.all.0.name }}</span></div>
                <div class="option-element color-selector form-group">
                    {% if product.colors.exists %}
                    <input type="hidden" name="color" id="color-{{ product.id }}" value="{{ product.colors.all.0.id }}" required>
                    <div class="color-samples">
                        {% for color in product.colors.all %}
                        {% color_images_url product.image color.name product.sku as color_images %}
                        <div class="color-sample {% if forloop.first %}selected{% endif %}"
                             {% if color.secondary_hex_color %}
                             style="background-image: linear-gradient(to right, {{ color.colorHex }} 50%, {{ color.secondary_hex_color }} 50%);"
                             {% else %}
                             style="background-color: {{ color.colorHex }};"
                             {% endif %}
                             title="{{ color.name }}"
                             data-color-id="{{ color.id }}"
                             data-color-name="{{ color.name }}"
                             data-color-images="{{ color_images|join:',' }}"
                             onclick="selectColor('{{ product.id }}', '{{ color.id }}', '{{ color.name }}', this)">
                        </div>
                        {% endfor %}
                    </div>
                    {% endif %}
                </div>


                <div class="option-element size-selector form-group">
                    {% if product.sizes.exists %}
                        {% if product.sizes.all|length == 1 %}
                            <input type="hidden" name="size" value="{{ product.sizes.all.0.id }}">
                            <div>{{ product.sizes.all.0.name }}</div>

                        {% else %}
                            <select name="size" id="size-{{ product.id }}" class="form-control" required>
                                <option value="" disabled selected>Taille</option>
                                {% for size in product.sizes.all %}
                                <option value="{{ size.id }}" {% if forloop.first %}selected{% endif %}>{{ size.name }}</option>
                                {% endfor %}
                            </select>
                        {% endif %}
                    {% endif %}
                </div>
                <div class="option-element quantity-selector form-group">
                    <div class="quantity-controls">
                        <input type="hidden" name="quantity" id="quantity-{{ product.id }}" value="1">
                        <button type="button" class="quantity-btn decrease-btn" onclick="adjustQuantity('{{ product.id }}', -1, {{ product.price }})" disabled>-</button>
                        <span class="quantity-value" id="quantity-display-{{ product.id }}">1</span>
                        <button type="button" class="quantity-btn increase-btn" onclick="adjustQuantity('{{ product.id }}', 1, {{ product.price }})">+</button>
                    </div>
                </div>
                <div class="option-element total-price form-group"><span id="total-price-{{ product.id }}">{{ product.price }}</span> €</div>
            </div>
            <button type="button" class="add-to-cart-button" onclick="addToCartAjax('{{ product.id }}')">Ajouter au panier</button>
        </form>
    </div>
</div>

<script>

function adjustQuantity(productId, change, price) {
    let quantityInput = document.getElementById(`quantity-${productId}`);
    let quantityDisplay = document.getElementById(`quantity-display-${productId}`);

    // Get the decrease button that's within the same form as the quantity input
    let decreaseBtn = quantityInput.closest('.quantity-controls').querySelector('.decrease-btn');

    let currentQuantity = parseInt(quantityInput.value) || 1;

    // Calculate new quantity
    let newQuantity = currentQuantity + change;

    // Enforce min/max limits
    if (newQuantity < 1) newQuantity = 1;
    if (newQuantity > 10) newQuantity = 10;

    // Update quantity in hidden input and display
    quantityInput.value = newQuantity;
    quantityDisplay.textContent = newQuantity;

    // Enable/disable decrease button based on quantity
    decreaseBtn.disabled = (newQuantity <= 1);

    // Update total price
    updateTotal(productId, price);
}

function updateTotal(productId, price) {
    let quantityInput = document.getElementById(`quantity-${productId}`);
    let totalPriceElement = document.getElementById(`total-price-${productId}`);

    let quantity = parseInt(quantityInput.value) || 1; // Default to 1 if invalid
    let totalPrice = (quantity * price).toFixed(2); // Ensure two decimal places

    totalPriceElement.textContent = totalPrice;
}

function selectColor(productId, colorId, colorName, element) {
    // Update hidden input value
    document.getElementById(`color-${productId}`).value = colorId;

    // Update displayed color name
    document.getElementById(`selected-color-name-${productId}`).textContent = colorName;

    // Remove selected class from all colors
    const colorSamples = element.parentElement.querySelectorAll('.color-sample');
    colorSamples.forEach(sample => sample.classList.remove('selected'));

    // Add selected class to clicked color
    element.classList.add('selected');

    // Update product images based on selected color
    const slider = document.getElementById(`slider-${productId}`);
    if (slider) {
        const colorImages = element.getAttribute('data-color-images').split(',');
        const slidesContainer = slider.querySelector('.slides');

        // Clear existing slides
        slidesContainer.innerHTML = '';

        // Add new slides
        colorImages.forEach((imageUrl, index) => {
            const img = document.createElement('img');
            img.src = imageUrl;
            img.alt = colorName;
            img.className = `product-image ${index === 0 ? 'active' : ''}`;
            img.id = `product-image-${productId}-${index}`;
            slidesContainer.appendChild(img);
        });

        // Update navigation buttons visibility
        const navButtons = slider.querySelectorAll('.prev, .next');
        navButtons.forEach(button => {
            button.style.display = colorImages.length > 1 ? 'block' : 'none';
        });
    }
}

function addToCartAjax(productId) {
    // Get the form
    const form = document.getElementById(`cart-form-${productId}`);
    const formData = new FormData(form);

    // Add CSRF token
    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

    // Create notification element
    const notification = document.createElement('div');
    notification.className = 'add-to-cart-notification';
    notification.style.position = 'fixed';
    notification.style.bottom = '20px';
    notification.style.right = '20px';
    notification.style.padding = '20px';
    notification.style.backgroundColor = '#90ee90';
    notification.style.color = '#707070';
    notification.style.borderRadius = '12px';
    notification.style.zIndex = '9999';
    notification.style.opacity = '0';
    notification.style.transition = 'opacity 0.3s';

    // Send AJAX request
    fetch(form.action, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': csrftoken,
        }
    })
    .then(response => response.json())
    .then(data => {
        // Show success message
        notification.textContent = data.message;
        document.body.appendChild(notification);

        // Update cart total in the navigation
        const cartTotalElements = document.querySelectorAll('.confirm-nav-button');
        cartTotalElements.forEach(element => {
            element.textContent = `Voir mon panier (${data.cart_total} €)`;
        });

        // Show notification
        setTimeout(() => { notification.style.opacity = '1'; }, 100);

        // Hide notification after 3 seconds
        setTimeout(() => {
            notification.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300); // Wait for fade-out animation
        }, 3000);
    })
    .catch(error => {
        console.error('Error:', error);
        notification.textContent = "Erreur lors de l'ajout au panier";
        notification.style.backgroundColor = '#F44336';
        document.body.appendChild(notification);

        // Show notification
        setTimeout(() => { notification.style.opacity = '1'; }, 100);

        // Hide notification after 3 seconds
        setTimeout(() => {
            notification.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300); // Wait for fade-out animation
        }, 3000);
    });
}

function changeSlide(productId, direction) {
    const slides = document.querySelectorAll(`#slider-${productId} .product-image`);
    let activeIndex = Array.from(slides).findIndex(slide => slide.classList.contains('active'));

    // Remove active class from current slide
    slides[activeIndex].classList.remove('active');

    // Calculate new index
    activeIndex = activeIndex + direction;
    if (activeIndex >= slides.length) activeIndex = 0;
    if (activeIndex < 0) activeIndex = slides.length - 1;

    // Add active class to new slide
    slides[activeIndex].classList.add('active');
}

</script>
