if ('serviceWorker' in navigator) {
    // 1) Attach listeners BEFORE register
    navigator.serviceWorker.addEventListener('message', (event) => {
        console.log('SW → Page:', event.data);
        //alert(event.data);
    });

    // Fires when this page finally gets a controller
    navigator.serviceWorker.addEventListener('controllerchange', () => {
        console.log('🔄 controllerchange: page is now controlled by a SW');
        // Now that we’re controlled, send a ping
        navigator.serviceWorker.controller?.postMessage({ type: 'PING', at: Date.now() });
    });

    // 2) Register
    navigator.serviceWorker.register('/scan-terminal/service-worker.js')
        .then(async (reg) => {
            console.log('✅ Service worker registered with scope:', reg.scope);

            // If already active, talk to it immediately
            if (reg.active) {
                reg.active.postMessage({ type: 'HELLO_FROM_PAGE', at: Date.now() });
            }

            // Also when it's ready (active + controlling or soon)
            const ready = await navigator.serviceWorker.ready;
            ready.active?.postMessage({ type: 'READY_PING', at: Date.now() });

            // If this page still lacks a controller on first install, force one reload
            if (!navigator.serviceWorker.controller) {
                console.log('No controller yet; forcing one-time reload for control');
                // Prevent infinite loops: mark that we've reloaded once
                if (!sessionStorage.getItem('sw-reloaded')) {
                    sessionStorage.setItem('sw-reloaded', '1');
                    location.reload();
                }
            }
        })
        .catch((err) => console.error('❌ SW registration failed:', err));
}
//navigator.serviceWorker.register('/service-worker.js');


window.globalKeyListener = {
    init: function (dotNetRef) {

        window.OnAppMinimized = () => {
            dotNetRef.invokeMethodAsync('OnAppMinimized');
        }

        window.OnAppActivated = () => {
            dotNetRef.invokeMethodAsync('OnAppActivated');
        }



        let blurControl = false;
        let altValue = '';
        let altPreviousLength = 0;
        const hiddenInputCatcher = document.getElementById('hiddenInputCatcher');
        hiddenInputCatcher.focus();


        window.addEventListener('blur', async (e) => {
            blurControl = true;
        });

        document.addEventListener('focusout', async (e) => {
            if (e.relatedTarget != undefined) {
                return;
            }


            blurControl = false;
            setTimeout(() => {

                if (!blurControl) {
                    hiddenInputCatcher.focus();
                }

                blurControl = false;

            }, "100");

        });

        function isTextReceiver(el) {
            if (!el) return false;
            const tag = el.tagName;
            if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
            if (el.isContentEditable) return true;
            return el.id === 'hiddenInputCatcher';
        }

        /*const blockFocus = (e) => {
            const t = e.target;
            if (!isTextReceiver(t)) {
                e.preventDefault();
                hiddenInputCatcher.focus();
            }
        };*/


        /*document.addEventListener('mousedown', blockFocus, true);
        document.addEventListener('pointerdown', blockFocus, true);
        document.addEventListener('touchstart', blockFocus, true);
        */


        /*document.addEventListener('focusin', (e) => {
            const t = e.target;
            if (!isTextReceiver(t)) {
                setTimeout(() => hiddenInputCatcher.focus(), 0);
            }
        });*/


        const controlFocus = (e) => {
            const t = e.target;
            if (!isTextReceiver(t)) {
                setTimeout(() => hiddenInputCatcher.focus(), 0);
            }
        };

        document.addEventListener('mousedown', controlFocus, true);
        document.addEventListener('pointerdown', controlFocus, true);
        document.addEventListener('touchstart', controlFocus, true);
        document.addEventListener('focusin', controlFocus, true);

        hiddenInputCatcher.addEventListener('keydown', async (e) => {

            //console.log("keydown", e.key);
            if (e.key == undefined) {
                return;
            }


            //if (e.key == "Alt") {
            //    return;
            //}

            if (e.altKey && e.key != "Alt") {
                if (altValue.length == 0) {
                    altPreviousLength = hiddenInputCatcher.value.length;
                }
                altValue += e.key;
            }
            else {
                if (altValue.length > 0) {
                    //console.log("altValue", altValue);
                    //console.log("parseInt(altValue)", parseInt(altValue));
                    //console.log("String.fromCharCode(parseInt(altValue))", String.fromCharCode(parseInt(altValue)));
                    if (hiddenInputCatcher.value.length == altPreviousLength) {
                        hiddenInputCatcher.value += String.fromCharCode(parseInt(altValue));
                    }
                    //console.log("hiddenInputCatcher.value", hiddenInputCatcher.value);

                    altValue = '';
                    altPreviousLength = 0;
                }
            }

            if (e.key == "Alt") {
                e.preventDefault();
                return;
            }

            if (e.key == "Enter") {
                e.preventDefault();

                var inputText = hiddenInputCatcher.value;

                if (inputText) {
                    hiddenInputCatcher.value = '';
                    await dotNetRef.invokeMethodAsync('OnGlobalEnter', inputText);
                }
            }
        });

        hiddenInputCatcher.addEventListener('paste', async (e) => {
            e.preventDefault();

            const pastedText = (e.clipboardData || window.clipboardData).getData('text');

            if (pastedText) {
                await dotNetRef.invokeMethodAsync('OnGlobalPaste', pastedText);
            }
        });
    }
};

window.getAppVersion = () => {
    const version = document.querySelector('meta[name="app-version"]').content;
    return version;
};

function requestFullScreen() {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
    }
    else {
        document.exitFullscreen();
    }
}

function playAudio(url) {
    const audio = new Audio(url);
    audio.play();
}