{% extends 'core/base.html' %}
{% load currency_filters %}
{% load static %}

{% block title %}{{ product.name }} — SwiftPOS{% endblock %}
{% block topbar_title %}Product Detail{% endblock %}

{% block extra_css %}
<style>
/* ── Product Detail Layout ───────────────────────── */

/* Image card — large, dominant */
.pd-img-card {
    border-radius: 16px;
    overflow: hidden;
    background: #f8fafc;
    border: 1px solid #e8ecf0;
    aspect-ratio: 1 / 1;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}
.pd-img-card img {
    width: 100%; height: 100%;
    object-fit: cover;
}
.pd-img-placeholder {
    text-align: center;
    color: #cbd5e1;
    padding: 2rem;
}
.pd-img-placeholder i { font-size: 4rem; display: block; margin-bottom: .75rem; }
.pd-img-placeholder span { font-size: .8rem; color: #94a3b8; }

/* Status chip absolute on image */
.pd-status-chip {
    position: absolute;
    top: 12px; right: 12px;
    font-size: .65rem;
    font-weight: 700;
    padding: .3em .7em;
    border-radius: 50px;
    border: 1.5px solid;
    backdrop-filter: blur(4px);
    letter-spacing: .04em;
}
.pd-status-chip.in  { background:rgba(220,252,231,.9); color:#15803d; border-color:#86efac; }
.pd-status-chip.low { background:rgba(255,251,235,.9); color:#b45309; border-color:#fde68a; }
.pd-status-chip.out { background:rgba(254,226,226,.9); color:#b91c1c; border-color:#fca5a5; }
.pd-status-chip.hid { background:rgba(241,245,249,.9); color:#64748b; border-color:#cbd5e1; }

/* Info card grid */
.pd-info-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0;
}
.pd-info-cell {
    padding: .9rem 1.1rem;
    border-right: 1px solid #f1f5f9;
    border-bottom: 1px solid #f1f5f9;
}
.pd-info-cell:nth-child(3n) { border-right: none; }
/* remove bottom border from last row */
.pd-info-cell:nth-last-child(-n+3) { border-bottom: none; }

.pd-info-label {
    font-size: .62rem;
    font-weight: 700;
    letter-spacing: .06em;
    text-transform: uppercase;
    color: #94a3b8;
    margin-bottom: .2rem;
}
.pd-info-value {
    font-size: .88rem;
    font-weight: 600;
    color: #1e293b;
    line-height: 1.3;
}
.pd-info-value.sell { font-size: 1.15rem; font-weight: 900; color: #059669; }
.pd-info-value.cost { font-size: 1rem;   font-weight: 800; color: #dc2626; }

/* Stock number display */
.pd-stock-hero {
    display: flex;
    align-items: flex-end;
    gap: .5rem;
    padding: 1.25rem 1.25rem .5rem;
}
.pd-stock-num {
    font-size: 3rem;
    font-weight: 900;
    line-height: 1;
    color: #1e293b;
}
.pd-stock-num.low { color: #d97706; }
.pd-stock-num.out { color: #dc2626; }
.pd-stock-sub {
    font-size: .72rem;
    color: #94a3b8;
    padding-bottom: .4rem;
    font-weight: 500;
}

/* Branch rows */
.pd-branch-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: .55rem 1.25rem;
    border-top: 1px solid #f1f5f9;
    font-size: .82rem;
}

/* Section card */
.pd-section {
    background: #fff;
    border: 1px solid #e8ecf0;
    border-radius: 14px;
    overflow: hidden;
    margin-bottom: 1rem;
}
.pd-section-head {
    padding: .75rem 1.25rem;
    border-bottom: 1px solid #f1f5f9;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: .75rem;
}
.pd-section-title {
    font-size: .8rem;
    font-weight: 700;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: .4rem;
    margin: 0;
}
.pd-section-title i { color: var(--sp-primary, #4f46e5); font-size: .75rem; }

/* Barcode box */
.pd-barcode-box {
    background: #fff;
    border: 1px solid #e8ecf0;
    border-radius: 10px;
    padding: 1rem;
    display: inline-block;
}

@media (max-width: 575.98px) {
    .pd-info-grid { grid-template-columns: repeat(2, 1fr); }
    .pd-info-cell:nth-child(3n) { border-right: 1px solid #f1f5f9; }
    .pd-info-cell:nth-child(2n) { border-right: none; }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid px-0">

    <!-- Toast Messages -->
    <div class="swiftpos-toast-container">
        {% if messages %}{% for message in messages %}
            <div class="swiftpos-toast swiftpos-toast-{{ message.tags }}">
                <div class="toast-icon">
                    {% if message.tags == 'success' %}<i class="fas fa-check-circle"></i>
                    {% elif message.tags == 'error' or message.tags == 'danger' %}<i class="fas fa-exclamation-circle"></i>
                    {% elif message.tags == 'warning' %}<i class="fas fa-exclamation-triangle"></i>
                    {% else %}<i class="fas fa-info-circle"></i>{% endif %}
                </div>
                <div class="toast-text">{{ message }}</div>
            </div>
        {% endfor %}{% endif %}
    </div>

    <!-- Standard page header — no special card -->
    <div class="sp-page-header">
        <div>
            <h1 class="sp-page-title"><i class="fas fa-box"></i>{{ product.name }}</h1>
            <p class="sp-page-subtitle">
                SKU: {{ product.sku }}{% if product.barcode %} &nbsp;·&nbsp; Barcode: {{ product.barcode }}{% endif %}
                &nbsp;·&nbsp; {{ product.category.name|default:"Uncategorized" }}
            </p>
        </div>
        <div class="sp-page-actions">
            <a href="{% url 'inventory:product_list' %}" class="btn btn-sm btn-outline-secondary"><i class="fas fa-list me-1"></i>Products</a>
            <a href="{% url 'inventory:restock_product' product.id %}" class="btn btn-sm btn-outline-success"><i class="fas fa-plus-circle me-1"></i>Restock</a>
            <a href="{% url 'inventory:reduce_stock' product.id %}" class="btn btn-sm btn-outline-danger"><i class="fas fa-minus-circle me-1"></i>Reduce</a>
            {% if request.company.plan.feature_product_variants %}
            <a href="{% url 'inventory:product_variants' product.id %}" class="btn btn-sm btn-outline-info"><i class="fas fa-swatchbook me-1"></i>Variants</a>
            {% endif %}
            <a href="{% url 'inventory:edit_product' product.id %}" class="btn btn-sm btn-primary fw-bold"><i class="fas fa-pen me-1"></i>Edit</a>
        </div>
    </div>

    <!-- ══ ROW 1: Image  +  Pricing/Details  +  Stock ══ -->
    <div class="row g-3 mb-1">

        <!-- Image — square, prominent -->
        <div class="col-sm-6 col-lg-3">
            <div class="pd-img-card">
                {% if product.is_hidden %}
                    <span class="pd-status-chip hid"><i class="fas fa-eye-slash me-1"></i>Hidden</span>
                {% elif product.stock_status == 'in_stock' %}
                    <span class="pd-status-chip in"><i class="fas fa-circle me-1"></i>In Stock</span>
                {% elif product.stock_status == 'low_stock' %}
                    <span class="pd-status-chip low"><i class="fas fa-exclamation-circle me-1"></i>Low Stock</span>
                {% else %}
                    <span class="pd-status-chip out"><i class="fas fa-times-circle me-1"></i>Out of Stock</span>
                {% endif %}

                {% if product.image %}
                    <img src="{{ product.image.url }}" alt="{{ product.name }}">
                {% else %}
                    <div class="pd-img-placeholder">
                        <i class="fas fa-box-open"></i>
                        <span>No image</span>
                    </div>
                {% endif %}
            </div>
            <p class="text-muted small text-center mt-2 mb-0">
                <a href="{% url 'inventory:edit_product' product.id %}">Update image</a>
            </p>
        </div>

        <!-- Pricing & Details -->
        <div class="col-sm-6 col-lg-5">
            <div class="pd-section h-100">
                <div class="pd-section-head">
                    <h2 class="pd-section-title"><i class="fas fa-circle-info"></i>Product Details</h2>
                </div>
                <div class="pd-info-grid">
                    <div class="pd-info-cell" style="grid-column: span 1;">
                        <div class="pd-info-label">Selling Price</div>
                        <div class="pd-info-value sell">{% money product.price %}</div>
                    </div>
                    <div class="pd-info-cell" style="grid-column: span 1;">
                        <div class="pd-info-label">Cost Price</div>
                        <div class="pd-info-value cost">{% money product.cost_price %}</div>
                    </div>
                    <div class="pd-info-cell">
                        <div class="pd-info-label">Category</div>
                        <div class="pd-info-value">
                            <span class="sp-badge sp-badge-purple">{{ product.category.name|default:"Uncategorized" }}</span>
                        </div>
                    </div>
                    <div class="pd-info-cell">
                        <div class="pd-info-label">Supplier</div>
                        <div class="pd-info-value">{{ product.supplier|default:"—" }}</div>
                    </div>
                    <div class="pd-info-cell">
                        <div class="pd-info-label">SKU</div>
                        <div class="pd-info-value"><code style="font-size:.78rem;background:#f1f5f9;padding:.1rem .35rem;border-radius:5px;">{{ product.sku }}</code></div>
                    </div>
                    {% if product.barcode %}
                    <div class="pd-info-cell">
                        <div class="pd-info-label">Barcode</div>
                        <div class="pd-info-value"><code style="font-size:.78rem;background:#f1f5f9;padding:.1rem .35rem;border-radius:5px;">{{ product.barcode }}</code></div>
                    </div>
                    {% endif %}
                    <div class="pd-info-cell">
                        <div class="pd-info-label">Date Added</div>
                        <div class="pd-info-value">{{ product.created_at|date:"M j, Y" }}</div>
                    </div>
                    {% if product.description %}
                    <div class="pd-info-cell" style="grid-column: 1 / -1; border-right: none;">
                        <div class="pd-info-label">Description</div>
                        <div class="pd-info-value" style="font-weight:400; color:#475569; font-size:.82rem; white-space: normal; line-height:1.5;">{{ product.description }}</div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Stock + Branch Allocations -->
        <div class="col-sm-12 col-lg-4">
            <div class="pd-section h-100">
                <div class="pd-section-head">
                    <h2 class="pd-section-title">
                        <i class="fas fa-warehouse"></i>Stock
                        {% if has_variants %}<span class="sp-badge sp-badge-info" style="font-size:.6rem;">Variant-managed</span>{% endif %}
                    </h2>
                </div>

                <!-- Big stock number -->
                <div class="pd-stock-hero">
                    {% if has_variants %}
                        {% if variant_stock_total <= 0 %}
                            <span class="pd-stock-num out">{{ variant_stock_total }}</span>
                        {% elif variant_stock_total <= product.minimum_stock %}
                            <span class="pd-stock-num low">{{ variant_stock_total }}</span>
                        {% else %}
                            <span class="pd-stock-num">{{ variant_stock_total }}</span>
                        {% endif %}
                    {% else %}
                        {% if product.stock_status == 'out_of_stock' %}
                            <span class="pd-stock-num out">{{ product.stock_quantity }}</span>
                        {% elif product.stock_status == 'low_stock' %}
                            <span class="pd-stock-num low">{{ product.stock_quantity }}</span>
                        {% else %}
                            <span class="pd-stock-num">{{ product.stock_quantity }}</span>
                        {% endif %}
                    {% endif %}
                    <span class="pd-stock-sub">units in stock</span>
                </div>

                <div class="pd-branch-row" style="background:#fafbfc;">
                    <span class="small text-muted">Minimum threshold</span>
                    <span class="fw-bold small">{{ product.minimum_stock }} units</span>
                </div>

                <!-- Branch breakdown -->
                {% if has_variants and variant_branch_stocks %}
                    {% for vbs in variant_branch_stocks %}
                    <div class="pd-branch-row">
                        <span class="fw-semibold small">{{ vbs.branch.name }}</span>
                        <span class="sp-badge {% if vbs.quantity > 0 %}sp-badge-success{% else %}sp-badge-neutral{% endif %}">{{ vbs.quantity }}</span>
                    </div>
                    {% endfor %}
                {% elif not has_variants and branch_stocks %}
                    {% for bs in branch_stocks %}
                    <div class="pd-branch-row">
                        <span class="fw-semibold small">{{ bs.branch.name|default:"Main Branch" }}</span>
                        <span class="sp-badge {% if bs.quantity > 0 %}sp-badge-success{% else %}sp-badge-danger{% endif %}">{{ bs.quantity }}</span>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="pd-branch-row">
                        <span class="small text-muted">No branch allocations set yet.</span>
                    </div>
                {% endif %}

                {% if has_variants and variant_branch_stocks %}
                <div class="pd-branch-row" style="background:#f8fafc;">
                    <span class="small text-muted fw-semibold">Global total (all variants)</span>
                    <span class="sp-badge sp-badge-info">{{ variant_stock_total }}</span>
                </div>
                {% endif %}

                {% if has_variants %}
                <div style="padding:.75rem 1.25rem;">
                    <div class="alert alert-info py-2 px-3 mb-0 small">
                        <i class="fas fa-info-circle me-1"></i> Stock is managed per variant. Total = sum of all variant stocks.
                    </div>
                </div>
                {% endif %}
            </div>
        </div>

    </div><!-- /row 1 -->

    <!-- ══ ROW 2: Variants (full width) ══════════════════ -->
    {% if request.company.plan.feature_product_variants %}
    <div class="pd-section" id="product_variants_section">
        <div class="pd-section-head">
            <h2 class="pd-section-title"><i class="fas fa-layer-group"></i>Product Variants</h2>
            <a href="{% url 'inventory:product_variants' product.id %}" class="btn btn-sm btn-outline-primary d-flex align-items-center gap-1">
                <i class="fas fa-cog"></i> Manage Variants
            </a>
        </div>
        <div class="sp-table-container">
            <table class="table table-sm table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Attributes</th>
                        <th>SKU</th>
                        <th>Price</th>
                        <th>Stock</th>
                    </tr>
                </thead>
                <tbody>
                    {% for variant in variants %}
                    <tr>
                        <td>
                            <div class="d-flex flex-wrap gap-1">
                            {% for key, val in variant.attribute_values.items %}
                                <span class="sp-badge sp-badge-neutral">{{ key|title }}: {{ val }}</span>
                            {% empty %}
                                <span class="text-muted small">Standard</span>
                            {% endfor %}
                            </div>
                        </td>
                        <td><code class="small">{{ variant.sku }}</code></td>
                        <td><span class="fw-bold small" style="color:#059669;">{% money variant.effective_price %}</span></td>
                        <td>
                            {% if variant.real_stock <= 0 %}
                                <span class="sp-badge sp-badge-danger">Out of Stock</span>
                            {% elif variant.real_stock <= variant.minimum_stock %}
                                <span class="sp-badge sp-badge-warning">{{ variant.real_stock }} (Low)</span>
                            {% else %}
                                <span class="sp-badge sp-badge-success">{{ variant.real_stock }}</span>
                            {% endif %}
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="4" class="text-center py-5 text-muted small">
                            <i class="fas fa-swatchbook fa-2x opacity-25 d-block mb-2"></i>
                            No variants configured.
                            <a href="{% url 'inventory:product_variants' product.id %}" class="btn btn-sm btn-primary ms-2 mt-1">Add First Variant</a>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    {% endif %}

    <!-- ══ ROW 3: Barcode ════════════════════════════════ -->
    <div class="pd-section">
        <div class="pd-section-head">
            <h2 class="pd-section-title"><i class="fas fa-barcode"></i>Product Barcode</h2>
            {% if product.barcode %}
            <span class="sp-badge sp-badge-success"><i class="fas fa-check me-1"></i>{{ product.barcode }}</span>
            {% else %}
            <span class="sp-badge sp-badge-neutral">No barcode set</span>
            {% endif %}
        </div>
        <div style="padding: 1.25rem; text-align: center;">
            {% if product.barcode %}
                <div class="pd-barcode-box mb-3">
                    <canvas id="productBarcodeCanvas" style="max-width:280px;width:100%;display:block;"></canvas>
                </div>
                <div class="d-flex justify-content-center gap-2">
                    <button type="button" class="btn btn-outline-primary btn-sm" id="downloadBarcodeBtn">
                        <i class="fas fa-download me-1"></i>Save Image
                    </button>
                    <a href="{% url 'inventory:print_product_barcode' product.id %}" target="_blank" class="btn btn-primary btn-sm fw-bold">
                        <i class="fas fa-print me-1"></i>Print Label
                    </a>
                </div>
                <p class="text-muted small mt-2 mb-0">Includes barcode and product name for easy scanning.</p>
            {% else %}
                <div class="py-4 text-muted">
                    <i class="fas fa-barcode fa-3x opacity-25 d-block mb-3"></i>
                    <p class="small mb-0">No barcode set. <a href="{% url 'inventory:edit_product' product.id %}">Edit this product</a> to add one.</p>
                </div>
            {% endif %}
        </div>
    </div>

</div><!-- /container -->

{% block extra_js %}
{{ block.super|default:"" }}
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
    const barcodeValue = "{{ product.barcode|default_if_none:''|escapejs }}";
    const productName  = "{{ product.name|escapejs }}";
    const canvas       = document.getElementById("productBarcodeCanvas");
    const downloadBtn  = document.getElementById("downloadBarcodeBtn");
    if (!canvas || !barcodeValue) return;
    try {
        JsBarcode(canvas, barcodeValue, {
            format:"CODE128", displayValue:true, text:productName,
            font:"Poppins,Arial,sans-serif", fontSize:14, textMargin:4,
            margin:10, lineColor:"#111827", width:2, height:60
        });
    } catch(e){ console.error("Barcode error:", e); }
    if (downloadBtn) {
        downloadBtn.addEventListener("click", function(){
            try {
                const safeName = (productName||"product").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");
                const a = document.createElement("a");
                a.href = canvas.toDataURL("image/png");
                a.download = safeName + "_barcode.png";
                document.body.appendChild(a); a.click(); document.body.removeChild(a);
            } catch(e){ alert("Cannot save image in this browser."); }
        });
    }
});
</script>
{% endblock %}
{% endblock %}