window.FilterCair = {
    registerNetworkHandler: function (dotnetRef) {
        window.addEventListener('online', () => dotnetRef.invokeMethodAsync('UpdateNetworkStatus', true));
        window.addEventListener('offline', () => dotnetRef.invokeMethodAsync('UpdateNetworkStatus', false));
    },

    isOnline: function () {
        return navigator.onLine;
    },

    getLocation: async function () {
        if (!navigator.geolocation) return "nicht verfügbar";

        return new Promise(resolve => {
            navigator.geolocation.getCurrentPosition(
                pos => resolve(`${pos.coords.latitude.toFixed(4)}, ${pos.coords.longitude.toFixed(4)}`),
                _ => resolve("nicht verfügbar"),
                { enableHighAccuracy: true }
            );
        });
    }
};



window.QRScanner = {
    video: null,
    stream: null,
    dotnetRef: null,
    scanning: false,

    init: function (dotnetRef) {
        this.dotnetRef = dotnetRef;
        console.log("QRScanner initialized");
    },

    start: async function () {
        if (!this.video) {
            this.video = document.getElementById("video");
        }
        try {
            this.stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
            this.video.srcObject = this.stream;
            this.scanning = true;
            this.scanLoop();
        } catch (err) {
            alert("Kamera konnte nicht gestartet werden: " + err);
        }
    },

    stop: function () {
        if (this.stream) {
            this.stream.getTracks().forEach(t => t.stop());
        }
        this.scanning = false;
    },

    scanLoop: async function () {
        if (!this.video) return;
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        const jsQRAvailable = typeof jsQR !== 'undefined';

        if (!jsQRAvailable) {
            console.warn("jsQR not loaded yet.");
            return;
        }

        const tick = () => {
            if (!this.scanning) return;
            if (this.video.readyState === this.video.HAVE_ENOUGH_DATA) {
                canvas.width = this.video.videoWidth;
                canvas.height = this.video.videoHeight;
                context.drawImage(this.video, 0, 0, canvas.width, canvas.height);
                const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                const code = jsQR(imageData.data, imageData.width, imageData.height);
                if (code) {
                    console.log("QR erkannt:", code.data);
                    this.dotnetRef.invokeMethodAsync("OnQrDetected", code.data);
                    this.stop();
                    return;
                }
            }
            requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
    }
};
