{% extends "base.html" %}
{% load static %}
{% load humanize %}

{% block title %}{{ sale.title }} -- {{ PLATFORM_NAME }}{% endblock %}

{% block extra_css %}
<style>
.sale-hero {
    background: linear-gradient(135deg, var(--color-primary-50) 0%, var(--color-bg) 100%);
    padding: var(--space-10) 0 var(--space-8); text-align: center;
}
.sale-hero__business { display: flex; align-items: center; justify-content: center; gap: var(--space-3); margin-bottom: var(--space-4); }
.sale-hero__logo { width: 48px; height: 48px; border-radius: 50%; object-fit: cover; border: 2px solid var(--color-bg-card); box-shadow: var(--shadow-sm); }
.sale-hero__logo-ph { width: 48px; height: 48px; border-radius: 50%; background: var(--color-primary); color: var(--color-text-inverse); display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: var(--font-size-lg); }
.sale-ended-banner { background: var(--color-bg-dark); color: var(--color-text-inverse); text-align: center; padding: var(--space-4); font-weight: 600; font-size: var(--font-size-sm); }
.product-grid { display: grid; grid-template-columns: 1fr; gap: var(--space-6); }
@media (min-width: 640px) { .product-grid { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 1024px) { .product-grid { grid-template-columns: repeat(3, 1fr); } }
.cart-fab { position: fixed; bottom: calc(64px + 16px); right: var(--space-4); z-index: 180; }
@media (min-width: 768px) {
    .cart-fab { bottom: var(--space-6); right: var(--space-6); }
}
.cart-fab__btn { width: 56px; height: 56px; border-radius: 50%; background: linear-gradient(135deg, var(--color-primary), var(--color-primary-light)); color: var(--color-text-inverse); border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: var(--shadow-lg); transition: var(--transition); position: relative; }
.cart-fab__btn:hover { transform: scale(1.05); box-shadow: var(--shadow-xl); }
.cart-fab__badge { position: absolute; top: -4px; right: -4px; background: var(--color-error); color: white; width: 22px; height: 22px; border-radius: 50%; font-size: 11px; font-weight: 700; display: flex; align-items: center; justify-content: center; }
.clickable-card { cursor: pointer; transition: transform 0.2s var(--ease); }
.clickable-card:hover { transform: translateY(-4px); }
.pd-media-gallery { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 8px; margin-top: 8px; }
.pd-media-thumb { width: 60px; height: 60px; border-radius: 4px; object-fit: cover; cursor: pointer; border: 2px solid transparent; }
.pd-media-thumb.active { border-color: var(--color-primary); }
.pd-video-thumb { width: 60px; height: 60px; border-radius: 4px; background: #000; color: #fff; display: flex; align-items: center; justify-content: center; cursor: pointer; border: 2px solid transparent; font-size: 10px; font-weight: bold; }
.pd-video-thumb.active { border-color: var(--color-primary); }
</style>
{% endblock %}

{% block content %}
{% if sale.is_ended %}<div class="sale-ended-banner">This sale has ended.</div>{% endif %}

<section class="sale-hero">
    <div class="container">
        <div class="sale-hero__business animate-in">
            {% if sale.business.logo %}<img src="{{ sale.business.logo.url }}" alt="{{ sale.business.name }}" class="sale-hero__logo">
            {% else %}<div class="sale-hero__logo-ph">{{ sale.business.name|first }}</div>{% endif %}
            <span class="text-secondary">{{ sale.business.name }}</span>
        </div>
        <h1 class="animate-in animate-in--delay-1 mb-4">{{ sale.title }}</h1>
        <div class="animate-in animate-in--delay-2 mb-6"><span class="badge badge--{{ sale.status }}">{{ sale.get_status_display }}</span></div>

        {% if not sale.is_ended %}
        <div class="countdown animate-in animate-in--delay-3" id="countdown"
             data-target-time="{% if sale.is_upcoming %}{{ sale.start_at|date:'c' }}{% else %}{{ sale.end_at|date:'c' }}{% endif %}"
             data-sale-status="{{ sale.status }}">
            <div class="countdown__unit"><div class="countdown__number" id="cd-days">--</div><span class="countdown__label">Days</span></div>
            <div class="countdown__unit"><div class="countdown__number" id="cd-hours">--</div><span class="countdown__label">Hours</span></div>
            <div class="countdown__unit"><div class="countdown__number" id="cd-minutes">--</div><span class="countdown__label">Mins</span></div>
            <div class="countdown__unit"><div class="countdown__number" id="cd-seconds">--</div><span class="countdown__label">Secs</span></div>
        </div>
        <p class="text-sm text-muted mt-4">{% if sale.is_upcoming %}Sale starts in{% else %}Sale ends in{% endif %}</p>
        {% endif %}
    </div>
</section>

<section style="padding: var(--space-8) 0;">
    <div class="container">
        <div class="product-grid">
            {% for item in items %}
            <div class="card product-card reveal clickable-card" data-sale-item-id="{{ item.id }}">
                <div class="product-card__image-wrapper" onclick="openProductDetail('{{ item.id }}')">
                    {% if item.product.primary_image %}<img src="{{ item.product.primary_image.image.url }}" alt="{{ item.product.name }}" class="product-card__image" loading="lazy">
                    {% else %}<div style="width:100%;height:200px;background:var(--color-border-light);display:flex;align-items:center;justify-content:center;color:var(--color-text-muted);">No image</div>{% endif %}
                    {% if item.discount_percent %}<span class="product-card__badge badge badge--live">-{{ item.discount_percent|floatformat:0 }}%</span>{% endif %}
                </div>
                <div class="product-card__body" onclick="openProductDetail('{{ item.id }}')">
                    <h3 class="product-card__name">{{ item.product.name }}</h3>
                    <div><span class="product-card__price">GHS {{ item.price|floatformat:2 }}</span>{% if item.discount_percent %}<span class="product-card__original-price">GHS {{ item.original_price|floatformat:2 }}</span>{% endif %}</div>
                    {% if not item.is_sold_out %}
                    <p class="product-card__stock">{{ item.stock_remaining }} left of {{ item.stock_total }}</p>
                    <div class="product-card__stock-bar"><div class="product-card__stock-fill {% if item.stock_percentage < 20 %}product-card__stock-fill--critical{% elif item.stock_percentage < 50 %}product-card__stock-fill--low{% endif %}" style="width:{{ item.stock_percentage }}%"></div></div>
                    {% else %}<p class="product-card__stock text-error" style="font-weight:600;">Sold Out</p>{% endif %}
                </div>
                {% if sale.is_live and not item.is_sold_out %}
                <div class="product-card__actions flex gap-2">
                    <button class="btn btn--secondary btn--sm" style="flex:1;" onclick="openProductDetail('{{ item.id }}')">View Details</button>
                    <button class="btn btn--primary btn--sm" style="flex:1;" onclick="addToCart('{{ item.id }}','{{ item.product.name|escapejs }}',{{ item.price }},'{% if item.product.primary_image %}{{ item.product.primary_image.image.url }}{% endif %}',{{ item.stock_remaining }})">Add to Cart</button>
                </div>
                {% elif sale.is_upcoming %}
                <div class="product-card__actions flex gap-2">
                    <button class="btn btn--secondary btn--sm" style="flex:1;" onclick="openProductDetail('{{ item.id }}')">View Details</button>
                    <button class="btn btn--secondary btn--sm" style="flex:1;" disabled>Upcoming</button>
                </div>
                {% else %}
                <div class="product-card__actions">
                    <button class="btn btn--secondary btn--sm btn--block" onclick="openProductDetail('{{ item.id }}')">View Details</button>
                </div>
                {% endif %}
            </div>

            <!-- Hidden Product Detail Template Data -->
            <script id="product-detail-data-{{ item.id }}" type="application/json">
            {
                "id": "{{ item.id }}",
                "name": "{{ item.product.name|escapejs }}",
                "description": "{{ item.product.description|escapejs }}",
                "price": "{{ item.price|floatformat:2 }}",
                "original_price": "{% if item.discount_percent %}{{ item.original_price|floatformat:2 }}{% endif %}",
                "discount_percent": "{% if item.discount_percent %}{{ item.discount_percent|floatformat:0 }}{% endif %}",
                "stock_remaining": {{ item.stock_remaining }},
                "stock_total": {{ item.stock_total }},
                "stock_percentage": {{ item.stock_percentage }},
                "is_sold_out": {% if item.is_sold_out %}true{% else %}false{% endif %},
                "image_url": "{% if item.product.primary_image %}{{ item.product.primary_image.image.url }}{% endif %}",
                "images": [{% for img in item.product.images.all %}"{{ img.image.url }}"{% if not forloop.last %},{% endif %}{% endfor %}],
                "video_url": "{% if item.product.video %}{{ item.product.video.url }}{% endif %}"
            }
            </script>
            {% empty %}
            <div class="empty-state" style="grid-column:1/-1;"><h3 class="empty-state__title">No products yet</h3><p class="empty-state__desc">The seller has not added products to this sale yet.</p></div>
            {% endfor %}
        </div>
    </div>
</section>

<!-- Product Details Modal -->
<div class="modal-overlay" id="productDetailModal">
    <div class="modal" style="max-width:640px;">
        <div class="modal__header">
            <h3 class="modal__title" id="pdTitle">Product Details</h3>
            <button class="modal__close" onclick="closeProductDetail()">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
            </button>
        </div>
        <div id="pdContent">
            <div id="pdMediaContainer" class="mb-4">
                <img id="pdImage" src="" alt="" style="width:100%;max-height:320px;object-fit:cover;border-radius:var(--radius-md);" class="hidden">
                <video id="pdVideo" controls style="width:100%;max-height:320px;border-radius:var(--radius-md);" preload="metadata" class="hidden">
                    <source id="pdVideoSource" src="">
                    Your browser does not support HTML5 video player.
                </video>
                <div id="pdMediaThumbs" class="pd-media-gallery"></div>
            </div>

            <!-- Price & Stock -->
            <div class="flex justify-between items-center mb-4">
                <div>
                    <span id="pdPrice" style="font-size:var(--font-size-2xl);font-weight:800;color:var(--color-primary);"></span>
                    <span id="pdOriginalPrice" style="font-size:var(--font-size-base);color:var(--color-text-muted);text-decoration:line-through;margin-left:8px;"></span>
                    <span id="pdBadge" class="badge badge--live hidden" style="margin-left:8px;"></span>
                </div>
                <div class="text-right">
                    <span id="pdStockText" class="text-sm font-semibold"></span>
                </div>
            </div>

            <div class="product-card__stock-bar mb-6"><div id="pdStockFill" class="product-card__stock-fill" style="width:0%"></div></div>

            <!-- Description -->
            <div class="mb-6">
                <h4 style="font-size:var(--font-size-sm);font-weight:700;color:var(--color-text-muted);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:var(--space-2);">Description</h4>
                <p id="pdDescription" class="text-secondary text-sm" style="white-space:pre-line;line-height:1.6;"></p>
            </div>

            <!-- Add to Cart Controls -->
            {% if sale.is_live %}
            <div id="pdCartActions" class="flex gap-4 items-center">
                <div class="cart-item__quantity" style="margin-top:0;">
                    <button class="cart-item__qty-btn" onclick="adjustPdQty(-1)">-</button>
                    <span id="pdQty" class="text-sm font-semibold" style="padding:0 8px;">1</span>
                    <button class="cart-item__qty-btn" onclick="adjustPdQty(1)">+</button>
                </div>
                <button id="pdAddToCartBtn" class="btn btn--primary btn--block btn--lg" style="flex:1;">Add to Cart</button>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Cart Drawer -->
<div class="cart-drawer" id="cartDrawer">
    <div class="cart-drawer__header"><h3 style="font-weight:700;">Your Cart</h3><button class="modal__close" onclick="toggleCart()"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg></button></div>
    <div class="cart-drawer__body" id="cartItems"><div class="empty-state" id="cartEmpty"><p class="text-sm text-muted">Your cart is empty</p></div></div>
    <div class="cart-drawer__footer">
        <div class="flex justify-between items-center mb-4"><strong>Total</strong><strong id="cartTotal" style="font-size:var(--font-size-xl);color:var(--color-primary);">GHS 0.00</strong></div>
        <button class="btn btn--primary btn--block" id="checkoutBtn" onclick="goToCheckout()" disabled>Checkout</button>
    </div>
</div>
<div class="sidebar-overlay" id="cartOverlay" onclick="toggleCart()"></div>

{% if sale.is_live %}
<div class="cart-fab" id="cartFab" style="display:none;"><button class="cart-fab__btn" onclick="toggleCart()"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"/></svg><span class="cart-fab__badge" id="cartBadge">0</span></button></div>
{% endif %}

<!-- Checkout Modal -->
<div class="modal-overlay" id="checkoutModal">
    <div class="modal">
        <div class="modal__header"><h3 class="modal__title">Guest Checkout</h3><button class="modal__close" onclick="closeCheckout()"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg></button></div>
        <form id="checkoutForm" onsubmit="submitCheckout(event)">
            <div class="form-group"><label class="form-label">Full Name</label><input type="text" name="buyer_name" class="form-input" required placeholder="Your full name"></div>
            <div class="grid grid--2">
                <div class="form-group">
                    <label class="form-label">Phone Number</label>
                    <div class="phone-input-group">
                        <span class="phone-prefix">+233</span>
                        <input type="tel" name="buyer_phone" class="form-input" required placeholder="24 123 4567" maxlength="9" oninput="formatGhanaPhoneInput(this)">
                    </div>
                </div>
                <div class="form-group"><label class="form-label">Email</label><input type="email" name="buyer_email" class="form-input" required placeholder="you@email.com"></div>
            </div>

            {% if delivery_options %}
            <div class="form-group">
                <label class="form-label">Select Delivery Location / Option</label>
                <div class="flex flex-col gap-2 mb-2">
                    {% for opt in delivery_options %}
                    <label class="card card--flat" style="cursor:pointer;padding:var(--space-3);margin-bottom:0;">
                        <div class="flex items-center gap-2">
                            <input type="radio" name="delivery_option_id" value="{{ opt.id }}" data-fee="{{ opt.fee }}" {% if forloop.first %}checked{% endif %} onchange="updateCheckoutTotal()" style="accent-color:var(--color-primary);">
                            <div style="flex:1;">
                                <div class="flex justify-between items-center">
                                    <strong class="text-sm">{{ opt.name }}</strong>
                                    <span class="text-sm font-semibold" style="color:var(--color-primary);">
                                        {% if opt.fee == 0 %}Free (GHS 0.00){% else %}+ GHS {{ opt.fee|floatformat:2 }}{% endif %}
                                    </span>
                                </div>
                                {% if opt.description %}<p class="text-xs text-muted mt-1">{{ opt.description }}</p>{% endif %}
                            </div>
                        </div>
                    </label>
                    {% endfor %}
                </div>
            </div>
            {% endif %}

            <div class="form-group">
                <label class="form-label">Delivery Address / Landmark Notes</label>
                <textarea name="delivery_address" class="form-textarea" rows="2" placeholder="House no, street, landmark, area notes..."></textarea>
            </div>

            <div id="checkoutError" class="alert alert--error hidden"></div>
            <div class="flex justify-between items-center mb-4">
                <span class="text-secondary">Grand Total</span>
                <strong id="checkoutTotal" style="font-size:var(--font-size-xl);color:var(--color-primary);"></strong>
            </div>
            <button type="submit" class="btn btn--primary btn--block btn--lg" id="submitCheckoutBtn">Pay Now</button>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'js/countdown.js' %}"></script>
<script src="{% static 'js/cart.js' %}"></script>
<script>
const SALE_SLUG='{{ sale.slug }}', CSRF_TOKEN='{{ csrf_token }}';
{% if not sale.is_ended %}initCountdown();{% endif %}
initCart(SALE_SLUG);

let currentPdData = null;
let currentPdQty = 1;

function openProductDetail(itemId) {
    const dataEl = document.getElementById('product-detail-data-' + itemId);
    if (!dataEl) return;

    currentPdData = JSON.parse(dataEl.textContent);
    currentPdQty = 1;

    document.getElementById('pdTitle').textContent = currentPdData.name;
    document.getElementById('pdDescription').textContent = currentPdData.description || 'No description available.';
    document.getElementById('pdPrice').textContent = 'GHS ' + currentPdData.price;

    if (currentPdData.original_price) {
        document.getElementById('pdOriginalPrice').textContent = 'GHS ' + currentPdData.original_price;
        document.getElementById('pdBadge').textContent = '-' + currentPdData.discount_percent + '%';
        document.getElementById('pdBadge').classList.remove('hidden');
    } else {
        document.getElementById('pdOriginalPrice').textContent = '';
        document.getElementById('pdBadge').classList.add('hidden');
    }

    const imgEl = document.getElementById('pdImage');
    const videoEl = document.getElementById('pdVideo');
    const videoSrcEl = document.getElementById('pdVideoSource');
    const thumbsContainer = document.getElementById('pdMediaThumbs');
    thumbsContainer.innerHTML = '';

    const showMedia = (type, url, thumbEl) => {
        Array.from(thumbsContainer.children).forEach(child => child.classList.remove('active'));
        if (thumbEl) thumbEl.classList.add('active');

        if (type === 'video') {
            imgEl.classList.add('hidden');
            videoSrcEl.src = url;
            videoEl.load();
            videoEl.classList.remove('hidden');
        } else {
            videoEl.classList.add('hidden');
            videoEl.pause();
            imgEl.src = url;
            imgEl.classList.remove('hidden');
        }
    };

    let firstMediaShown = false;

    if (currentPdData.video_url) {
        const thumb = document.createElement('div');
        thumb.className = 'pd-video-thumb' + (!firstMediaShown ? ' active' : '');
        thumb.textContent = 'VIDEO';
        thumb.onclick = () => showMedia('video', currentPdData.video_url, thumb);
        thumbsContainer.appendChild(thumb);
        
        if (!firstMediaShown) {
            showMedia('video', currentPdData.video_url, thumb);
            firstMediaShown = true;
        }
    }

    if (currentPdData.images && currentPdData.images.length > 0) {
        currentPdData.images.forEach((imgUrl) => {
            const thumb = document.createElement('img');
            thumb.src = imgUrl;
            thumb.className = 'pd-media-thumb' + (!firstMediaShown ? ' active' : '');
            thumb.onclick = () => showMedia('image', imgUrl, thumb);
            thumbsContainer.appendChild(thumb);

            if (!firstMediaShown) {
                showMedia('image', imgUrl, thumb);
                firstMediaShown = true;
            }
        });
    } else if (currentPdData.image_url && !firstMediaShown) {
        // Fallback if images array is empty but primary image exists
        showMedia('image', currentPdData.image_url, null);
        firstMediaShown = true;
    }

    if (!firstMediaShown) {
        videoEl.classList.add('hidden');
        imgEl.classList.add('hidden');
    }

    const stockText = document.getElementById('pdStockText');
    const stockFill = document.getElementById('pdStockFill');

    if (currentPdData.is_sold_out) {
        stockText.textContent = 'Sold Out';
        stockText.className = 'text-sm font-semibold text-error';
        stockFill.style.width = '0%';
        if (document.getElementById('pdCartActions')) {
            document.getElementById('pdCartActions').style.display = 'none';
        }
    } else {
        stockText.textContent = currentPdData.stock_remaining + ' left of ' + currentPdData.stock_total;
        stockText.className = 'text-sm font-semibold';
        stockFill.style.width = currentPdData.stock_percentage + '%';
        if (document.getElementById('pdCartActions')) {
            document.getElementById('pdCartActions').style.display = 'flex';
        }
    }

    document.getElementById('pdQty').textContent = currentPdQty;

    const addBtn = document.getElementById('pdAddToCartBtn');
    if (addBtn) {
        addBtn.onclick = function() {
            for (let i = 0; i < currentPdQty; i++) {
                addToCart(currentPdData.id, currentPdData.name, parseFloat(currentPdData.price), currentPdData.image_url, currentPdData.stock_remaining);
            }
            closeProductDetail();
        };
    }

    document.getElementById('productDetailModal').classList.add('is-open');
    document.body.style.overflow = 'hidden';
}

function closeProductDetail() {
    const videoEl = document.getElementById('pdVideo');
    if (videoEl) videoEl.pause();
    document.getElementById('productDetailModal').classList.remove('is-open');
    document.body.style.overflow = '';
}

function adjustPdQty(delta) {
    if (!currentPdData) return;
    currentPdQty += delta;
    if (currentPdQty < 1) currentPdQty = 1;
    if (currentPdQty > currentPdData.stock_remaining) currentPdQty = currentPdData.stock_remaining;
    document.getElementById('pdQty').textContent = currentPdQty;
}
</script>
{% endblock %}
