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

{% block title %}POS Terminal - SwiftPOS{% endblock %}

{% block topbar_title %}
POS Terminal
{% endblock %}
{% block extra_css %}
<style>
/* ── Classic POS: Grid-style sticky right panel ─────────────── */
@media (min-width: 992px) {
  .sp-cpos-panel {
    position: sticky;
    top: 66px;
    height: calc(100vh - 82px);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background: var(--sp-surface, #fff);
    border: 1px solid var(--sp-border, #e5e7eb);
    border-radius: 12px;
  }
}
.sp-cpos-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--sp-border, #e5e7eb);
  flex-shrink: 0;
}
.sp-cpos-cart-scroll {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}
.sp-cpos-totals {
  flex-shrink: 0;
  padding: 0.75rem 1rem;
  border-top: 1px solid var(--sp-border, #e5e7eb);
  border-bottom: 1px solid var(--sp-border, #e5e7eb);
  background: var(--sp-surface-muted, #f9fafb);
}
.sp-cpos-promo {
  flex-shrink: 0;
  padding: 0.5rem 1rem;
  border-bottom: 1px solid var(--sp-border, #e5e7eb);
}
.sp-cpos-payment {
  flex-shrink: 0;
  padding: 0.75rem 1rem;
  overflow-y: auto;
  max-height: 46vh;
}
</style>
{% endblock %}

{% block content %}


<!-- 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>

<div class="container-fluid px-0">
        <div id="offline-banner" class="alert alert-warning rounded-0 mb-0 d-none">
        <i class="fas fa-wifi-slash me-2"></i>
        You are currently offline. Orders will be saved and synced automatically when you’re back online.
    </div>

    <!-- 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>

    <!-- Order + cashier overview -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card border-0" style="background: radial-gradient(circle at top left, rgba(79,70,229,.18), transparent 55%), radial-gradient(circle at bottom right, rgba(34,197,94,.14), transparent 45%), var(--sp-surface);">
                <div class="card-body d-flex flex-wrap justify-content-between align-items-center gap-3">
                    <div>
                        <div class="small text-muted mb-1">Active order</div>
                        <h5 class="mb-1">
                            <i class="fas fa-receipt me-2"></i>
                            {{ order.order_number }}
                        </h5>
                        <div class="small text-muted">
                            Cashier: {{ user_name }}
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 align-items-center">
                        <span class="badge rounded-pill bg-light text-muted border">
                            <i class="fas fa-box-open me-1"></i>
                            <span id="itemCount">{{ order_items|length }}</span> item{{ order_items|length|pluralize }}
                        </span>
                        <span class="badge rounded-pill bg-success-subtle text-success border border-success-subtle">
                            Total: <span class="ms-1 fw-semibold">{{ currency_symbol }}<span id="headerTotal">{{ final_total|floatformat:2 }}</span></span>
                        </span>
                        <a href="{% url 'sales:daily_dashboard' %}" class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2">
                            <i class="fas fa-chart-line"></i> Today’s summary
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main POS layout -->
    <div class="row g-3">
        <!-- LEFT: Products / search / quantity -->
        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                            <i class="fas fa-boxes-stacked"></i> Product Selection
                        </h6>
                        <div class="d-flex align-items-center gap-2">
                            <span class="small text-muted">
                                Choose product & quantity, then add to cart
                            </span>
                            <button type="button"
                                    class="btn btn-sm btn-outline-secondary"
                                    id="refresh-products-btn">
                                <i class="fas fa-rotate-right me-1"></i> Refresh
                            </button>
                        </div>
                    </div>

                <div class="card-body">
                    <!-- Product select (now filled from IndexedDB via JS) -->
                    <form id="productForm" class="mb-3" onsubmit="return false;">
                        <div class="mb-3">
                            <label for="product-dropdown" class="form-label fw-semibold small">
                                Product
                            </label>
                            <select
                                class="form-select"
                                id="product-dropdown"
                                required>
                                <option value="">Search or choose product…</option>
                            </select>

                            <!-- Barcode Scanner (QuaggaJS) -->
                            {% if barcode_scanner_enabled %}
                                <div class="mt-2 d-flex align-items-center gap-2">
                                    <button type="button"
                                            class="btn btn-outline-secondary btn-sm d-inline-flex align-items-center gap-2"
                                            id="openScannerBtn">
                                        <i class="fas fa-barcode"></i>
                                        Scan barcode
                                    </button>
                                    <span id="scanStatus" class="small text-muted"></span>
                                </div>

                                <div id="scannerContainer"
                                     class="border rounded mt-2"
                                     style="display:none; padding:6px; width: 280px; height: 280px; position: relative;">
                                    <div class="small text-muted mb-1">
                                        Align the barcode inside the box:
                                    </div>
                                    <!-- Small camera frame -->
                                    <video id="barcodeVideo"
                                           style="width: 100%; height: 100%; object-fit: cover; background: #000;"
                                           playsinline></video>
                                    <div class="text-end mt-2">
                                        <button type="button"
                                                class="btn btn-sm btn-light"
                                                id="closeScannerBtn">
                                            Close scanner
                                        </button>
                                    </div>
                                </div>
                            {% else %}
                                <div class="mt-2 small text-muted">
                                    Barcode scanning is not available on your current plan.
                                </div>
                            {% endif %}

                            <div class="form-text small text-muted">
                                Use SKU or name to quickly find items.
                            </div>
                        </div>

                        <!-- Quantity + quick add -->
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="quantity-input" class="form-label fw-semibold small">
                                    Quantity
                                </label>
                                <input
                                    type="number"
                                    class="form-control"
                                    id="quantity-input"
                                    min="1"
                                    value="1"
                                    placeholder="Enter quantity">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold small">
                                    Quick add
                                </label>
                                <div class="d-flex gap-2 flex-wrap">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="quickAdd(1)">+1</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="quickAdd(5)">+5</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="quickAdd(10)">+10</button>
                                </div>
                            </div>
                        </div>

                        <!-- Selected product info + add to cart -->
                        <div class="mt-4 p-3 rounded-3" style="background:var(--sp-surface-muted);">
                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                                <div>
                                    <div class="small text-muted mb-1">Selected product</div>
                                    <div class="small">
                                        Price: {{ currency_symbol }}<span id="selectedProductPrice">0.00</span> ·
                                        Stock: <span id="selectedProductStock">0</span>
                                    </div>
                                </div>
                                <div class="d-flex gap-2">
                                    <button type="button" class="btn btn-primary d-flex align-items-center gap-2" id="add-item-btn">
                                        <i class="fas fa-cart-plus"></i>
                                        Add to cart
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- RIGHT: Cart / totals / payment — Grid-POS-style sticky panel -->
        <div class="col-lg-4">
            <div class="sp-cpos-panel">
                <!-- ── CART HEADER ── -->
                <div class="sp-cpos-header">
                    <div class="d-flex align-items-center gap-2">
                        <i class="fas fa-shopping-basket"></i>
                        <span class="fw-semibold">Cart</span>
                        <span class="badge bg-light text-muted border small ms-1">
                            <span id="cartItemCount">{{ order_items|length }}</span> item{{ order_items|length|pluralize }}
                        </span>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-danger d-flex align-items-center gap-1" id="clear-cart-btn">
                        <i class="fas fa-trash"></i> Clear
                    </button>
                </div>

                <!-- ── CART ITEMS (scrollable) ── -->
                <div class="sp-cpos-cart-scroll" id="orderItemsContainer">
                    <table class="table table-sm mb-0">
                        <tbody id="cart-items-body">
                            <!-- Filled by JS from IndexedDB -->
                        </tbody>
                    </table>
                </div>

                <!-- ── TOTALS (fixed) ── -->
                <div class="sp-cpos-totals">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="small text-muted">Subtotal</span>
                        <span class="small">{{ currency_symbol }}<span id="cart-subtotal">{{ subtotal|floatformat:2 }}</span></span>
                    </div>
                    <div class="d-flex justify-content-between mb-1 text-success d-none" id="cart-discount-row">
                        <span class="small fw-semibold"><i class="fas fa-tag me-1"></i>Discount</span>
                        <span class="small fw-semibold">− {{ currency_symbol }}<span id="cart-discount-amount">0.00</span></span>
                    </div>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="small text-muted">Tax</span>
                        <span class="small">{% money tax_amount %}</span>
                    </div>
                    <hr class="my-2">
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="fw-bold">Total</span>
                        <span class="fw-bold fs-5 text-success">{{ currency_symbol }}<span id="cart-grand-total">{{ final_total|floatformat:2 }}</span></span>
                    </div>
                </div>

                <!-- ── PROMO CODE (compact) ── -->
                <div class="sp-cpos-promo">
                    <div class="input-group input-group-sm">
                        <span class="input-group-text"><i class="fas fa-tag"></i></span>
                        <input type="text" id="promo-code-input" class="form-control" placeholder="Promo code…" style="text-transform:uppercase;">
                        <button class="btn btn-outline-success" type="button" id="apply-promo-btn">Apply</button>
                    </div>
                    <div id="promo-message" class="small mt-1"></div>
                </div>

                <!-- ── PAYMENT FORM (always visible) ── -->
                <form method="post" id="pos-form" class="sp-cpos-payment">
                    {% csrf_token %}
                    <input type="hidden" name="cart_payload" id="cart-payload-field">

                    <!-- Payment method + status in one row -->
                    <div class="row g-2 mb-2">
                        <div class="col-7">
                            <select class="form-select form-select-sm" name="payment_method" required>
                                <option value="pos">POS / Card</option>
                                <option value="transfer">Bank Transfer</option>
                                <option value="cash">Cash</option>
                                <option value="mobile_money">Mobile Money</option>
                                <option value="credit">Credit</option>
                            </select>
                        </div>
                        <div class="col-5">
                            <select class="form-select form-select-sm" name="payment_status" id="payment-status-select">
                                <option value="full" selected>Paid in Full</option>
                                <option value="partial">Partial</option>
                                <option value="credit">Credit</option>
                            </select>
                        </div>
                    </div>

                    <!-- Amount paid (hidden when Full) -->
                    <div class="mb-2 d-none" id="amount-paid-group">
                        <input type="number" step="0.01" min="0" name="amount_paid"
                               class="form-control form-control-sm"
                               placeholder="Amount paid now">
                    </div>

                    <!-- Reference + Customer -->
                    <div class="row g-2 mb-2">
                        <div class="col-6">
                            <input type="text" name="reference_number" class="form-control form-control-sm" placeholder="Reference (optional)">
                        </div>
                        <div class="col-6 position-relative">
                            <input type="text" id="pos-cust-search" class="form-control form-control-sm" placeholder="🔍 Customer (opt.)" autocomplete="off">
                            <div id="pos-cust-dropdown" class="list-group position-absolute w-100 shadow-sm" style="z-index:9999;max-height:180px;overflow-y:auto;display:none;top:100%;left:0;">
                                <button type="button" class="list-group-item list-group-item-action py-1 small" data-name="" data-phone="">
                                    <span class="fw-semibold">Walk-in</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-1">{{ c.phone }}</span>{% endif %}
                                </button>
                                {% endfor %}
                            </div>
                            <input type="hidden" name="customer_name" id="pos-cust-name-val">
                            <input type="hidden" name="customer_phone" id="pos-cust-phone-val">
                        </div>
                    </div>

                    <!-- Complete Order button -->
                    <button type="submit" class="btn btn-primary w-100 fw-bold d-flex justify-content-center align-items-center gap-2" style="border-radius:12px;padding:0.85rem;font-size:1rem;">
                        <i class="fas fa-check-circle"></i> Complete Order
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
    <!-- QuaggaJS barcode library -->
    <script src="{% static 'js/quagga.min.js' %}"></script>

    <!-- Unlimited stock flag for JS -->
    <script>
    window.swiftposUnlimitedStock = {{ unlimited_stock|yesno:"true,false" }};
    window.swiftposOrdersApiUrl   = "{% url 'sales:api_create_order' %}";
    window.swiftposPromoApiUrl    = "{% url 'sales:validate_promo' %}";
    </script>

    <!-- Offline product + cart + order sync -->
    <script src="{% static 'js/product-cache.js' %}"></script>
    <script src="{% static 'js/pos-cart.js' %}"></script>
    <script src="{% static 'js/order-sync.js' %}"></script>

    <!-- ★ CRITICAL: initialise cart (wires add-to-cart, +/-, remove, promo buttons) -->
    <script>
    // Preload items from backend order (for Repeat Sale / Resume Draft)
    window.swiftposPreloadedItems = [
        {% for item in order_items %}
        {
            id: "{{ item.product.id }}",
            name: "{{ item.product.name|escapejs }}",
            basePrice: {{ item.product.price|default:0 }},
            price: {{ item.unit_price }},
            quantity: {{ item.quantity }},
            stock: {{ item.product.stock_quantity|default:0 }},
            barcode: "{{ item.product.barcode|escapejs|default:'' }}",
            wholesalePrice: {% if item.product.wholesale_price %}{{ item.product.wholesale_price }}{% else %}null{% endif %},
            wholesaleMinQty: {% if item.product.wholesale_min_quantity %}{{ item.product.wholesale_min_quantity }}{% else %}0{% endif %}
        }{% if not forloop.last %},{% endif %}
        {% endfor %}
    ];

    document.addEventListener('DOMContentLoaded', async function () {
        if (window.swiftposCart && window.swiftposCart.init) {
            // First we check if we need to force preload items into DB
            if (window.swiftposPreloadedItems.length > 0 && window.swiftposCart.getDB) {
                try {
                    const { items } = await window.swiftposCart.loadCartFromDB();
                    if (items.length === 0) {
                        // Cart empty on frontend, but backend has items -> inject them!
                        let subtotal = 0;
                        window.swiftposPreloadedItems.forEach(i => subtotal += (i.price * i.quantity));
                        const totals = { id: 'current', subtotal, discount: 0, tax: 0, grandTotal: subtotal };
                        await window.swiftposCart.saveCartToDB(window.swiftposPreloadedItems, totals);
                        console.log("DEBUG POS: Preloaded", window.swiftposPreloadedItems.length, "items into cart from backend.");
                    }
                } catch(e) { console.error("Error preloading cart:", e); }
            }
            window.swiftposCart.init();
        }
    });
    </script>

    <script>
    // Barcode scanner logic (same as before, but using #product-dropdown)
    document.addEventListener('DOMContentLoaded', function () {
        const scannerEnabled = {{ barcode_scanner_enabled|yesno:"true,false" }};
        if (!scannerEnabled) {
            console.log("DEBUG POS: Barcode scanner disabled by plan");
            return;
        }

        const productSelect = document.getElementById('product-dropdown');
        const openBtn = document.getElementById('openScannerBtn');
        const closeBtn = document.getElementById('closeScannerBtn');
        const scannerContainer = document.getElementById('scannerContainer');
        const scanStatus = document.getElementById('scanStatus');
        const videoElem = document.getElementById('barcodeVideo');

        let scanning = false;

        function selectProductByBarcode(barcode) {
            if (!productSelect) return false;
            const value = barcode.trim();
            console.log("DEBUG POS: Decoded barcode =", value);

            const opts = productSelect.options;
            for (let i = 0; i < opts.length; i++) {
                const opt = opts[i];
                if (opt.dataset && opt.dataset.barcode && opt.dataset.barcode === value) {
                    productSelect.value = opt.value;
                    productSelect.dispatchEvent(new Event('change'));
                    scanStatus.textContent = "Scanned: " + value;
                    scanStatus.classList.remove('text-danger');
                    scanStatus.classList.add('text-success');
                    return true;
                }
            }
            scanStatus.textContent = "No product found with barcode " + value;
            scanStatus.classList.remove('text-success');
            scanStatus.classList.add('text-danger');
            return false;
        }

        function startScanner() {
            if (scanning) return;

            scannerContainer.style.display = 'block';
            scanStatus.textContent = "Align barcode with camera…";
            scanStatus.classList.remove('text-danger', 'text-success');

            Quagga.init({
                inputStream: {
                    name: "Live",
                    type: "LiveStream",
                    target: document.querySelector('#scannerContainer'),
                    constraints: {
                        width: { min: 640, ideal: 640, max: 1280 },
                        height: { min: 480, ideal: 480, max: 720 },
                        aspectRatio: { ideal: 1 },
                        facingMode: "environment"
                    },
                },
                decoder: {
                    readers: ["code_128_reader"]
                }
            }, function (err) {
                if (err) {
                    console.error("DEBUG POS: Quagga initialization error:", err);
                    scanStatus.textContent = "Error initializing scanner.";
                    scanStatus.classList.add('text-danger');
                    scannerContainer.style.display = 'none';
                    return;
                }
                console.log("DEBUG POS: Quagga initialized successfully.");
                Quagga.start();
                scanning = true;
            });

            Quagga.onDetected(function (result) {
                const barcode = result.codeResult.code;
                console.log("DEBUG POS: Barcode detected:", barcode);
                const found = selectProductByBarcode(barcode);
                if (found) {
                    stopScanner();
                }
            });
        }

        function stopScanner() {
            if (!scanning) return;
            Quagga.stop();
            scanning = false;
            scannerContainer.style.display = 'none';
            console.log("DEBUG POS: Scanner stopped");
        }

        if (openBtn) {
            openBtn.addEventListener('click', function () {
                if (scanning) {
                    stopScanner();
                } else {
                    startScanner();
                }
            });
        }

        if (closeBtn) {
            closeBtn.addEventListener('click', function () {
                stopScanner();
            });
        }

        window.addEventListener('beforeunload', function () {
            stopScanner();
        });
    });
    </script>

    <!-- Existing POS JS: Select2, selected product info, quickAdd -->
    <script>
    document.addEventListener('DOMContentLoaded', async function () {
        const productSelect = document.getElementById('product-dropdown');
        const priceSpan = document.getElementById('selectedProductPrice');
        const stockSpan = document.getElementById('selectedProductStock');
        const statusEl = document.getElementById('product-loading-status');
        const refreshBtn = document.getElementById('refresh-products-btn');

                // ---- Payment status -> show/hide Amount Paid ----
        const paymentStatusSelect = document.getElementById("payment-status-select");
        const amountPaidGroup = document.getElementById("amount-paid-group");

        function updateAmountPaidVisibility() {
            if (!paymentStatusSelect || !amountPaidGroup) return;
            const val = paymentStatusSelect.value;
            if (val === "full") {
                amountPaidGroup.classList.add("d-none");
            } else {
                amountPaidGroup.classList.remove("d-none");
            }
        }

        if (paymentStatusSelect && amountPaidGroup) {
            paymentStatusSelect.addEventListener("change", updateAmountPaidVisibility);
            updateAmountPaidVisibility();
        }

    
        async function populateProducts(options) {
            if (!productSelect || !window.swiftposLoadProducts) return;
    
            const forceRefresh = options && options.forceRefresh;
            if (statusEl) {
                statusEl.textContent = forceRefresh ? "Refreshing products…" : "Loading products…";
            }
    
            try {
                let products;
                if (forceRefresh && window.swiftposRefreshProducts) {
                    products = await window.swiftposRefreshProducts();
                } else {
                    products = await window.swiftposLoadProducts();
                }
    
                productSelect.innerHTML = '<option value="">Search or choose product…</option>';
    
                (products || []).forEach((p) => {
                    // if (Number(p.stock_quantity) <= 0) return; // safety removed to show all products

                    const opt = document.createElement('option');
                    opt.value = p.id;

                    // Build label: show wholesale price if configured
                    let label = `${p.name} (${p.id}) - {{ currency_symbol }}${p.price}`;
                    if (p.wholesale_price && Number(p.wholesale_min_quantity) > 0) {
                        label += ` / Wholesale: {{ currency_symbol }}${p.wholesale_price} (≥ ${p.wholesale_min_quantity})`;
                    }
                    label += ` | Stock: ${p.stock_quantity}`;
                    opt.textContent = label;

                    opt.dataset.name = p.name;
                    opt.dataset.price = p.price;
                    opt.dataset.stock = p.stock_quantity;
                    opt.dataset.barcode = p.barcode || "";

                    // NEW: store wholesale info
                    opt.dataset.wholesalePrice = p.wholesale_price || "";
                    opt.dataset.wholesaleMinQty = p.wholesale_min_quantity || "";

                    productSelect.appendChild(opt);
                });

    
                if (statusEl) {
                    statusEl.textContent = navigator.onLine ? "Products up to date." : "Offline — using cached products.";
                }
    
                updateSelectedInfo();
            } catch (err) {
                console.error("SwiftPOS: error loading products", err);
                if (statusEl) {
                    statusEl.textContent = "Error loading products. Using cached data if available.";
                }
            }
        }
    
        function updateSelectedInfo() {
            if (!productSelect || !priceSpan || !stockSpan) return;
            const opt = productSelect.options[productSelect.selectedIndex];
            if (opt && opt.value) {
                priceSpan.textContent = opt.dataset.price || '0.00';
                stockSpan.textContent = opt.dataset.stock || '0';
            } else {
                priceSpan.textContent = '0.00';
                stockSpan.textContent = '0';
            }
        }
    
        // Initialize Select2 if available
        if (window.jQuery && jQuery.fn.select2) {
            $('#product-dropdown').select2({
                placeholder: "Search or choose product…",
                allowClear: true,
                width: '100%',
                dropdownAutoWidth: true
            });
        }
    
        if (productSelect) {
            productSelect.addEventListener('change', updateSelectedInfo);
        }
    
        // Initial load
        populateProducts({ forceRefresh: false });
    
        // Refresh button
        if (refreshBtn) {
            refreshBtn.addEventListener('click', function () {
                populateProducts({ forceRefresh: true });
            });
        }
    
        // Auto-refresh when back online
        window.addEventListener('online', () => {
            populateProducts({ forceRefresh: true });
        });
    
        // Offline banner
        function updateOfflineBanner() {
            const banner = document.getElementById('offline-banner');
            if (!banner) return;
            if (navigator.onLine) {
                banner.classList.add('d-none');
            } else {
                banner.classList.remove('d-none');
            }
        }
    
        window.addEventListener('online', updateOfflineBanner);
        window.addEventListener('offline', updateOfflineBanner);
        updateOfflineBanner();
    
        const container = document.getElementById('orderItemsContainer');
        if (container) {
            container.scrollTop = container.scrollHeight;
        }
    });
    
    function quickAdd(qty) {
        const quantityInput = document.getElementById('quantity-input');
        if (!quantityInput) return;
        quantityInput.value = qty;
        const addBtn = document.getElementById('add-item-btn');
        if (addBtn) addBtn.click();
    }
    </script>


<script>
(function() {
    const search = document.getElementById('pos-cust-search');
    const drop   = document.getElementById('pos-cust-dropdown');
    const nameV  = document.getElementById('pos-cust-name-val');
    const phoneV = document.getElementById('pos-cust-phone-val');
    if (!search) return;
    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>
// ── Post-Sale Overlay (What Next?) ────────────────────────
(function () {
  var posUrl = "{% url 'sales:pos' %}";

  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 %}
