{% comment %}
  _variant_picker_modal.html — POS Variant Picker Modal (Phase 2)
  To use: add the include tag to your POS template.
  Exposes: window.swiftVariantPicker.open(product, callback)
{% endcomment %}

<div class="modal fade" id="variantPickerModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-md">
    <div class="modal-content border-0 shadow-lg" style="border-radius:16px;overflow:hidden;">

      <!-- Header -->
      <div class="modal-header text-white" style="background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);">
        <div>
          <h5 class="modal-title mb-0 fw-bold" id="vpm-product-name">Select Variant</h5>
          <small class="opacity-75" id="vpm-product-subtitle">Choose an option to continue</small>
        </div>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <!-- Product image row (optional) -->
      <div id="vpm-image-row" class="text-center pt-3 pb-1 d-none">
        <img id="vpm-product-image" src="" alt="" style="height:90px;object-fit:contain;border-radius:8px;">
      </div>

      <!-- Variants Grid -->
      <div class="modal-body p-3">
        <div id="vpm-loading" class="text-center py-4 d-none">
          <div class="spinner-border text-primary" role="status"></div>
          <p class="mt-2 text-muted small">Loading variants…</p>
        </div>
        <div id="vpm-no-variants" class="text-center py-4 d-none">
          <i class="fas fa-exclamation-circle fa-2x text-warning mb-2 d-block"></i>
          <p class="text-muted small">No active variants found for this product.</p>
        </div>
        <div class="row g-2" id="vpm-grid"></div>
      </div>

      <!-- Footer -->
      <div class="modal-footer border-0 pt-0">
        <button class="btn btn-outline-secondary w-100" data-bs-dismiss="modal">Cancel</button>
      </div>

    </div>
  </div>
</div>

<style>
.vpm-card {
  cursor: pointer;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 12px 10px;
  text-align: center;
  transition: all .18s ease;
  background: #fff;
  position: relative;
}
.vpm-card:hover {
  border-color: #667eea;
  background: #f5f3ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 14px rgba(102,126,234,.2);
}
.vpm-card.out-of-stock {
  opacity: .55;
  cursor: not-allowed;
  background: #f8f9fa;
}
.vpm-card .vpm-label { font-weight: 700; font-size: .9rem; color: #2d3748; }
.vpm-card .vpm-price { font-size: .85rem; color: #667eea; font-weight: 600; }
.vpm-card .vpm-stock { font-size: .75rem; color: #6c757d; }
.vpm-card .vpm-badge {
  position: absolute; top: 6px; right: 6px;
  font-size: .65rem; padding: 2px 6px; border-radius: 20px;
}
</style>

<style>
/* Raise variant picker above SwiftPOS swiftposAlert overlay (z-index:999999) */
#variantPickerModal { z-index: 1000020 !important; }
/* Ensure inputs inside Bootstrap modals are always interactive */
.modal .form-control, .modal .form-select,
.modal input, .modal textarea, .modal select { pointer-events: auto !important; }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
  var pickerEl = document.getElementById('variantPickerModal');
  if (pickerEl && pickerEl.parentNode !== document.body) {
    document.body.appendChild(pickerEl);
  }

(function() {
  let _modal  = null;
  let _cb     = null;
  let _product = null;

  function getModal() {
    // Always use getOrCreateInstance — avoids Bootstrap 5 stale-instance bugs
    return bootstrap.Modal.getOrCreateInstance(document.getElementById('variantPickerModal'));
  }

  function open(product, callback) {
    _cb      = callback;
    _product = product;

    document.getElementById('vpm-product-name').textContent    = product.name || 'Select Variant';
    document.getElementById('vpm-product-subtitle').textContent = 'Choose a variant to add to cart';

    const imgRow = document.getElementById('vpm-image-row');
    if (product.image) {
      document.getElementById('vpm-product-image').src = product.image;
      imgRow.classList.remove('d-none');
    } else {
      imgRow.classList.add('d-none');
    }

    const grid    = document.getElementById('vpm-grid');
    const loading = document.getElementById('vpm-loading');
    const noVars  = document.getElementById('vpm-no-variants');

    grid.innerHTML = '';
    loading.classList.remove('d-none');
    noVars.classList.add('d-none');

    // Close any currently-open Bootstrap modal first (prevents Bootstrap's
    // double-modal inert attribute making inputs unclickable)
    document.querySelectorAll('.modal.show').forEach(function(el) {
      var inst = bootstrap.Modal.getInstance(el);
      if (inst) inst.hide();
    });

    // Short delay so Bootstrap finishes hide animation before opening picker,
    // then also raise the new backdrop above the SwiftPOS alert overlay
    setTimeout(function() {
      getModal().show();
      // Raise the backdrop Bootstrap just created
      setTimeout(function() {
        var bds = document.querySelectorAll('.modal-backdrop');
        if (bds.length) bds[bds.length - 1].style.zIndex = '1000010';
      }, 20);
    }, 50);

    // Use variants already embedded in product JSON (from /api/products/json/)
    const variants = product.variants || [];
    loading.classList.add('d-none');

    if (!variants.length) {
      noVars.classList.remove('d-none');
      return;
    }

    variants.forEach(v => {
      const oos  = v.stock_status === 'out_of_stock';
      const low  = v.stock_status === 'low_stock';
      const col  = document.createElement('div');
      col.className = 'col-6 col-sm-4';

      col.innerHTML = `
        <div class="vpm-card ${oos ? 'out-of-stock' : ''}"
             data-variant-id="${v.id}"
             data-label="${v.display_label}"
             data-price="${v.price}"
             data-sku="${v.sku}"
             data-stock="${v.stock_quantity}"
             title="${oos ? 'Out of stock' : v.display_label}">
          ${oos ? '<span class="vpm-badge bg-danger text-white">Out of Stock</span>'
                : (low ? '<span class="vpm-badge bg-warning text-dark">Low Stock</span>' : '')}
          <div class="vpm-label">${v.display_label}</div>
          <div class="vpm-price">₦${parseFloat(v.price).toLocaleString('en-NG', {minimumFractionDigits:2})}</div>
          <div class="vpm-stock">${oos ? 'No stock' : v.stock_quantity + ' available'}</div>
        </div>
      `;

      if (!oos) {
        col.querySelector('.vpm-card').addEventListener('click', function() {
          const chosen = {
            id:            parseInt(this.dataset.variantId),
            display_label: this.dataset.label,
            price:         this.dataset.price,
            sku:           this.dataset.sku,
            stock_quantity: parseInt(this.dataset.stock),
            // Pass through the parent product details POS needs
            product_id:    _product.id,
            product_name:  _product.name,
            image:         _product.image || '',
            category:      _product.category || '',
            has_variants:  true,
          };
          getModal().hide();
          if (_cb) _cb(chosen);
        });
      }
      grid.appendChild(col);
    });
  }

  // Expose globally so any POS JS can call it
  window.swiftVariantPicker = { open };
})();
}); // end DOMContentLoaded
</script>
