import { DeviceUtilities, setParamWithoutReload } from "../engine_utils.js";
import { NeedleXRSession } from "./NeedleXRSession.js";

/**
 * Initialize XR subsystem. Called from `initEngine()`
 */
export function initXR() {
    // Prewarm AR support check
    NeedleXRSession.isARSupported();



    if (DeviceUtilities.isiOS()) {

        // Prefetch
        const url = new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");
        url.searchParams.set("url", location.href);
        const urlStr = url.toString();
        fetch(urlStr, { method: "HEAD", mode: "no-cors" }).catch(() => {
            // appclip prefetch - to get metadata faster on iOS devices, this seems to fix the double tap issue when opening the appclip for AR sessions.
        });

        try {
            // We add the meta tag here to preload app clip card data for iOS.
            const meta = window.top?.document.querySelector('meta[name="apple-itunes-app"]');
            if(!meta) {
                const metaTag = document.createElement("meta");
                metaTag.name = "apple-itunes-app";
                metaTag.content = "app-id=6757205152, app-clip-bundle-id=tools.needle.launch-app.Clip, app-clip-display=card";
                window.top?.document.head.appendChild(metaTag);
            }
        }
        catch (e) {
            console.warn("Error adding apple-itunes-app meta tag for appclip support\n", e);
        }

        try {
            // We preconnect to apple here to speed up the appclip meta request for the first click. NOT sure if necessary and working but can't hurt either?
            const topWindow = window.top || window;
            const preconnectMeta = topWindow.document.createElement("link");
            preconnectMeta.rel = "preconnect";
            preconnectMeta.href = url.toString();
            topWindow.document.head.appendChild(preconnectMeta);
        }
        catch (e) {
            console.warn("Error adding preconnect link for appclip.apple.com\n", e);
        }
    }
}