{% extends "tienda/base.html" %}
{% load vat_filters %}
{% block content %}

<div class="row mt-2">
    <div class="col-md-4">
        <div id="carouselProducto" class="carousel slide">
            <div class="carousel-inner">
                <div class="carousel-item active">
                    <img src="/media/{{ product.primary_image.image }}" class="d-block w-100" alt="{{ product.primary_image.alt|default:product.name }}">
                </div>
                {% for image in product.secondary_images.all %}
                    <div class="carousel-item">
                        <img src="/media/{{ image.image }}" class="d-block w-100" alt="{{ image.alt|default:product.name }}">
                    </div>
                {% endfor %}
            </div>
            <button class="carousel-control-prev" type="button" data-bs-target="#carouselProducto" data-bs-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Anterior</span>
            </button>
            <button class="carousel-control-next" type="button" data-bs-target="#carouselProducto" data-bs-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="visually-hidden">Siguiente</span>
            </button>
        </div>
    </div>
    <div class="col-md-1"></div>
    <div class="col-md-5">
        <h1>{{product.name}}</h1>
        <div class="price-section mb-4">
            <div class="small text-muted mb-2">Precio sin IVA (21%):</div>
            <div class="price text-muted mb-3" style="text-decoration: line-through;">€{{ product.price|format_price }}</div>
            
            <div class="small text-primary font-weight-bold mb-2">Precio total (IVA incluido):</div>
            <span class="price" style="font-size: 2rem; color: #28a745;">€{{ product.get_price_with_vat|format_price }}</span>
            <div class="small text-success mt-2"><span aria-hidden="true">ℹ️</span> IVA incluido: €{{ product.get_vat_amount|format_price }}</div>
        </div>
        <div id="descripcion" class="texto-ajustado">
            {{ product.briefdesc }}
        </div>
        <div class="mt-3">
            {% if product.stock > 0 %}
            <span class="badge bg-success" role="status"><span aria-hidden="true">✓</span> Stock disponible: {{ product.stock }}</span>
            {% else %}
            <span class="badge bg-danger" role="status"><span aria-hidden="true">✗</span> Sin stock</span>
            {% endif %}
        </div>
        
        <form method="post" action="{% url 'add_to_cart' product.id %}" class="mt-4">
            {% csrf_token %}
            <div class="mb-3">
                <label for="quantity" class="form-label">Cantidad:</label>
                <input type="number" name="quantity" id="quantity" value="1" min="1" max="{{ product.stock }}" class="form-control" style="max-width: 100px;" {% if product.stock == 0 %}disabled{% endif %}>
            </div>
            <button type="submit" class="btn btn-primary btn-lg" {% if product.stock == 0 %}disabled{% endif %}>🛒 Agregar al Carrito</button>
        </form>
    </div>
</div>
<div class="row pt-2 pb-2">
    <div class="col-md-12 texto-ajustado">
        {{ product.description }}
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-12">
        <h4 class="mb-3">Valoraciones</h4>
        <div id="reviews-summary" class="mb-4">
            <div class="d-flex align-items-center gap-3">
                <div class="fs-4" id="average-rating">0.0</div>
                <div>
                    <div id="stars-display"></div>
                    <small class="text-muted" id="reviews-count">0 valoraciones</small>
                </div>
                {% if can_review %}
                <a href="{% url 'add_review' product.id %}" class="btn btn-sm btn-outline-primary ms-auto">Valorar este producto</a>
                {% elif user_has_review %}
                <div class="ms-auto">
                    <a href="{% url 'add_review' product.id %}" class="btn btn-sm btn-outline-primary">Editar mi valoración</a>
                    <form method="post" action="{% url 'delete_review' user_review_id %}" style="display:inline;">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('¿Eliminar esta valoración?');">Eliminar</button>
                    </form>
                </div>
                {% elif user.is_authenticated %}
                <span class="text-muted ms-auto">Solo puedes valorar productos que hayas comprado</span>
                {% else %}
                <a href="{% url 'login' %}?next={% url 'producto' product.id %}" class="btn btn-sm btn-outline-primary ms-auto">Inicia sesión para valorar</a>
                {% endif %}
            </div>
        </div>
        <div id="reviews-list"></div>
    </div>
</div>

<script>
async function loadReviews() {
    try {
        const response = await fetch("{% url 'product_reviews' product.id %}");
        const data = await response.json();
        
        document.getElementById('average-rating').textContent = data.average_rating;
        document.getElementById('reviews-count').textContent = data.reviews_count + ' valoraciones';
        
        let starsHtml = '';
        for (let i = 1; i <= 5; i++) {
            starsHtml += `<span class="${i <= Math.round(data.average_rating) ? 'text-warning' : 'text-secondary'}">★</span>`;
        }
        document.getElementById('stars-display').innerHTML = starsHtml;
        
        const reviewsList = document.getElementById('reviews-list');
        if (data.reviews.length === 0) {
            reviewsList.innerHTML = '<p class="text-muted">Aún no hay valoraciones para este producto.</p>';
        } else {
            let reviewsHtml = '';
            data.reviews.forEach(review => {
                let imagesHtml = '';
                if (review.images && review.images.length > 0) {
                    imagesHtml = '<div class="mt-2">';
                    review.images.forEach(img => {
                        imagesHtml += `<img src="${img.image}" class="img-thumbnail me-1" style="max-width: 80px; max-height: 80px;" alt="">`;
                    });
                    imagesHtml += '</div>';
                }
                const actionsHtml = review.is_owner 
                    ? `<div class="mt-2">
                         <a href="/tienda/producto/${review.id}/valorar/" class="btn btn-sm btn-outline-primary me-1">Editar</a>
                         <form method="post" action="/tienda/producto/${review.id}/valorar/eliminar/" style="display:inline;">
                           {% csrf_token %}
                           <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('¿Eliminar esta valoración?');">Eliminar</button>
                         </form>
                       </div>`
                    : '';
                reviewsHtml += `
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <strong>${review.user}</strong>
                                    <span class="text-warning ms-1">${'★'.repeat(review.rating)}</span>
                                </div>
                                <small class="text-muted">${new Date(review.created_at).toLocaleDateString('es-ES')}</small>
                            </div>
                            <h6 class="mt-2">${review.title}</h6>
                            <p class="mb-1">${review.content}</p>
                            ${imagesHtml}
                            ${actionsHtml}
                        </div>
                    </div>
                `;
            });
            reviewsList.innerHTML = reviewsHtml;
        }
    } catch (error) {
        console.error('Error loading reviews:', error);
    }
}

loadReviews();
</script>
{% endblock %}
