window.qrScanner = (function () {
    let animationFrameId = null;
    let currentStream = null;

    async function start(videoElement, dotNetRef) {
        try {
            // chiede accesso alla camera (di solito quella posteriore su mobile)
            const constraints = {
                video: {
                    facingMode: "environment"
                }
            };

            currentStream = await navigator.mediaDevices.getUserMedia(constraints);
            videoElement.srcObject = currentStream;
            await videoElement.play();

            const canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");

            const tick = async () => {
                if (!videoElement || videoElement.readyState !== videoElement.HAVE_ENOUGH_DATA) {
                    animationFrameId = requestAnimationFrame(tick);
                    return;
                }

                canvas.width = videoElement.videoWidth;
                canvas.height = videoElement.videoHeight;

                ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

                const code = jsQR(imageData.data, canvas.width, canvas.height, {
                    inversionAttempts: "dontInvert"
                });

                if (code) {
                    console.log("QR trovato:", code.data);
                    // Chiama il metodo C# marcato [JSInvokable]
                    await dotNetRef.invokeMethodAsync("OnQrDecoded", code.data);

                    //stop(videoElement); // ferma appena trovato
                    return;
                }

                animationFrameId = requestAnimationFrame(tick);
            };

            tick();
        } catch (err) {
            console.error("Errore avvio camera:", err);
            if (dotNetRef) {
                await dotNetRef.invokeMethodAsync("OnQrError", err.message ?? "Errore sconosciuto");
            }
        }
    }

    function stop(videoElement) {
        if (animationFrameId) {
            cancelAnimationFrame(animationFrameId);
            animationFrameId = null;
        }

        if (currentStream) {
            currentStream.getTracks().forEach(t => t.stop());
            currentStream = null;
        }

        if (videoElement) {
            videoElement.srcObject = null;
        }
    }

    return {
        start: start,
        stop: stop
    };
})();