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

{% block extra_head %}
<style>
#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">Use your physical barcode scanner to add items</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-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="text-center py-5 mb-4 bg-light" style="border-radius: 12px; border: 2px dashed #dee2e6;">
            <i class="fas fa-barcode text-muted mb-3" style="font-size: 5rem; opacity: 0.3;"></i>
            <h5 class="text-muted fw-bold">Awaiting Scan...</h5>
            <p class="text-muted small px-3">Start scanning products with your USB/Bluetooth barcode scanner. Items will automatically appear in the cart.</p>
          </div>
          {% endif %}

          <!-- Manual barcode input (the target wrapper) -->
          <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..." autofocus 
                   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;">
              <div>
                <div class="fw-semibold">{{ item.product.name }}</div>
                <small class="text-muted">{{ item.unit_price|floatformat:2 }} × <span class="bp-qty">{{ item.quantity }}</span></small>
              </div>
              <div class="fw-bold text-primary bp-row-total">{{ item.total_price|floatformat:2 }}</div>
            </div>
            {% empty %}
            <div id="empty-cart" class="text-center py-5 text-muted">
              <i class="fas fa-shopping-basket 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>

{% 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>
(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();
    }

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

    // 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 : '';
  }
})();
</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';
        
        // 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>
{% endblock %}
