/**
 * Product Autocomplete (PAC) Widget
 * Fixed-position global dropdown — works inside overflow-scroll containers.
 * Usage: call initProductAC(products) where products = [{id, name, code, available_qty, sell_price}, ...]
 * Set _pacOnAddNew = function(prefill){} per-page to enable "Add New Product".
 */
var _pacProducts = [];
var _pacOnAddNew = null;

function initProductAC(products) {
    _pacProducts = products;
}

/* ─── PAC input styling (injected once) ────────────────────── */
(function() {
    if (document.getElementById('_pac_style')) return;
    var s = document.createElement('style');
    s.id = '_pac_style';
    s.textContent =
        '.pac-input{'
        + 'background:#f0f7ff!important;'
        + 'border:1.5px solid #93c5fd!important;'
        + 'border-radius:6px!important;'
        + 'padding:5px 28px 5px 10px!important;'
        + 'width:100%!important;'
        + 'box-sizing:border-box!important;'
        + 'font-size:12px!important;'
        + 'background-image:url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' viewBox=\'0 0 24 24\' stroke=\'%2393c5fd\' stroke-width=\'2\'%3E%3Ccircle cx=\'11\' cy=\'11\' r=\'8\'/%3E%3Cpath d=\'m21 21-4.35-4.35\'/%3E%3C/svg%3E")!important;'
        + 'background-repeat:no-repeat!important;'
        + 'background-position:right 7px center!important;'
        + 'background-size:14px!important;'
        + 'transition:border-color .2s,box-shadow .2s!important;}'
        + '.pac-input:focus{'
        + 'border-color:#2563eb!important;'
        + 'outline:none!important;'
        + 'box-shadow:0 0 0 2px rgba(37,99,235,.15)!important;'
        + 'background-color:#fff!important;}'
        + '.pac-input::placeholder{color:#94a3b8!important;}';
    document.head.appendChild(s);
})();

/* ─── Global dropdown (body-appended, fixed position) ──────── */
var _pacDd = null, _pacActiveInput = null;

function _getPacDd() {
    if (!_pacDd) {
        _pacDd = document.createElement('div');
        _pacDd.style.cssText = 'display:none;position:fixed;z-index:9999;background:#fff;'
            + 'border:1px solid #e2e8f0;border-radius:0 0 8px 8px;'
            + 'max-height:260px;overflow-y:auto;box-shadow:0 6px 24px rgba(0,0,0,.13);min-width:500px;';
        document.body.appendChild(_pacDd);
    }
    return _pacDd;
}
function _posDd(input) {
    var dd = _getPacDd(), r = input.getBoundingClientRect();
    dd.style.left  = r.left + 'px';
    dd.style.top   = (r.bottom + 1) + 'px';
    dd.style.width = Math.max(500, r.width) + 'px';
}
function _escH(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function _hlMatch(text, q) {
    try {
        return _escH(text).replace(
            new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')', 'gi'),
            '<mark style="background:#bfdbfe;padding:0;border-radius:2px;">$1</mark>'
        );
    } catch(e) { return _escH(text); }
}

