{% extends "core/base.html" %}
{% load static %}
{% load currency_filters %}
{% block title %}Barcode POS — SwiftPOS{% endblock %}

{% block extra_head %}
<style>
.pulse-anim { animation: pulse 0.4s ease; }
@keyframes pulse { 0%{transform:scale(1)} 50%{transform:scale(1.06)} 100%{transform:scale(1)} }
.cart-item-row { animation: slideIn .2s ease; }
@keyframes slideIn { from{opacity:0;transform:translateY(-8px)} to{opacity:1;transform:translateY(0)} }
/* Barcode POS compact tweaks */
.bpos-scan-placeholder {
    padding: 2rem 1rem;
    border-radius: 14px;
    border: 2px dashed #dee2e6;
    background: #f8f9fa;
    text-align: center;
    margin-bottom: 1rem;
}
.bpos-scan-placeholder .bi-icon {
    font-size: 3.5rem;
    opacity: 0.25;
    color: #6b7280;
    display: block;
    margin-bottom: 0.75rem;
}
.bpos-header-title {
    font-size: 1.4rem;
    font-weight: 800;
    background: linear-gradient(135deg,#11998e,#38ef7d);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}
</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>
      <button 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
      </button>
      <button 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
      </button>
    </div>
  </div>
</div>

<div class="container-fluid px-4 py-2">

  <div class="d-flex align-items-center justify-content-between mb-3">
    <div>
      <h1 class="bpos-header-title mb-0"><i class="fas fa-barcode me-2"></i>Barcode POS</h1>
      <p class="text-muted small mb-0">Scan products with your USB / Bluetooth barcode scanner</p>
    </div>
    <div class="d-flex gap-2">
      <a href="{% url 'sales:pos' %}" class="btn btn-sm btn-outline-secondary" style="border-radius:10px;">
        <i class="fas fa-cash-register me-1"></i>Standard POS
      </a>
    </div>
  </div>

  <div class="row g-4">
    <!-- Scanner Column -->
    <div class="col-lg-5">
      <div class="card border-0 shadow-sm" style="border-radius:20px;overflow:hidden;">
        <div class="card-header border-0 bg-transparent px-4 pt-4 pb-2 fw-bold">
          <i class="fas fa-keyboard me-2 text-success"></i>Scanner Ready
        </div>
        <div class="card-body px-4 pb-4">
          
          {% if system_settings.enable_camera_scanner %}
          <div id="scanner-container" class="mb-3 shadow-sm" style="width: 100%; height: 220px; min-height: 220px; max-height: 220px; border-radius: 12px; overflow: hidden; background: #000; position: relative; display: flex; justify-content: center; align-items: center;">
            <div id="interactive" class="viewport" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden;"></div>
          </div>
          <div id="scan-status" class="text-center text-muted small mb-3">
            <span class="spinner-border spinner-border-sm me-1"></span>Starting scanner...
          </div>
          <div class="text-center mb-2">
            <button id="bpos-torch-btn" class="btn btn-sm btn-outline-warning d-none" title="Toggle flashlight" style="border-radius:10px;">
              <i class="fas fa-lightbulb-slash me-1"></i> Flashlight
            </button>
          </div>
          {% else %}
          <div class="bpos-scan-placeholder">
            <i class="fas fa-barcode bi-icon"></i>
            <div class="fw-bold text-muted mb-1">Awaiting Scan</div>
            <p class="text-muted small mb-0">Point your scanner at a product barcode — items will appear in the cart instantly.</p>
          </div>
          {% endif %}

          <div class="input-group mb-3 shadow-sm" style="border-radius: 12px;">
            <input type="text" id="manual-barcode" class="form-control py-3" placeholder="Barcode will appear here..." 
                   style="border-radius:12px 0 0 12px; letter-spacing: 2px; font-family: monospace; font-size: 1.1rem; border-color: transparent; background: #f8f9fa;">
            <button class="btn btn-success px-4" id="manual-scan-btn" style="border-radius:0 12px 12px 0;">
              <i class="fas fa-search"></i>
            </button>
          </div>

          <div id="scan-alert" class="alert d-none py-2 px-3" style="border-radius:12px;" role="alert"></div>
        </div>
      </div>
    </div>

    <!-- Cart Column -->
    <div class="col-lg-7">
      <div class="card border-0 shadow-sm" style="border-radius:20px;">
        <div class="card-header border-0 bg-transparent px-4 pt-4 pb-2 d-flex justify-content-between align-items-center">
          <span class="fw-bold"><i class="fas fa-shopping-cart me-2 text-primary"></i>Current Order #{{ order.order_number }}</span>
          <form method="post" style="display:inline;">
            {% csrf_token %}
            <input type="hidden" name="action" value="clear_order">
            <button type="submit" class="btn btn-sm btn-outline-danger" style="border-radius:10px;"
                    onclick="return confirm('Clear this order and return all stock?')">
              <i class="fas fa-trash me-1"></i>Clear
            </button>
          </form>
        </div>
        <div class="card-body px-4 pb-0">
          <div id="cart-items" style="max-height:320px;overflow-y:auto;">
            {% for item in order_items %}
            <div class="cart-item-row d-flex align-items-center justify-content-between mb-3 p-3 rounded-3" style="background:#f8f9fa;" id="bpos-row-{{ item.id }}" data-product-id="{{ item.product.id }}" data-item-id="{{ item.id }}">
              <div class="flex-grow-1">
                <div class="fw-semibold">{{ item.product.name }}</div>
                <small class="text-muted">
                  {% if item.product.wholesale_price and item.product.wholesale_min_quantity and item.quantity >= item.product.wholesale_min_quantity %}
                    <span class="badge bg-success me-1">WS</span>{{ item.unit_price|floatformat:2 }}
                  {% else %}
                    {{ item.unit_price|floatformat:2 }}
                  {% endif %}
                  × <span class="bp-qty">{{ item.quantity }}</span>
                </small>
              </div>
              <!-- Qty controls -->
              <div class="d-flex align-items-center gap-1 ms-2">
                <form method="post" style="display:inline;">
                  {% csrf_token %}
                  <input type="hidden" name="action" value="update_qty">
                  <input type="hidden" name="item_id" value="{{ item.id }}">
                  <input type="hidden" name="delta" value="-1">
                  <button type="submit" class="btn btn-sm btn-outline-secondary px-2 py-0" style="min-width:28px;">−</button>
                </form>
                <span class="fw-bold px-1">{{ item.quantity }}</span>
                <form method="post" style="display:inline;">
                  {% csrf_token %}
                  <input type="hidden" name="action" value="update_qty">
                  <input type="hidden" name="item_id" value="{{ item.id }}">
                  <input type="hidden" name="delta" value="1">
                  <button type="submit" class="btn btn-sm btn-outline-secondary px-2 py-0" style="min-width:28px;">+</button>
                </form>
                <!-- Remove -->
                <form method="post" style="display:inline;">
                  {% csrf_token %}
                  <input type="hidden" name="action" value="remove_item">
                  <input type="hidden" name="item_id" value="{{ item.id }}">
                  <button type="submit" class="btn btn-sm btn-outline-danger px-2 py-0" style="min-width:28px;" title="Remove">
                    <i class="fas fa-times"></i>
                  </button>
                </form>
              </div>
              <div class="fw-bold text-primary bp-row-total ms-3">{% money item.total_price %}</div>
            </div>
            {% empty %}
            <div id="empty-cart" class="text-center py-4 text-muted">
              <i class="fas fa-shopping-basket fa-2x opacity-25 d-block mb-2"></i>
              <span class="small">Scan a product to start order</span>
            </div>
            {% endfor %}
          </div>
        </div>

        <!-- Total + Promo -->
        <div class="card-footer bg-transparent border-0 px-4 pb-4">
          <!-- Subtotal / Discount / Total -->
          <div class="d-flex justify-content-between small text-muted mb-1">
            <span>Subtotal</span>
            <span id="bpos-subtotal">{% money subtotal %}</span>
          </div>
          <div class="d-flex justify-content-between small text-success mb-1 d-none" id="bpos-discount-row">
            <span><i class="fas fa-tag me-1"></i>Discount</span>
            <span>−<span id="bpos-discount-display">0.00</span></span>
          </div>
          <div class="d-flex justify-content-between small text-muted mb-1" id="bpos-tax-row"{% if not vat_rate %} style="display:none!important"{% endif %}>
            <span>VAT{% if vat_rate %} ({{ vat_rate }}%){% endif %}</span>
            <span id="bpos-tax-display">{% money tax_amount %}</span>
          </div>
          <div class="d-flex justify-content-between align-items-center mb-3 pt-2 border-top">
            <span class="h5 fw-bold mb-0">Total</span>
            <span class="h4 fw-bold text-success mb-0" id="cart-total">{{ final_total|floatformat:2 }}</span>
          </div>

          <!-- Checkout Form -->
          <form method="post" id="checkout-form" data-offline="true" data-offline-type="barcode_order">
            {% csrf_token %}
            <input type="hidden" name="action" value="complete_order">
            <input type="hidden" name="promo_code" id="bpos-promo-code-val">
            <input type="hidden" name="discount_amount" id="bpos-discount-amount-val" value="0">

            <!-- Customer -->
            <div class="mb-3 position-relative">
              <input type="text" id="bpos-cust-search" class="form-control form-control-sm" placeholder="🔍 Search customer… (optional)" autocomplete="off">
              <div id="bpos-cust-dropdown" class="list-group position-absolute w-100 shadow-sm" style="z-index:9999;max-height:200px;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>
              <input type="hidden" name="customer_name" id="bpos-cust-name-val">
              <input type="hidden" name="customer_phone" id="bpos-cust-phone-val">
            </div>

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

            <div id="std-payment-row" class="row g-2 mb-3">
              <div class="col-6">
                <select name="payment_method" class="form-select form-select-sm">
                  <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">
                <input type="number" name="amount_paid" class="form-control form-control-sm"
                       placeholder="Amount Paid" step="0.01" min="0">
              </div>
            </div>

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

            <input type="hidden" name="skip_receipt" id="bpos-skip-receipt" value="">
            <button type="button" class="btn btn-success w-100 fw-bold" id="bpos-complete-btn" style="border-radius:12px;padding:14px;">
              <i class="fas fa-check-circle me-2"></i>Complete Order
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

{% if system_settings.enable_camera_scanner %}
<script src="/static/js/quagga.js"></script>
<script>
(function() {
  var scanAlert   = document.getElementById('scan-alert');
  var scanStatus  = document.getElementById('scan-status');
  var SYM         = window.swiftposCurrencySymbol || '{{ currency_symbol }}';
  var lastScanned = '';
  var debounceTimer = null;
  var scanBuffer  = [];          // stores recent codes for confirmation
  var torchOn     = false;
  var streamTrack = null;        // MediaStreamTrack for torch control

  // ── Quagga Init ─────────────────────────────────────────
  Quagga.init({
    inputStream: {
      name: 'Live',
      type: 'LiveStream',
      target: document.querySelector('#interactive'),
      constraints: { facingMode: 'environment', width: 640, height: 480 }
    },
    decoder: {
      readers: ['ean_reader', 'code_128_reader', 'code_39_reader', 'upc_reader', 'upc_e_reader']
    },
    locate: true
  }, function(err) {
    if (err) {
      if (scanStatus) scanStatus.innerHTML = '<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i>Camera error: ' + err.message + '</span>';
      return;
    }
    Quagga.start();
    if (scanStatus) scanStatus.innerHTML = '<span class="text-success"><i class="fas fa-circle me-1"></i>Scanner active</span>';

    // Try to get track for torch
    try {
      var video = document.querySelector('#interactive video');
      if (video && video.srcObject) {
        var tracks = video.srcObject.getVideoTracks();
        if (tracks.length) {
          streamTrack = tracks[0];
          var caps = streamTrack.getCapabilities && streamTrack.getCapabilities();
          if (caps && caps.torch) {
            // Show flashlight button
            var torchBtn = document.getElementById('bpos-torch-btn');
            if (torchBtn) torchBtn.classList.remove('d-none');
          }
        }
      }
    } catch(e) {}
  });

  // ── Confirmation buffer: require 2 consecutive identical reads ──
  Quagga.onDetected(function(result) {
    var code = result.codeResult.code;
    if (!code) return;

    // Confidence filter (optional boost)
    var codes = result.codeResult.decodedCodes;
    if (codes && codes.length) {
      var conf = codes.filter(c => c.error !== undefined).reduce((s,c) => s + (1 - c.error), 0) / codes.length;
      if (conf < 0.7 && code.length < 8) return; // skip very low confidence short codes
    }

    // Push to buffer
    scanBuffer.push(code);
    if (scanBuffer.length > 3) scanBuffer.shift();

    var last2 = scanBuffer.slice(-2);
    var confirmed = last2.length >= 2 && last2[0] === last2[1];

    if (!confirmed) return;
    if (code === lastScanned) return;

    lastScanned = code;
    scanBuffer  = [];
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(function() { lastScanned = ''; }, 2500);

    // Call the global processBarcode function
    if (window.processBarcode) {
        window.processBarcode(code);
    }
  });

  // ── Flashlight toggle ──────────────────────────────────────
  var torchBtn = document.getElementById('bpos-torch-btn');
  if (torchBtn) {
    torchBtn.addEventListener('click', function() {
      if (!streamTrack) return;
      torchOn = !torchOn;
      streamTrack.applyConstraints({ advanced: [{ torch: torchOn }] })
        .then(function() {
          torchBtn.querySelector('i').className = torchOn ? 'fas fa-lightbulb' : 'fas fa-lightbulb-slash';
          torchBtn.title = torchOn ? 'Turn torch off' : 'Turn torch on';
        })
        .catch(function () {
          torchBtn.title = 'Torch not supported on this device';
          torchBtn.disabled = true;
        });
    });
  }
})();
</script>
{% endif %}

<script src="{% static 'js/offline-queue.js' %}?v=3"></script>

<script>
window.swiftposPromoApiUrl = "{% url 'sales:validate_promo' %}";
window.swiftposOrdersApiUrl = "{% url 'sales:api_create_order' %}";
</script>
<script>
(function() {
  var scanAlert   = document.getElementById('scan-alert');
  var cartEl      = document.getElementById('cart-items');
  var cartTotalEl = document.getElementById('cart-total');
  var emptyCart   = document.getElementById('empty-cart');
  var checkoutBtn = document.querySelector('#checkout-form [type=submit]');
  var manualInput = document.getElementById('manual-barcode');
  var scanBtn     = document.getElementById('manual-scan-btn');
  
  var SYM         = window.swiftposCurrencySymbol || '{{ currency_symbol }}';
  var cartRunningTotal = {{ subtotal|floatformat:2 }};

  // Focus the input to catch initial scans
  if (manualInput) manualInput.focus();

  // 1. Listen for Enter on the manual input (in case they paste or type manually)
  if (manualInput) {
      manualInput.addEventListener('keydown', function(e) {
          if (e.key === 'Enter') {
              e.preventDefault();
              scanBtn.click();
          }
      });
  }

  // 2. Listen to the scan button click
  if (scanBtn) {
      scanBtn.addEventListener('click', function() {
          var val = manualInput.value.trim();
          if (val) {
              processBarcode(val);
          }
      });
  }

  // 3. Global Scanner Listener (Hardware Keyboard Wedge Support)
  // Physical barcode scanners type characters very quickly and output an 'Enter' key at the end.
  let barcodeBuffer = "";
  let lastKeyTime = Date.now();
  
  document.addEventListener('keydown', function(e) {
      // Don't intercept if user is typing in the customer search box or amount fields
      const activeEl = document.activeElement;
      if (activeEl && (activeEl.id === 'bpos-cust-search' || activeEl.name === 'amount_paid' || activeEl.name === 'payment_method' || activeEl.tagName === 'SELECT')) {
          return;
      }

      // If they are directly typing in the manual scanner box, let the input field handle it.
      if (activeEl && activeEl.id === 'manual-barcode') {
          return;
      }

      const currentTime = Date.now();
      
      // If keystrokes are more than 50ms apart, it's likely human typing, wipe the buffer
      if (currentTime - lastKeyTime > 50) {
          barcodeBuffer = "";
      }
      lastKeyTime = currentTime;
      
      if (e.key === 'Enter' && barcodeBuffer.length > 2) {
          e.preventDefault();
          // Visual feedback
          if (manualInput) manualInput.value = barcodeBuffer;
          // Process the barcode!
          processBarcode(barcodeBuffer);
          barcodeBuffer = "";
          return;
      }
      
      // Accumulate printable characters
      if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
          barcodeBuffer += e.key;
      }
  });


  // ── Process barcode ────────────────────────────────────────
  window.processBarcode = function(code) {
    showAlert('info', '<span class="spinner-border spinner-border-sm me-1"></span>Looking up: ' + code);
    
    // Clear input for next scan
    if (manualInput) {
        manualInput.value = '';
        manualInput.focus();
    }

    const url = window.swiftposScanApiUrl || '/sales/api/scan/';
    fetch(url + (url.includes('?') ? '&' : '?') + 'barcode=' + encodeURIComponent(code), {
    })
    .then(r => r.json())
    .then(data => {
      if (data.ok) {
        var p = data.product;
        showAlert('success',
          '<i class="fas fa-check-circle me-1"></i>Added: <strong>' + p.name + '</strong> — '
          + SYM + parseFloat(p.price).toFixed(2));
        insertCartRow(p);
      } else {
        showAlert('danger', '<i class="fas fa-times-circle me-1"></i>' + data.message);
      }
    })
    .catch(() => showAlert('danger', 'Network error. Check connection.'));
  }

  // ── Dynamic cart row insert (no reload) ─────────────────────
  function insertCartRow(product) {
    // Remove empty-cart placeholder
    var empty = document.getElementById('empty-cart');
    if (empty) empty.remove();

    // Check if product already in cart — works for both server-rendered and JS-inserted rows
    var existing = cartEl.querySelector('[data-product-id="' + product.id + '"]');
    if (existing) {
      // Update quantity display
      var qtyEls = existing.querySelectorAll('.bp-qty');
      var newQty = 1;
      if (qtyEls.length > 0) {
        newQty = parseInt(qtyEls[0].textContent || '1') + 1;
        qtyEls.forEach(function(el) { el.textContent = newQty; });
      }
      // Update row total display
      var totalEl2 = existing.querySelector('.bp-row-total');
      if (totalEl2) {
        totalEl2.textContent = SYM + (parseFloat(product.price) * newQty).toFixed(2);
      }
      // Update the item_id on the form inputs if server returned a new one
      if (product.item_id) {
          existing.querySelectorAll('input[name="item_id"]').forEach(function(inp) {
              inp.value = product.item_id;
          });
          existing.dataset.itemId = product.item_id;
      }
    } else {
      var row = document.createElement('div');
      row.className = 'cart-item-row d-flex align-items-center justify-content-between mb-3 p-3 rounded-3';
      row.style.background = '#f8f9fa';
      row.dataset.productId = product.id;
      
      var priceStr = SYM + parseFloat(product.price).toFixed(2);
      var itemIdStr = product.item_id ? product.item_id : '';
      var csrfToken = getCsrf();
      
      var controlsHtml = '';
      if (itemIdStr) {
          controlsHtml = `
              <div class="d-flex align-items-center gap-1 ms-2">
                <form method="post" style="display:inline;">
                  <input type="hidden" name="csrfmiddlewaretoken" value="${csrfToken}">
                  <input type="hidden" name="action" value="update_qty">
                  <input type="hidden" name="item_id" value="${itemIdStr}">
                  <input type="hidden" name="delta" value="-1">
                  <button type="submit" class="btn btn-sm btn-outline-secondary px-2 py-0" style="min-width:28px;">−</button>
                </form>
                <span class="fw-bold px-1 bp-qty">1</span>
                <form method="post" style="display:inline;">
                  <input type="hidden" name="csrfmiddlewaretoken" value="${csrfToken}">
                  <input type="hidden" name="action" value="update_qty">
                  <input type="hidden" name="item_id" value="${itemIdStr}">
                  <input type="hidden" name="delta" value="1">
                  <button type="submit" class="btn btn-sm btn-outline-secondary px-2 py-0" style="min-width:28px;">+</button>
                </form>
                <form method="post" style="display:inline;">
                  <input type="hidden" name="csrfmiddlewaretoken" value="${csrfToken}">
                  <input type="hidden" name="action" value="remove_item">
                  <input type="hidden" name="item_id" value="${itemIdStr}">
                  <button type="submit" class="btn btn-sm btn-outline-danger px-2 py-0" style="min-width:28px;" title="Remove">
                    <i class="fas fa-times"></i>
                  </button>
                </form>
              </div>
          `;
      } else {
          controlsHtml = '<small class="text-muted ms-2">× <span class="bp-qty">1</span></small>';
      }

      row.innerHTML = `
        <div class="flex-grow-1">
          <div class="fw-semibold">${product.name}</div>
          <small class="text-muted">${priceStr} × <span class="bp-qty">1</span></small>
        </div>
        ${controlsHtml}
        <div class="fw-bold text-primary bp-row-total ms-3">${priceStr}</div>
      `;
      cartEl.insertBefore(row, cartEl.firstChild);
    }

    // Always recompute total from DOM (never let JS-tracked number drift)
    window.bposUpdateTotals();

    // Enable checkout button
    if (checkoutBtn) checkoutBtn.disabled = false;

    // Refocus for next scan
    if (manualInput) setTimeout(() => manualInput.focus(), 100);
  }

  function showAlert(type, html) {
    scanAlert.className = 'alert alert-' + type + ' py-2 px-3 mt-3';
    scanAlert.innerHTML = html;
    scanAlert.style.borderRadius = '12px';
    scanAlert.classList.remove('d-none');
    
    // Auto-hide success messages after 2 seconds
    if (type === 'success') {
        setTimeout(() => {
            if (scanAlert.className.includes('alert-success')) {
                scanAlert.classList.add('d-none');
            }
        }, 2000);
    }
  }

  function getCsrf() {
    var el = document.querySelector('[name=csrfmiddlewaretoken]');
    return el ? el.value : '';
  }

  var VAT_RATE = {{ vat_rate|default:0 }};

  window.bposGetSubtotal = function() {
      let sub = 0;
      document.querySelectorAll('.bp-row-total').forEach(function(el) {
          let val = el.textContent.replace(/[^0-9.-]+/g, '');
          sub += parseFloat(val) || 0;
      });
      return sub;
  };

  window.bposUpdateTotals = function() {
      let sub = window.bposGetSubtotal();
      cartRunningTotal = sub;

      var subEl = document.getElementById('bpos-subtotal');
      if (subEl) subEl.textContent = SYM + sub.toFixed(2);

      var disc = window.bposPromoDiscount || 0;
      var taxAmt = parseFloat(((sub - disc) * VAT_RATE / 100).toFixed(2));
      var tot = Math.max(0, sub - disc + taxAmt);

      var taxRow = document.getElementById('bpos-tax-row');
      var taxDisp = document.getElementById('bpos-tax-display');
      if (taxDisp) taxDisp.textContent = SYM + taxAmt.toFixed(2);
      if (taxRow) taxRow.style.display = VAT_RATE > 0 ? '' : 'none';

      var totalEl = document.getElementById('cart-total');
      if (totalEl) {
          totalEl.textContent = tot.toFixed(2);
          totalEl.classList.remove('pulse-anim');
          void totalEl.offsetWidth;
          totalEl.classList.add('pulse-anim');
          setTimeout(() => totalEl.classList.remove('pulse-anim'), 500);
      }
  };

})();
</script>

<script>
(function() {
    const search = document.getElementById('bpos-cust-search');
    const drop   = document.getElementById('bpos-cust-dropdown');
    const nameV  = document.getElementById('bpos-cust-name-val');
    const phoneV = document.getElementById('bpos-cust-phone-val');
    if (!search) return;
    // Prevent Enter from submitting the checkout form while typing a customer name
    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';
        // Return focus to barcode scanner so next scan works!
        const manualInput = document.getElementById('manual-barcode');
        if (manualInput) manualInput.focus();
    }));
    document.addEventListener('click', e => {
        if (!search.contains(e.target) && !drop.contains(e.target)) drop.style.display = 'none';
    });
})();
</script>

