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

{% block extra_head %}
<style>
#scanner-container { width: 100%; height: 220px; border-radius: 12px; overflow: hidden; background: #000; position: relative; display: flex; justify-content: center; align-items: center; margin-bottom: 1rem; }
#interactive.viewport { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
#interactive.viewport video, #interactive.viewport canvas { position: absolute !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; object-fit: cover !important; pointer-events: none !important; }
#barcode-result-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)} }
</style>
{% endblock %}

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

  <div class="d-flex align-items-center justify-content-between mb-4">
    <div>
      <h1 class="h3 fw-bold mb-0" style="background:linear-gradient(135deg,#11998e,#38ef7d);-webkit-background-clip:text;-webkit-text-fill-color:transparent;">
        <i class="fas fa-barcode me-2"></i>Barcode POS
      </h1>
      <p class="text-muted mb-0">Scan a product barcode to add it to this order</p>
    </div>
    <div class="d-flex gap-2">
      <a href="{% url 'sales:pos' %}" class="btn btn-outline-secondary" style="border-radius:12px;">
        <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-camera me-2 text-success"></i>Camera Scanner
        </div>
        <div class="card-body px-4 pb-4">
          <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>

          <!-- Flashlight toggle (shown by JS only when device supports torch) -->
          <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>

          <!-- Manual barcode input -->
          <div class="input-group mb-3">
            <input type="text" id="manual-barcode" class="form-control" placeholder="Or type barcode manually…" 
                   style="border-radius:12px 0 0 12px;">
            <button class="btn btn-success" 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;">
              <div>
                <div class="fw-semibold">{{ item.product.name }}</div>
                <small class="text-muted">{{ item.unit_price|floatformat:2 }} × {{ item.quantity }}</small>
              </div>
              <div class="fw-bold text-primary">{{ item.total_price|floatformat:2 }}</div>
            </div>
            {% empty %}
            <div id="empty-cart" class="text-center py-5 text-muted">
              <i class="fas fa-barcode fa-3x opacity-25 d-block mb-3"></i>
              Scan a product to start order
            </div>
            {% endfor %}
          </div>
        </div>

        <!-- Total -->
        <div class="card-footer bg-transparent border-0 px-4 pb-4">
          <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">{{ subtotal|floatformat:2 }}</span>
          </div>

          <!-- Checkout Form -->
          <form method="post" id="checkout-form">
            {% csrf_token %}
            <input type="hidden" name="action" value="complete_order">
            <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>
            <div 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>
            <button type="submit" class="btn btn-success w-100 fw-bold" style="border-radius:12px;padding:14px;"
                    {% if not order_items %}disabled{% endif %}>
              <i class="fas fa-check-circle me-2"></i>Complete Order
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="/static/js/quagga.js"></script>
<script>
(function() {
  var scanAlert   = document.getElementById('scan-alert');
  var scanStatus  = document.getElementById('scan-status');
  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 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
  var cartRunningTotal = {{ subtotal|floatformat:2 }};

  // ── 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) {
      scanStatus.innerHTML = '<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i>Camera error: ' + err.message + '</span>';
      return;
    }
    Quagga.start();
    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);

    processBarcode(code);
  });

  // ── Manual input ──────────────────────────────────────────
  document.getElementById('manual-scan-btn').addEventListener('click', function() {
    var val = document.getElementById('manual-barcode').value.trim();
    if (val) { processBarcode(val); document.getElementById('manual-barcode').value = ''; }
  });
  document.getElementById('manual-barcode').addEventListener('keydown', function(e) {
    if (e.key === 'Enter') { e.preventDefault(); document.getElementById('manual-scan-btn').click(); }
  });

  // ── 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;
        });
    });
  }

  // ── Process barcode ────────────────────────────────────────
  function processBarcode(code) {
    showAlert('info', '<span class="spinner-border spinner-border-sm me-1"></span>Looking up: ' + code);
    fetch('/sales/api/scan/?barcode=' + encodeURIComponent(code), {
      headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': getCsrf() }
    })
    .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
    var existing = cartEl.querySelector('[data-product-id="' + product.id + '"]');
    if (existing) {
      var qtyEl = existing.querySelector('.bp-qty');
      var totalEl2 = existing.querySelector('.bp-row-total');
      var newQty = parseInt(qtyEl.textContent) + 1;
      qtyEl.textContent = newQty;
      totalEl2.textContent = SYM + (parseFloat(product.price) * newQty).toFixed(2);
    } 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;
      row.innerHTML = '<div>'
        + '<div class="fw-semibold">' + product.name + '</div>'
        + '<small class="text-muted">' + SYM + parseFloat(product.price).toFixed(2) + ' × <span class="bp-qty">1</span></small>'
        + '</div>'
        + '<div class="fw-bold text-primary bp-row-total">' + SYM + parseFloat(product.price).toFixed(2) + '</div>';
      cartEl.insertBefore(row, cartEl.firstChild);
    }

    // Update running total display
    cartRunningTotal += parseFloat(product.price);
    if (cartTotalEl) cartTotalEl.textContent = cartRunningTotal.toFixed(2);

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

    // Pulse animation on total
    if (cartTotalEl) {
      cartTotalEl.id = 'barcode-result-anim';
      setTimeout(() => { if(cartTotalEl) cartTotalEl.removeAttribute('id'); }, 500);
    }
  }

  function showAlert(type, html) {
    scanAlert.className = 'alert alert-' + type + ' py-2 px-3';
    scanAlert.innerHTML = html;
    scanAlert.style.borderRadius = '12px';
    scanAlert.classList.remove('d-none');
  }

  function getCsrf() {
    var el = document.querySelector('[name=csrfmiddlewaretoken]');
    return el ? el.value : '';
  }
})();
</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;
    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>
/* Barcode scan field auto-refocus (#19)
   Keeps the scan input focused at all times so handheld scanners work without clicking. */
(function () {
    const scanInput = document.getElementById('barcode_input')
                   || document.querySelector('input[name="barcode"]')
                   || document.querySelector('.barcode-scan-input');
    if (!scanInput) return;

    // Focus on page load
    scanInput.focus();

    // After every AJAX scan response the caller should call this
    window.refocusScanInput = () => setTimeout(() => scanInput.focus(), 80);

    // If any key is pressed while not in a form field, pump it into scan input
    document.addEventListener('keydown', function (e) {
        const tag = document.activeElement ? document.activeElement.tagName : '';
        if (['INPUT','TEXTAREA','SELECT'].includes(tag)) return;
        // Printable character → redirect to scan field
        if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
            scanInput.focus();
        }
    });
})();
</script>
{% endblock %}

