(async function (doc) {
    try {
        const currentUrl = window.location.origin;
        const response = await fetch(`${currentUrl}/get-webapp-metadata`);
        if (response.ok) {
            const data = await response.json();
            const webAppId = data.id;
            const target = doc.getElementsByClassName("web-app-container");
            target[0].setAttribute("id", webAppId);
            const parent = target[0].parentElement;
            parent.setAttribute("data-script", `/binaries/webapp-demo/${data.indexFileJs}`);
            parent.setAttribute("data-style", `/binaries/webapp-demo/${data.indexFileCss}`);

            const jsElement = doc.getElementById("metadata__js-files");
            const cssElement = doc.getElementById("metadata__css-files");
            const idElement = doc.getElementById("metadata__webapp-id");
            const lastUpdate = doc.getElementById("metadata__last-update");
            jsElement.innerHTML = "js: " + data.indexFileJs;
            cssElement.innerHTML = "css: " + data.indexFileCss;
            idElement.innerHTML = "id: " + data.id;
            lastUpdate.innerHTML = "Last update: " + timePassed(data.lastUpdate);
        } else {
            const error = await response.json();
            const lastUpdate = doc.getElementById("metadata__last-update");
            lastUpdate.innerHTML = "Error: " + error.message;
            console.log("Error fetching metadata:", error.message);
        }
    } catch (error) {
        console.log("Fetch error:", error.message);
    }

    // --------- infographics.js ----------

    const e = doc.getElementsByClassName("infographic");
    for (let a = 0, i = e.length; a < i; a++) {
        const i = e[a].getElementsByTagName("div")[0],
            n = i.getAttribute("data-script"),
            s = i.getAttribute("data-style"),
            l = i.querySelector(".web-app-container");
        if (n) {
            const t = n.split(",");
            // eslint-disable-next-line no-undef
            l ? await import(t) : require(t);
        }
        if (s) {
            const e = doc.createElement("link");
            e.setAttribute("rel", "stylesheet"),
                e.setAttribute("href", s),
                e.setAttribute("media", "all"),
                (l ? l.shadowRoot : doc.getElementsByTagName("head")[0]).appendChild(e);
        }
    }
})(document);

function timePassed(dateString) {
    const pastDate = new Date(dateString);
    const currentDate = new Date();
    const elapsedTime = currentDate - pastDate; // Time in milliseconds

    if (elapsedTime < 60000) {
        return Math.floor(elapsedTime / 1000) + " seconds";
    } else if (elapsedTime < 3600000) {
        // Less than 60 minutes
        return Math.floor(elapsedTime / 60000) + " minutes";
    } // More than 60 minutes
    return Math.floor(elapsedTime / 3600000) + " hours";
}