function showPacDropdown(input) {
    var dd = _getPacDd();
    _pacActiveInput = input;
    _posDd(input);
    var q = input.value.trim().toLowerCase();
    var filtered = q
        ? _pacProducts.filter(function(p) {
              return p.name.toLowerCase().indexOf(q) !== -1 || p.code.toLowerCase().indexOf(q) !== -1;
          }).sort(function(a, b) {
              var posA = a.name.toLowerCase().indexOf(q);
              var posB = b.name.toLowerCase().indexOf(q);
              if (posA === -1) posA = 9999;
              if (posB === -1) posB = 9999;
              if (posA !== posB) return posA - posB;
              return a.name.localeCompare(b.name);
          })
        : _pacProducts.slice(0, 30);

    var rows = filtered.slice(0, 30).map(function(p) {
        var hl = q ? _hlMatch(p.name, q) : _escH(p.name);
        var qty = (p.available_qty != null)
            ? parseFloat(p.available_qty || 0)
            : null;
        var price = (p.sell_price != null && parseFloat(p.sell_price) > 0)
            ? parseFloat(p.sell_price)
            : null;
        var qtyBadge = qty !== null
            ? '<span style="font-size:10px;background:#f0fdf4;color:#15803d;border:1px solid #bbf7d0;'
              + 'padding:1px 6px;border-radius:3px;white-space:nowrap;flex-shrink:0;" title="Available qty">'
              + qty.toFixed(qty % 1 === 0 ? 0 : 2) + '</span>'
            : '';
        var priceBadge = price !== null
            ? '<span style="font-size:10px;background:#fefce8;color:#92400e;border:1px solid #fde68a;'
              + 'padding:1px 6px;border-radius:3px;white-space:nowrap;flex-shrink:0;" title="Sell price">'
              + '&#8377;' + price.toFixed(0) + '</span>'
            : '';
        return '<div class="_pac_item" data-id="' + p.id + '" data-name="' + _escH(p.name) + '" data-code="' + p.code + '"'
            + ' style="padding:5px 9px;cursor:pointer;display:flex;align-items:center;gap:6px;'
            + 'border-bottom:1px solid #f8fafc;font-size:12px;">'
            + '<span style="font-family:monospace;font-size:11px;background:#eff6ff;color:#2563eb;'
            + 'padding:1px 5px;border-radius:3px;white-space:nowrap;flex-shrink:0;">' + p.code + '</span>'
            + '<span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + hl + '</span>'
            + qtyBadge + priceBadge
            + '</div>';
    }).join('');

    if (!filtered.length) {
        rows = '<div style="padding:8px 12px;font-size:12px;color:#94a3b8;">No products found</div>';
    }

    var addRow = typeof _pacOnAddNew === 'function'
        ? '<div class="_pac_addnew" style="padding:7px 12px;cursor:pointer;font-size:12px;color:#16a34a;'
          + 'border-top:2px solid #f1f5f9;background:#f9fafb;font-weight:500;">'
          + '<i class="fas fa-plus-circle" style="margin-right:5px;"></i>Add New Product</div>'
        : '';

    dd.innerHTML = rows + addRow;
    dd.style.display = 'block';

    dd.querySelectorAll('._pac_item').forEach(function(item) {
        item.addEventListener('mousedown', function(e) {
            e.preventDefault();
            pacSelectProduct(input, this.dataset.id, this.dataset.name, this.dataset.code);
        });
        item.addEventListener('mouseover', function() { this.style.background = '#eff6ff'; });
        item.addEventListener('mouseout',  function() { this.style.background = ''; });
    });
    var an = dd.querySelector('._pac_addnew');
    if (an) {
        an.addEventListener('mousedown', function(e) {
            e.preventDefault();
            dd.style.display = 'none';
            if (typeof _pacOnAddNew === 'function') _pacOnAddNew(input.value.trim());
        });
        an.addEventListener('mouseover', function() { this.style.background = '#f0fdf4'; });
        an.addEventListener('mouseout',  function() { this.style.background = '#f9fafb'; });
    }
}

function pacSelectProduct(input, id, name, code) {
    var dd = _getPacDd();
    var td = input.closest('td') || input.parentElement;
    var hidden = td ? td.querySelector('input[name="product_id[]"]') : null;
    if (hidden) hidden.value = id;
    input.value = name;
    dd.style.display = 'none';
    _pacActiveInput = null;
    var badge = td ? td.querySelector('._pac_unmatched') : null;
    if (badge) badge.remove();
    var panel = td ? td.querySelector('._pac_resolve') : null;
    if (panel) panel.remove();
    var addBtn = td ? td.querySelector('.addProductBtn') : null;
    if (addBtn) addBtn.style.display = 'none';
    input.dispatchEvent(new CustomEvent('pac:select', {
        bubbles: true,
        detail: { id: parseInt(id), name: name, code: code }
    }));
}

/* ─── Event delegation ──────────────────────────────────────── */
document.addEventListener('focusin', function(e) {
    if (e.target.classList.contains('pac-input')) showPacDropdown(e.target);
});
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('pac-input')) {
        showPacDropdown(e.target);
        if (!e.target.value.trim()) {
            var td = e.target.closest('td') || e.target.parentElement;
            var hidden = td ? td.querySelector('input[name="product_id[]"]') : null;
            if (hidden) hidden.value = '';
        }
    }
});
document.addEventListener('mousedown', function(e) {
    if (_pacDd && _pacDd.style.display !== 'none'
        && !_pacDd.contains(e.target)
        && !(e.target.classList && e.target.classList.contains('pac-input'))) {
        _pacDd.style.display = 'none';
    }
});
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && _pacDd) _pacDd.style.display = 'none';
});
window.addEventListener('scroll', function() {
    if (_pacActiveInput && _pacDd && _pacDd.style.display !== 'none') _posDd(_pacActiveInput);
}, true);