<script>
// Promo code logic for Barcode POS
(function() {
    var SYM = '{{ currency_symbol|escapejs }}';
    var promoDiscount = 0;

    var promoInput   = document.getElementById('bpos-promo-input');
    var promoBtn     = document.getElementById('bpos-promo-btn');
    var promoMsg     = document.getElementById('bpos-promo-msg');
    var discRow      = document.getElementById('bpos-discount-row');
    var discDisplay  = document.getElementById('bpos-discount-display');
    var totalEl      = document.getElementById('cart-total');
    var subtotalEl   = document.getElementById('bpos-subtotal');
    var promoCodeVal = document.getElementById('bpos-promo-code-val');
    var discountVal  = document.getElementById('bpos-discount-amount-val');

    if (!promoBtn) return;

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

        var currentSubtotal = window.bposGetSubtotal ? window.bposGetSubtotal() : (parseFloat('{{ subtotal|floatformat:"2" }}') || 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: currentSubtotal })
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.valid) {
                window.bposPromoDiscount = parseFloat(data.discount_amount || 0);
                if (promoMsg) { promoMsg.textContent = '✓ ' + (data.message || 'Promo applied!'); promoMsg.style.color = '#16a34a'; }
                if (discRow) discRow.classList.remove('d-none');
                if (discDisplay) discDisplay.textContent = window.bposPromoDiscount.toFixed(2);
                if (promoCodeVal) promoCodeVal.value = code;
                if (discountVal) discountVal.value = window.bposPromoDiscount.toFixed(2);
                if (window.bposUpdateTotals) window.bposUpdateTotals();
            } else {
                window.bposPromoDiscount = 0;
                if (promoMsg) { promoMsg.textContent = '✗ ' + (data.message || 'Invalid code.'); promoMsg.style.color = '#dc3545'; }
                if (promoCodeVal) promoCodeVal.value = '';
                if (discountVal) discountVal.value = '0';
                if (discRow) discRow.classList.add('d-none');
                if (window.bposUpdateTotals) window.bposUpdateTotals();
            }
        })
        .catch(function() {
            if (promoMsg) { promoMsg.textContent = 'Network error.'; promoMsg.style.color = '#dc3545'; }
        });
    });
})();
</script>

