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

{% block title %}Smart POS V2 — SwiftPOS{% endblock %}
{% block topbar_title %}Smart POS{% endblock %}

{% block extra_css %}
<style>
/* ── Grid POS Layout ─────────────────────────────────── */
:root {
    --grid-cols: repeat(auto-fill, minmax(160px, 1fr));
}
.gpos-wrap { display: flex; height: calc(100vh - 130px); gap: 0; }
.gpos-left { flex: 1 1 60%; overflow: hidden; display: flex; flex-direction: column; padding: 1rem; gap: 0.75rem; }
.gpos-right {
    width: 360px; flex-shrink: 0;
    background: var(--sp-surface, #fff);
    border-left: 1px solid var(--sp-border, #e5e7eb);
    display: flex; flex-direction: column;
    /* Must NOT be overflow:hidden — let inner .gpos-cart-items scroll */
    overflow: visible;
    /* Constrain height so the flex child can actually scroll */
    height: 100%;
    min-height: 0;
}

/* Mobile: stack */
@media (max-width: 991px) {
    .gpos-wrap { flex-direction: column; height: auto; }
    .gpos-right { width: 100%; border-left: none; border-top: 1px solid var(--sp-border, #e5e7eb); height: auto; overflow: visible; }
}

/* Search + filter row */
.gpos-search-row { display: flex; gap: 0.5rem; }
.gpos-search-row input { flex: 1; border-radius: 12px; border: 1px solid var(--sp-border,#e5e7eb); padding: 0.55rem 1rem; font-size: 0.875rem; background: var(--sp-surface,#fff); }
.gpos-search-row input:focus { outline: none; border-color: var(--sp-primary,#4f46e5); box-shadow: 0 0 0 3px rgba(79,70,229,0.12); }

/* Category chips */
.gpos-cats { display: flex; gap: 0.5rem; overflow-x: auto; padding-bottom: 0.2rem; flex-shrink: 0; }
.gpos-cats::-webkit-scrollbar { height: 3px; }
.gpos-cat-btn {
    white-space: nowrap; padding: 0.3rem 0.85rem;
    border-radius: 50px; font-size: 0.78rem; font-weight: 600;
    border: 2px solid var(--sp-border,#e5e7eb);
    background: var(--sp-surface,#fff);
    color: var(--sp-text-muted,#6b7280);
    cursor: pointer; transition: all 0.18s;
}
.gpos-cat-btn.active,
.gpos-cat-btn:hover {
    background: var(--sp-primary,#4f46e5);
    border-color: var(--sp-primary,#4f46e5);
    color: #fff;
}

/* Product grid */
.gpos-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr); /* default: 3 cols */
    gap: 0.75rem;
    overflow-y: auto;
    flex: 1;
    padding-right: 4px;
    align-content: start;
}
/* Wider left panel = more columns */
@media (min-width: 1400px) { .gpos-grid { grid-template-columns: repeat(6, 1fr); } }
@media (min-width: 1200px) and (max-width: 1399px) { .gpos-grid { grid-template-columns: repeat(5, 1fr); } }
@media (min-width: 992px)  and (max-width: 1199px) { .gpos-grid { grid-template-columns: repeat(4, 1fr); } }
/* Mobile (full width, no cart panel) */
@media (max-width: 991px)  { .gpos-grid { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 600px)  { .gpos-grid { grid-template-columns: repeat(2, 1fr); } }

/* Product card */
.gpos-card {
    background: var(--sp-surface,#fff);
    border: 1px solid var(--sp-border,#e5e7eb);
    border-radius: 14px;
    padding: 0.6rem;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    flex-direction: column;
    gap: 0.3rem;
    position: relative;
    overflow: visible;   /* allow badge to overflow */
    user-select: none;
    min-height: 180px;   /* guarantee room for all 4 info items */
}
.gpos-card:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,0.1); border-color: var(--sp-primary,#4f46e5); }
.gpos-card:active { transform: scale(0.97); }
.gpos-card.out-of-stock { opacity: 0.45; pointer-events: none; }

/* Fixed-height image — never takes over the whole card */
.gpos-card-img {
    width: 100%;
    height: 75px;        /* fixed — not aspect-ratio */
    object-fit: cover;
    border-radius: 8px;
    background: var(--sp-surface-muted,#f3f4f6);
    flex-shrink: 0;
}
.gpos-card-img-placeholder {
    width: 100%;
    height: 75px;        /* same fixed height */
    border-radius: 8px;
    background: linear-gradient(135deg, var(--sp-surface-muted,#f3f4f6), #e5e7eb);
    display: flex; align-items: center; justify-content: center;
    color: var(--sp-text-muted,#9ca3af); font-size: 1.6rem;
    flex-shrink: 0;
}
/* Always-visible text below image */
.gpos-card-name {
    font-weight: 600;
    font-size: 0.78rem;
    line-height: 1.25;
    color: var(--sp-text,#111827);
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
.gpos-card-price {
    font-weight: 800;
    font-size: 0.88rem;
    color: var(--sp-primary,#4f46e5);
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.gpos-card-stock {
    font-size: 0.68rem;
    color: var(--sp-text-muted,#9ca3af);
    margin-bottom: 0.25rem;  /* breathing room before + btn */
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}

.gpos-add-btn {
    position: absolute; bottom: 0.6rem; right: 0.6rem;
    width: 28px; height: 28px;
    border-radius: 50%; border: none;
    background: var(--sp-primary,#4f46e5); color: #fff;
    font-size: 1rem; display: flex; align-items: center; justify-content: center;
    transition: background 0.15s; line-height: 1;
}
.gpos-add-btn:hover { background: var(--sp-secondary,#7c3aed); }

/* Added animation */
@keyframes gpos-added { 0%{transform:scale(1)} 40%{transform:scale(1.06)} 100%{transform:scale(1)} }
.gpos-card.just-added { animation: gpos-added 0.25s ease; border-color: #22c55e; }

/* Stock badge */
.gpos-stock-badge {
    position: absolute; top: 0.8rem; left: 0.8rem;
    font-size: 0.65rem; font-weight: 700; border-radius: 50px;
    padding: 0.1rem 0.4rem; color: #fff;
    box-shadow: 0 2px 4px rgba(0,0,0,0.15);
}
.gpos-stock-badge.low { background: #f59e0b; }
.gpos-stock-badge.ok { background: #22c55e; }

/* Recent products row */
.gpos-recent-row { display: flex; gap: 0.5rem; overflow-x: auto; padding-bottom: 0.25rem; flex-shrink: 0; }
.gpos-recent-row::-webkit-scrollbar { height: 3px; }
.gpos-recent-chip {
    display: flex; align-items: center; gap: 0.35rem;
    background: var(--sp-surface-muted,#f3f4f6);
    border: 1px solid var(--sp-border,#e5e7eb);
    border-radius: 50px; padding: 0.25rem 0.6rem;
    font-size: 0.72rem; font-weight: 600; white-space: nowrap;
    cursor: pointer; transition: background 0.15s; color: var(--sp-text,#374151);
}
.gpos-recent-chip:hover { background: var(--sp-primary,#4f46e5); color: #fff; border-color: transparent; }

/* ── RIGHT CART PANEL ────────────────────────────────── */
.gpos-cart-header {
    padding: 1rem 1.2rem 0.5rem;
    border-bottom: 1px solid var(--sp-border,#e5e7eb);
    flex-shrink: 0;
}
.gpos-cart-items {
    padding: 0.75rem 1rem;
    display: flex; flex-direction: column; gap: 0.5rem;
    min-height: 80px; 
}
.gpos-cart-items::-webkit-scrollbar { width: 4px; }
.gpos-cart-items::-webkit-scrollbar-track { background: transparent; }
.gpos-cart-items::-webkit-scrollbar-thumb { background: #d1d5db; border-radius: 4px; }

/* Mobile: give cart a max-height so it scrolls instead of growing forever */
@media (max-width: 991px) {
    .gpos-cart-items {
        max-height: 40vh;
        min-height: 80px;
    }
}
.gpos-cart-item {
    display: flex; align-items: center; gap: 0.6rem;
    padding: 0.5rem 0.6rem;
    background: var(--sp-surface-muted,#f9fafb);
    border-radius: 10px; animation: gpos-cart-in 0.2s ease;
}
@keyframes gpos-cart-in {
    from { opacity:0; transform: translateX(-8px); }
    to   { opacity:1; transform: none; }
}
.gpos-ci-name { flex: 1; font-size: 0.82rem; font-weight: 600; }
.gpos-ci-qty {
    display: flex; align-items: center; gap: 0.25rem;
}
.gpos-ci-qty button {
    width: 22px; height: 22px; border-radius: 50%; border: 1px solid var(--sp-border,#e5e7eb);
    background: #fff; font-size: 0.8rem; display: flex; align-items: center; justify-content: center;
    cursor: pointer; padding: 0; color: var(--sp-text,#374151);
}
.gpos-ci-qty span { font-weight: 700; font-size: 0.85rem; min-width: 20px; text-align: center; }
.gpos-ci-price { font-weight: 700; font-size: 0.82rem; color: var(--sp-primary,#4f46e5); white-space: nowrap; min-width: 60px; text-align: right; }
.gpos-ci-del { color: var(--sp-text-muted,#9ca3af); cursor: pointer; font-size: 0.75rem; padding: 0; background: none; border: none; }

/* Sticky total bottom */
.gpos-cart-footer {
    flex-shrink: 0;
    padding: 0.85rem 1.2rem;
    border-top: 1px solid var(--sp-border,#e5e7eb);
    background: var(--sp-surface,#fff);
}
.gpos-total-strip {
    display: flex; justify-content: space-between; align-items: center;
    background: transparent;
    padding: 0.5rem 0; margin-bottom: 0.5rem; color: var(--sp-text,#111827);
    border-top: 1px dashed var(--sp-border,#e5e7eb);
    margin-top: 0.5rem;
}
.gpos-total-strip .label { font-size: 1.1rem; font-weight: 700; }
.gpos-total-strip .amount { font-size: 1.6rem; font-weight: 900; color: var(--sp-primary,#4f46e5); }

/* Mobile sticky bar */
@media (max-width: 991px) {
    .gpos-sticky-bottom {
        position: fixed; bottom: 0; left: 0; right: 0;
        background: var(--sp-surface,#fff);
        border-top: 1px solid var(--sp-border,#e5e7eb);
        padding: 0.7rem 1rem;
        display: flex; align-items: center; justify-content: space-between;
        z-index: 900; box-shadow: 0 -4px 16px rgba(0,0,0,0.08);
    }
    .gpos-sticky-bottom .gpos-sticky-total { font-weight: 800; font-size: 1.1rem; color: var(--sp-primary,#4f46e5); }
    .gpos-sticky-bottom .gpos-sticky-btn {
        background: var(--sp-primary,#4f46e5); color: #fff;
        border: none; border-radius: 12px; padding: 0.55rem 1.2rem;
        font-weight: 700; font-size: 0.875rem; display: flex; align-items: center; gap: 0.4rem;
    }
    .gpos-wrap { padding-bottom: 80px; }
    .gpos-right { display: none; }
}
@media (min-width: 992px) {
    .gpos-sticky-bottom { display: none; }
}

/* Checkout form in cart */
.gpos-checkout { padding: 0 1.2rem 0.75rem; }
.gpos-checkout .form-label { font-size: 0.78rem; font-weight: 600; color: var(--sp-text-muted,#6b7280); margin-bottom: 0.25rem; }
.gpos-checkout .form-control,
.gpos-checkout .form-select { font-size: 0.82rem; border-radius: 10px; padding: 0.45rem 0.7rem; }

/* Offline banner */
#gpos-offline-banner { border-radius: 0; }

/* Loading skeleton */
.gpos-skeleton { background: linear-gradient(90deg,#f0f0f0 25%,#e0e0e0 50%,#f0f0f0 75%); background-size: 200% 100%; animation: shimmer 1.5s infinite; border-radius: 16px; min-height: 200px; }
@keyframes shimmer { 0%{background-position:200% 0} 100%{background-position:-200% 0} }

/* Long press wave */
.gpos-card.long-pressing::after {
    content: ''; position: absolute; border-radius: 50%;
    background: rgba(79,70,229,0.18);
    width: 20px; height: 20px;
    top: 50%; left: 50%; transform: translate(-50%,-50%);
    animation: ripple 0.6s ease-out forwards;
}
@keyframes ripple {
    to { width: 160%; height: 160%; opacity: 0; }
}
</style>
{% endblock %}

{% block content %}
<!-- Post-Sale "What Next?" Modal -->
<!-- Post-Sale "What Next?" Overlay -->
<div id="postSaleOverlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:99999;align-items:center;justify-content:center;padding:1rem;">
  <div style="background:var(--sp-surface,#fff);border-radius:20px;overflow:hidden;width:100%;max-width:380px;box-shadow:0 25px 60px rgba(0,0,0,.4);">
    <div style="background:linear-gradient(135deg,#16a34a,#22c55e);text-align:center;padding:2rem 1.5rem;">
      <div style="font-size:3rem;line-height:1;margin-bottom:.5rem;">&#x2705;</div>
      <h5 style="color:#fff;font-weight:700;margin:0 0 .25rem;">Order Complete!</h5>
      <p id="postSaleOrderNum" style="color:rgba(255,255,255,.8);font-size:.85rem;margin:0;">Sale recorded.</p>
    </div>
    <div style="padding:1.5rem;">
      <p style="text-align:center;color:#6b7280;font-size:.875rem;margin:0 0 1rem;">What would you like to do next?</p>
      <a href="#" id="postSaleNewOrderBtn" class="btn btn-primary w-100 fw-bold mb-2 d-flex align-items-center justify-content-center gap-2" style="border-radius:12px;padding:.85rem;font-size:1rem;">
        <i class="fas fa-plus-circle"></i> New Order
      </a>
      <a href="#" id="postSaleReceiptBtn" class="btn btn-outline-secondary w-100 d-flex align-items-center justify-content-center gap-2" style="border-radius:12px;padding:.85rem;font-size:1rem;">
        <i class="fas fa-receipt"></i> View Receipt
      </a>
    </div>
  </div>
</div>

<!-- Offline banner -->
<div id="gpos-offline-banner" class="alert alert-warning rounded-0 mb-0 d-none">
    <i class="fas fa-wifi-slash me-2"></i>
    Offline mode — showing cached products. Orders will sync when connection returns.
</div>

<div class="gpos-wrap">
    <!-- ═══════ LEFT: Product Grid ═══════ -->
    <div class="gpos-left">

        <!-- Search + refresh -->
        <div class="gpos-search-row">
            <input type="text" id="gpos-search" placeholder="🔍  Search products by name or SKU…" autocomplete="off">
            <button type="button" class="btn btn-sm btn-outline-secondary" id="gpos-refresh-btn" title="Refresh products" style="border-radius:12px;">
                <i class="fas fa-rotate-right"></i>
            </button>
        </div>

        <!-- Category filter chips -->
        <div class="gpos-cats" id="gpos-cats">
            <button type="button" class="gpos-cat-btn active" data-cat="all">All</button>
        </div>

        <!-- Recent / fast-moving products row -->
        <div id="gpos-recent-wrap" style="display:none;">
            <div class="small text-muted mb-1" style="font-weight:600;font-size:0.72rem;text-transform:uppercase;letter-spacing:0.08em;">⚡ Recent</div>
            <div class="gpos-recent-row" id="gpos-recent-row"></div>
        </div>

        <!-- Product grid -->
        <div class="gpos-grid" id="gpos-grid">
            <!-- Skeleton placeholders while loading -->
            <div class="gpos-skeleton"></div>
            <div class="gpos-skeleton"></div>
            <div class="gpos-skeleton"></div>
            <div class="gpos-skeleton"></div>
        </div>

    </div>

    <!-- ═══════ RIGHT: Cart Panel ═══════ -->
    <div class="gpos-right d-flex flex-column">

        <!-- Cart header -->
        <div class="gpos-cart-header d-flex justify-content-between align-items-center">
            <span class="fw-bold d-flex align-items-center gap-2">
                <i class="fas fa-shopping-basket text-primary"></i>
                Cart
                <span class="badge bg-primary rounded-pill" id="gpos-cart-count">0</span>
            </span>
            <button type="button" class="btn btn-sm btn-outline-danger" id="gpos-clear-cart" style="border-radius:10px;font-size:0.75rem;">
                <i class="fas fa-trash me-1"></i>Clear
            </button>
        </div>

        <form method="post" id="pos-form" class="d-flex flex-column flex-grow-1" style="min-height:0;">
            {% csrf_token %}
            <input type="hidden" name="cart_payload" id="cart-payload-field">

            <!-- scrollable wrapper for items + inputs -->
            <div class="flex-grow-1" style="overflow-y: auto; scrollbar-width: thin;">
                <!-- Cart items -->
                <div class="gpos-cart-items" id="gpos-cart-items">
                    <div id="gpos-empty-cart" class="text-center py-5 text-muted">
                        <i class="fas fa-shopping-cart fa-2x opacity-25 d-block mb-2"></i>
                        <small>Tap a product to add it</small>
                    </div>
                </div>

                <!-- Checkout form inputs -->
                <div class="gpos-checkout px-3 py-2">
                    <div id="std-payment-row" class="row gx-2 mb-2">
                        <div class="col-6">
                            <label class="form-label text-truncate mb-1">Payment Method</label>
                            <select class="form-select form-select-sm" name="payment_method">
                                <option value="cash">Cash</option>
                                <option value="transfer">Transfer</option>
                                <option value="pos">POS / Card</option>
                                <option value="mobile_money">Mobile Money</option>
                                <option value="credit">Credit</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="form-label text-truncate mb-1">Payment Status</label>
                            <select class="form-select form-select-sm" name="payment_status" id="gpos-pay-status">
                                <option value="full" selected>Paid in Full</option>
                                <option value="partial">Partial</option>
                                <option value="credit">Credit / Owe</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-2 d-none" id="gpos-amount-paid-group">
                        <label class="form-label">Amount Paid</label>
                        <input type="number" class="form-control" name="amount_paid" placeholder="0.00" step="0.01" min="0">
                    </div>

                    {% include 'pos/_split_payment_panel.html' %}

                    <div class="mb-2">
                        <label class="form-label">Customer <span class="text-muted small">(optional)</span></label>
                        <div class="position-relative">
                            <input type="text" id="gpos-cust-search" class="form-control" placeholder="🔍 Search customer…" autocomplete="off">
                            <div id="gpos-cust-dropdown" class="list-group position-absolute w-100 shadow-sm" style="z-index:9999;max-height:210px;overflow-y:auto;display:none;top:100%;">
                                <button type="button" class="list-group-item list-group-item-action py-1 small" data-name="" data-phone="">
                                    <span class="fw-semibold">Walk-in (no customer)</span>
                                </button>
                                {% for c in customers %}
                                <button type="button" class="list-group-item list-group-item-action py-1 small"
                                        data-name="{{ c.name|escapejs }}"
                                        data-phone="{{ c.phone|default:''|escapejs }}">
                                    <span class="fw-semibold">{{ c.name }}</span>
                                    {% if c.phone %}<span class="text-muted ms-2">{{ c.phone }}</span>{% endif %}
                                </button>
                                {% endfor %}
                            </div>
                        </div>
                        <input type="hidden" name="customer_name" id="gpos-cust-name-val">
                        <input type="hidden" name="customer_phone" id="gpos-cust-phone-val">
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Reference (optional)</label>
                        <input type="text" class="form-control" name="reference_number" placeholder="Transaction reference">
                    </div>

                    <!-- Promo Code -->
                    <div class="mb-2">
                        <label class="form-label">Promo Code</label>
                        <div class="input-group input-group-sm">
                            <span class="input-group-text"><i class="fas fa-tag"></i></span>
                            <input type="text" id="gpos-promo-input" class="form-control" placeholder="Enter code…" style="text-transform:uppercase;">
                            <button class="btn btn-outline-success" type="button" id="gpos-promo-btn">Apply</button>
                        </div>
                        <div id="gpos-promo-msg" class="small mt-1"></div>
                    </div>

                    <!-- Discount row (shown when promo applied) -->
                    <div class="d-flex justify-content-between small text-success mb-1 d-none" id="gpos-discount-row">
                        <span><i class="fas fa-tag me-1"></i>Discount</span>
                        <span>−<span id="gpos-discount-display"></span></span>
                    </div>
                </div>
            </div> <!-- end scrollable wrapper -->

            <div class="gpos-cart-footer">
                <!-- Subtotal / VAT / Total -->
                <div class="d-flex justify-content-between small text-muted mb-1">
                    <span>Subtotal</span>
                    <span><span id="gpos-subtotal">{{ currency_symbol }}0.00</span></span>
                </div>
                {% if vat_rate > 0 %}
                <div class="d-flex justify-content-between small text-muted mb-1">
                    <span>VAT ({{ vat_rate }}%)</span>
                    <span><span id="gpos-vat">{{ currency_symbol }}0.00</span></span>
                </div>
                {% endif %}
                <div class="gpos-total-strip">
                    <div>
                        <div class="label">Total</div>
                        <div class="amount" id="gpos-total">{{ currency_symbol }}0.00</div>
                    </div>
                    <i class="fas fa-receipt fa-lg opacity-75"></i>
                </div>

                <div class="pb-1 mt-2">
                    <button type="submit" class="btn btn-success w-100 fw-bold d-flex align-items-center justify-content-center gap-2" id="gpos-submit-btn" style="border-radius:14px;padding:0.95rem; font-size:1.05rem;" disabled>
                        <i class="fas fa-check-circle fs-5"></i> Complete Order
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Mobile sticky cart total -->
<div class="gpos-sticky-bottom">
    <div>
        <div class="small text-muted">Total</div>
        <div class="gpos-sticky-total" id="gpos-sticky-total">{{ currency_symbol }}0.00</div>
    </div>
    <button type="button" class="gpos-sticky-btn" onclick="document.getElementById('gpos-cart-sheet').classList.toggle('show')">
        <i class="fas fa-shopping-cart"></i>
        Cart (<span id="gpos-sticky-count">0</span>)
    </button>
</div>

<!-- Quantity modal for long-press -->
<div class="modal fade" id="gposQtyModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered" style="max-width:300px;">
        <div class="modal-content" style="border-radius:20px;">
            <div class="modal-body p-4 text-center">
                <h6 class="fw-bold mb-3" id="gpos-modal-product-name">Product</h6>
                <div class="d-flex align-items-center justify-content-center gap-3 mb-4">
                    <button type="button" class="btn btn-outline-secondary" style="border-radius:50%;width:40px;height:40px;" id="gpos-modal-minus">−</button>
                    <input type="number" class="form-control text-center fw-bold fs-4" id="gpos-modal-qty" value="1" min="1" style="width:80px;border-radius:12px;">
                    <button type="button" class="btn btn-outline-secondary" style="border-radius:50%;width:40px;height:40px;" id="gpos-modal-plus">+</button>
                </div>
                <button type="button" class="btn btn-primary w-100 fw-bold" id="gpos-modal-confirm" style="border-radius:12px;">
                    <i class="fas fa-cart-plus me-2"></i>Add to Cart
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
/* Force currency symbol before pos_grid.js captures it */
window.swiftposCurrencySymbol = "{{ currency_symbol|escapejs }}";
window.swiftposVatRate        = {{ vat_rate|floatformat:4 }};
window.swiftposDecimalPlaces  = {{ decimal_places }};
window.swiftposCompanySlug    = "{{ request.company.slug|escapejs }}";
window.swiftposUnlimitedStock = {{ unlimited_stock|yesno:"true,false" }};
window.gposPreloadCart        = {% if preload_cart_json %}{{ preload_cart_json|safe }}{% else %}null{% endif %};
window.swiftposOrdersApiUrl   = "{% url 'sales:api_create_order' %}";
window.swiftposPromoApiUrl    = "{% url 'sales:validate_promo' %}";
</script>
<script src="{% static 'js/product-cache.js' %}?v=3"></script>
<script src="{% static 'js/order-sync.js' %}?v=3"></script>
<script src="{% static 'js/pos_grid.js' %}?v=3"></script>

<script>
(function() {
    const search = document.getElementById('gpos-cust-search');
    const drop   = document.getElementById('gpos-cust-dropdown');
    const nameV  = document.getElementById('gpos-cust-name-val');
    const phoneV = document.getElementById('gpos-cust-phone-val');
    if (!search) return;
    // Prevent Enter from submitting the form mid-typing
    search.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') { e.preventDefault(); }
    });
    const allBtns = Array.from(drop.querySelectorAll('button[data-name]'));
    search.addEventListener('input', function() {
        const q = this.value.toLowerCase();
        allBtns.forEach(b => b.style.display = b.textContent.toLowerCase().includes(q) ? '' : 'none');
        drop.style.display = '';
    });
    search.addEventListener('focus', () => drop.style.display = '');
    allBtns.forEach(btn => btn.addEventListener('click', function() {
        nameV.value  = this.dataset.name;
        phoneV.value = this.dataset.phone;
        search.value = this.dataset.name || '';
        drop.style.display = 'none';
    }));
    document.addEventListener('click', e => {
        if (!search.contains(e.target) && !drop.contains(e.target)) drop.style.display = 'none';
    });
})();
</script>

<script>
// Promo code logic for Grid POS
(function() {
    var SYM = window.swiftposCurrencySymbol || '₦';
    var promoDiscount = 0;
    var promoCode = '';

    var promoInput  = document.getElementById('gpos-promo-input');
    var promoBtn    = document.getElementById('gpos-promo-btn');
    var promoMsg    = document.getElementById('gpos-promo-msg');
    var discRow     = document.getElementById('gpos-discount-row');
    var discDisplay = document.getElementById('gpos-discount-display');
    var totalEl     = document.getElementById('gpos-total');
    var subtotalEl  = document.getElementById('gpos-subtotal');
    var vatEl       = document.getElementById('gpos-vat');
    var submitBtn   = document.getElementById('gpos-submit-btn');
    var cartPayload = document.getElementById('cart-payload-field');

    if (!promoBtn) return;

    function applyDiscount(rawSubtotal) {
        return Math.max(0, rawSubtotal - promoDiscount);
    }

    // Obsolete hook removed in favor of window.gposRenderCart

    promoBtn.addEventListener('click', function() {
        var code = (promoInput ? promoInput.value.trim().toUpperCase() : '');
        if (!code) { if (promoMsg) { promoMsg.textContent = 'Please enter a code.'; promoMsg.style.color = '#dc3545'; } return; }

        // Get current subtotal from DOM
        var subRaw = subtotalEl ? parseFloat(subtotalEl.textContent.replace(/[^0-9.]/g, '')) : 0;

        const url = window.swiftposPromoApiUrl || '/api/promo/validate/';
        fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value },
            body: JSON.stringify({ code: code, order_total: subRaw })
        })
        .then(r => r.json())
        .then(function(data) {
            if (data.valid) {
                promoDiscount = parseFloat(data.discount_amount || 0);
                promoCode = code;
                if (promoMsg) { promoMsg.textContent = '✓ ' + (data.message || 'Promo applied!'); promoMsg.style.color = '#16a34a'; }
                if (discRow) discRow.classList.remove('d-none');
                if (discDisplay) discDisplay.textContent = SYM + promoDiscount.toFixed(2);
                
                // Pass into cart payload state
                window.gposPromoCode = promoCode;
                window.gposPromoDiscount = promoDiscount;
                
                // Trigger full recalculation & UI update
                if (window.gposRenderCart) {
                    window.gposRenderCart();
                }
            } else {
                if (promoMsg) { promoMsg.textContent = '✗ ' + (data.message || 'Invalid code.'); promoMsg.style.color = '#dc3545'; }
                promoDiscount = 0; promoCode = '';
                
                window.gposPromoCode = '';
                window.gposPromoDiscount = 0;
                if (window.gposRenderCart) {
                    window.gposRenderCart();
                }
            }
        })
        .catch(function() {
            if (promoMsg) { promoMsg.textContent = 'Network error. Try again.'; promoMsg.style.color = '#dc3545'; }
        });
    });
})();
</script>

<script>
// ── Post-Sale Overlay (What Next?) — Grid POS ─────────────
(function () {
  var posUrl = '{% url "sales:pos_grid" %}';

  window.swiftposOnOrderComplete = function (result) {
    var overlay    = document.getElementById('postSaleOverlay');
    var numEl      = document.getElementById('postSaleOrderNum');
    var newBtn     = document.getElementById('postSaleNewOrderBtn');
    var receiptBtn = document.getElementById('postSaleReceiptBtn');

    var orderNum   = result.order_number || '';
    var receiptUrl = result.redirect_url || '';

    if (numEl)      numEl.textContent = orderNum ? 'Order #' + orderNum + ' recorded \u2713' : 'Sale recorded.';
    if (newBtn)     newBtn.href = posUrl;
    if (receiptBtn) receiptBtn.href = receiptUrl || '#';

    if (overlay) overlay.style.display = 'flex';
    else if (receiptUrl) window.location.href = receiptUrl;
  };
})();
</script>

  {# Variant Picker Modal - Phase 2 #}
  {% include 'pos/_variant_picker_modal.html' %}


{% endblock %}
