
window.bootLoader = {
    hide: function () {
        const el = document.getElementById('boot-loader');
        if (!el) return;
        el.classList.add('is-hidden');
        setTimeout(() => el.remove(), 200);
    }
};

(function () {
    const loader = document.getElementById('boot-loader');
    if (!loader) return;

    const hide = () => {
        loader.classList.add('is-hidden');
        // remove after fade
        setTimeout(() => loader.remove(), 200);
    };

    // .NET dispatches this when Blazor has started (works with blazor.web.js)
    document.addEventListener('blazor:loaded', hide, { once: true });

    // Fallback: if event doesn't fire in your setup, hide when app renders something
    const obs = new MutationObserver(() => {
        // pick a selector that only exists after render in your app
        if (document.querySelector('main, .mud-popover-provider, .mud-layout')) {
            obs.disconnect();
            hide();
        }
    });

    obs.observe(document.documentElement, { childList: true, subtree: true });
})();


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();
        focusInputCatcher();


        window.addEventListener('blur', async (e) => {
            //console.log("blur event listener", e.key);
            blurControl = true;
        });

        document.addEventListener('focusout', async (e) => {
            //console.log("focusout event listener", e.key);
            if (e.relatedTarget != undefined) {
                return;
            }

            blurControl = false;
            setTimeout(() => {

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

                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';
        }


        window.debugFocus = () => {
            console.log({
                hidden: document.hidden,
                hasFocus: document.hasFocus(),
                activeElement: document.activeElement?.id,
                inputFocused: document.activeElement === hiddenInputCatcher
            });
        };

        const controlFocus = (e) => {
            //console.log("controlFocus");

            const t = e.target;
            if (!isTextReceiver(t)) {
                focusInputCatcher();
            }
        };

        function debugToast(message, ms = 3000) {
            const el = document.createElement("div");

            el.textContent =
                typeof message === "string" ? message : JSON.stringify(message, null, 2);

            Object.assign(el.style, {
                position: "fixed",
                zIndex: "2147483647",
                left: "12px",
                bottom: "12px",
                maxWidth: "80vw",
                padding: "8px 10px",
                font: "13px/1.4 monospace",
                whiteSpace: "pre-wrap",
                background: "rgba(0,0,0,.85)",
                color: "white",
                borderRadius: "6px",
                pointerEvents: "none",
            });

            document.body.appendChild(el);

            setTimeout(() => {
                el.remove();
            }, ms);
        }

        function focusInputCatcher() {
            hiddenInputCatcher.inputMode = "none";

            requestAnimationFrame(() => {
                hiddenInputCatcher.focus({ preventScroll: true });

                setTimeout(() => {
                    hiddenInputCatcher.inputMode = "text";
                }, 0);
            });
            /*setTimeout(() => {
                hiddenInputCatcher.focus();

                setTimeout(() => {
                    //debugToast("setting to text");
                    hiddenInputCatcher.inputMode = "text";
                    //if (navigator.virtualKeyboard) {
                    //    debugToast("hiding keyboard using api");
                    //    navigator.virtualKeyboard.hide();
                    //}
                }, 1000);

            }, 5);*/
        }

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

        /*window.addEventListener('keydown', async (e) => {
            console.log("WINDOW keydown event listener", e.key);
        });*/

        

        /*document.addEventListener('keydown', async (e) => {
            console.log("DOCUMENT keydown event listener", e.key);
        });*/

        //hiddenInputCatcher.addEventListener("touchstart", e => e.preventDefault(), { passive: false });
        //hiddenInputCatcher.addEventListener("mousedown", e => e.preventDefault());

        /*hiddenInputCatcher.addEventListener('input', async (e) => {
            console.log("on input event listener", e.value);
        });*/

        hiddenInputCatcher.addEventListener('keydown', async (e) => {
            //console.log("on keydown event listener", e.key);
            //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) => {
            //console.log("on paste event listener");


            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;
};

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

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

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