/* ─── Fuzzy helpers for AI extract ─────────────────────────── */
function pacFuzzyScore(a, b) {
    a = a.toLowerCase().trim(); b = b.toLowerCase().trim();
    if (!a || !b) return 0;
    if (a === b) return 1.0;
    if (a.indexOf(b) !== -1 || b.indexOf(a) !== -1) return 0.8;
    var wa = a.split(/\s+/), wb = b.split(/\s+/);
    var n = wa.filter(function(w) {
        return wb.some(function(v) { return v.indexOf(w) !== -1 || w.indexOf(v) !== -1; });
    }).length;
    return n / Math.max(wa.length, wb.length);
}
function pacBestMatches(name, count) {
    return _pacProducts
        .map(function(p) { return Object.assign({}, p, { _s: pacFuzzyScore(p.name, name) }); })
        .filter(function(p) { return p._s > 0.25; })
        .sort(function(a, b) { return b._s - a._s; })
        .slice(0, count || 4);
}

/* ─── Resolve panel for AI-extract unmatched products ───────── */
function pacShowResolvePanel(input, extractedName, onAddNew) {
    var td = input.closest('td');
    if (!td) return;

    if (!td.querySelector('._pac_unmatched')) {
        var badge = document.createElement('span');
        badge.className = '_pac_unmatched';
        badge.style.cssText = 'display:inline-block;font-size:10px;background:#fee2e2;color:#dc2626;'
            + 'padding:1px 5px;border-radius:3px;margin-left:4px;vertical-align:middle;';
        badge.textContent = '⚠ Unmatched';
        input.insertAdjacentElement('afterend', badge);
    }

    var panel = td.querySelector('._pac_resolve');
    if (!panel) {
        panel = document.createElement('div');
        panel.className = '_pac_resolve';
        panel.style.cssText = 'margin-top:4px;padding:6px;background:#fff7ed;'
            + 'border:1px solid #fed7aa;border-radius:6px;';
        td.appendChild(panel);
    }

    var matches = pacBestMatches(extractedName, 4);
    var html = '<div style="font-size:11px;color:#92400e;margin-bottom:4px;">'
        + '<strong>"' + _escH(extractedName) + '"</strong> not found in product list</div>';
    if (matches.length) {
        html += '<div style="font-size:11px;color:#78350f;margin-bottom:3px;">Did you mean:</div>';
        matches.forEach(function(m) {
            html += '<div class="_pac_sug" data-id="' + m.id + '" data-name="' + _escH(m.name) + '" data-code="' + m.code + '"'
                + ' style="cursor:pointer;padding:3px 6px;border-radius:4px;margin:2px 0;background:#fff;'
                + 'border:1px solid #fed7aa;display:flex;align-items:center;gap:6px;font-size:11px;">'
                + '<span style="font-family:monospace;font-size:10px;background:#eff6ff;color:#2563eb;'
                + 'padding:0 4px;border-radius:2px;">' + m.code + '</span>'
                + _escH(m.name) + '</div>';
        });
    } else {
        html += '<div style="font-size:11px;color:#78350f;">No close matches found.</div>';
    }
    if (typeof onAddNew === 'function') {
        html += '<button type="button" class="_pac_addnewbtn" data-name="' + _escH(extractedName) + '"'
            + ' style="margin-top:4px;font-size:11px;padding:2px 8px;background:none;'
            + 'border:1px solid #16a34a;color:#16a34a;border-radius:4px;cursor:pointer;">'
            + '<i class="fas fa-plus"></i> Add as New Product</button>';
    }
    panel.innerHTML = html;

    panel.querySelectorAll('._pac_sug').forEach(function(item) {
        item.addEventListener('click', function() {
            pacSelectProduct(input, this.dataset.id, this.dataset.name, this.dataset.code);
        });
        item.addEventListener('mouseover', function() { this.style.background = '#fffbeb'; });
        item.addEventListener('mouseout',  function() { this.style.background = '#fff'; });
    });
    var btn = panel.querySelector('._pac_addnewbtn');
    if (btn) {
        btn.addEventListener('click', function() {
            if (typeof onAddNew === 'function') onAddNew(this.dataset.name);
        });
    }
}