<script>
// ── Barcode POS: Post-Sale Overlay ────────────────────────
(function () {
  var form        = document.getElementById('checkout-form');
  var completeBtn = document.getElementById('bpos-complete-btn');
  var skipField   = document.getElementById('bpos-skip-receipt');
  var submitting  = false;  // short debounce — NOT a permanent lock

  function showOverlay() {
    var o = document.getElementById('postSaleOverlay');
    if (o) o.style.display = 'flex';
  }

  function doSubmit(skip) {
    if (submitting) return;
    submitting = true;
    if (skipField) skipField.value = skip ? '1' : '';
    if (form) form.submit();
    // Auto-reset after 3s in case navigation doesn't happen (e.g. offline)
    setTimeout(function() { submitting = false; }, 3000);
  }

  if (completeBtn && form) {
    completeBtn.addEventListener('click', function () {
      if (completeBtn.disabled) return;
      showOverlay();
    });
  }

  var newBtn     = document.getElementById('postSaleNewOrderBtn');
  var receiptBtn = document.getElementById('postSaleReceiptBtn');

  if (newBtn)     newBtn.addEventListener('click',     function() { doSubmit(true);  });
  if (receiptBtn) receiptBtn.addEventListener('click', function() { doSubmit(false); });

  // When the user presses Back from the receipt page, bfcache restores the page.
  // Reset the debounce so buttons are fully functional again.
  window.addEventListener('pageshow', function(e) {
    if (e.persisted) {
      submitting = false;
      if (newBtn)     newBtn.disabled = false;
      if (receiptBtn) receiptBtn.disabled = false;
      // Hide the overlay so they can start a new order normally
      var o = document.getElementById('postSaleOverlay');
      if (o) o.style.display = 'none';
    }
  });
})();
</script>

  {# Variant Picker doesn't apply to Barcode POS since barcodes inherently identify specific variants #}

{% endblock %}
