/* global aieoDmmScanner, jQuery, BarcodeDetector */
/**
 * Frontend barcode scanner — used by both shortcodes (staff + customer).
 * Uses the native BarcodeDetector API when available, otherwise falls back
 * to manual barcode entry.
 */
(function ($) {
    'use strict';
    if (typeof aieoDmmScanner === 'undefined') {
        return;
    }

    // --- Customer scanner --------------------------------------------------
    $(document).on('click', '.aieo-dmm-customer-scanner .aieo-dmm-lookup-barcode', function () {
        var $scanner = $(this).closest('.aieo-dmm-customer-scanner');
        var barcode = $scanner.find('#aieo-dmm-cust-barcode-input').val();
        lookupCustomer($scanner, barcode);
    });
    $(document).on('click', '.aieo-dmm-customer-scanner .aieo-dmm-start-camera', function () {
        var $scanner = $(this).closest('.aieo-dmm-customer-scanner');
        startCamera($scanner, function (code) {
            lookupCustomer($scanner, code);
        });
    });

    function lookupCustomer($scanner, barcode) {
        if (!barcode) return;
        var nonce = $scanner.data('nonce');
        $.post(aieoDmmScanner.ajaxurl, {
            action: 'aieo_dmm_scanner_customer_lookup',
            nonce: nonce,
            barcode: barcode,
        }).done(function (resp) {
            var $result = $scanner.find('.aieo-dmm-customer-result').show();
            if (resp && resp.success) {
                var d = resp.data;
                var html = '';
                if (d.image_url) {
                    html += '<img src="' + d.image_url + '" alt="">';
                }
                html += '<h3>' + d.title + '</h3>';
                html += '<p>' + d.price + '</p>';
                html += '<p><a href="' + d.add_to_cart_url + '" class="button">' + aieoDmmScanner.i18n.addToCart + '</a> ';
                html += '<a href="' + d.permalink + '">' + aieoDmmScanner.i18n.viewProduct + '</a></p>';
                $result.html(html);
            } else {
                $result.text((resp && resp.data && resp.data.message) ? resp.data.message : aieoDmmScanner.i18n.notFound);
            }
        });
    }

    // --- Staff scanner -----------------------------------------------------
    $(document).on('change', '.aieo-dmm-staff-scanner #aieo-dmm-barcode-input', function () {
        var $scanner = $(this).closest('.aieo-dmm-staff-scanner');
        var barcode = $(this).val();
        staffLookup($scanner, barcode);
    });
    $(document).on('keypress', '.aieo-dmm-staff-scanner #aieo-dmm-barcode-input', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            var $scanner = $(this).closest('.aieo-dmm-staff-scanner');
            staffLookup($scanner, $(this).val());
        }
    });

    function staffLookup($scanner, barcode) {
        if (!barcode) return;
        var nonce = $scanner.data('nonce');
        var branch = $scanner.find('#aieo-dmm-branch-select').val();
        $.post(aieoDmmScanner.ajaxurl, {
            action: 'aieo_dmm_scanner_staff_lookup',
            nonce: nonce,
            barcode: barcode,
            branch: branch,
        }).done(function (resp) {
            var $r = $scanner.find('.aieo-dmm-scanner-result').show();
            if (resp && resp.success) {
                var row = resp.data.row || {};
                var html = '<table class="widefat">';
                Object.keys(row).forEach(function (k) {
                    html += '<tr><th>' + k + '</th><td>' + (row[k] == null ? '' : row[k]) + '</td></tr>';
                });
                html += '</table>';
                $r.html(html);
            } else {
                $r.text((resp && resp.data && resp.data.message) ? resp.data.message : aieoDmmScanner.i18n.notFound);
            }
        });
    }

    // --- Camera helper -----------------------------------------------------
    function startCamera($scanner, onDetected) {
        var $video = $scanner.find('video').show();
        if (!('BarcodeDetector' in window) || !navigator.mediaDevices) {
            alert(aieoDmmScanner.i18n.cameraUnavailable);
            return;
        }
        var detector = new BarcodeDetector();
        navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
            .then(function (stream) {
                $video.get(0).srcObject = stream;
                $video.get(0).play();
                var interval = setInterval(function () {
                    detector.detect($video.get(0)).then(function (codes) {
                        if (codes && codes.length > 0) {
                            clearInterval(interval);
                            stream.getTracks().forEach(function (t) { t.stop(); });
                            $video.hide();
                            onDetected(codes[0].rawValue);
                        }
                    }).catch(function () { /* ignore */ });
                }, 400);
            })
            .catch(function () { alert(aieoDmmScanner.i18n.cameraUnavailable); });
    }

})(jQuery);
