$(function () {
    var $unsupported = $('#scan-unsupported');
    var $cameraContainer = $('#scan-camera-container');
    var $video = $('#scan-video');
    var $startButton = $('#scan-start');
    var $result = $('#scan-result');
    var $manualForm = $('#scan-manual-form');

    function resolveBarcode(barcode) {
        $result.html('<p class="text-muted">Looking up ' + barcode + '…</p>');

        $.getJSON('/api/products/barcode/' + encodeURIComponent(barcode))
            .done(function (response) {
                if (response.found) {
                    window.location.href = response.redirectUrl;
                } else {
                    $result.html('<p class="text-danger">' + (response.error || 'Product not found.') + '</p>');
                }
            })
            .fail(function () {
                $result.html('<p class="text-danger">Something went wrong looking up that barcode.</p>');
            });
    }

    $manualForm.on('submit', function (event) {
        event.preventDefault();
        var barcode = $('#manual-barcode').val().trim();
        if (barcode) {
            resolveBarcode(barcode);
        }
    });

    if (!('BarcodeDetector' in window) || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        $unsupported.removeClass('d-none');
        $startButton.prop('disabled', true);
        return;
    }

    var detector = new BarcodeDetector({ formats: ['upc_a', 'upc_e', 'ean_13', 'ean_8'] });
    var activeStream = null;
    var scanning = false;

    function stopScanning() {
        scanning = false;
        if (activeStream) {
            activeStream.getTracks().forEach(function (track) { track.stop(); });
            activeStream = null;
        }
    }

    function scanLoop() {
        if (!scanning) {
            return;
        }

        detector.detect($video[0])
            .then(function (barcodes) {
                if (barcodes.length > 0) {
                    var barcode = barcodes[0].rawValue;
                    stopScanning();
                    resolveBarcode(barcode);
                } else {
                    requestAnimationFrame(scanLoop);
                }
            })
            .catch(function () {
                requestAnimationFrame(scanLoop);
            });
    }

    $startButton.on('click', function () {
        navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
            .then(function (mediaStream) {
                activeStream = mediaStream;
                $video[0].srcObject = mediaStream;
                $cameraContainer.removeClass('d-none');
                scanning = true;
                scanLoop();
            })
            .catch(function () {
                $result.html('<p class="text-danger">Camera permission was denied.</p>');
            });
    });

    $(window).on('beforeunload', stopScanning);
});
