window.pushState = function(folder, page, category, subcategory, listing, detail) {

    let pageURL = "/" + [folder, page, category, subcategory, listing, detail].filter(function(v){
        if(v) {
            return true;
        }
        return false;
    }).join("/");
    window.location.href = pageURL;
    
}
var loadScript = function(jqueryFile) {
    return new Promise(function(resolve, reject){
        var jqueryScript = document.createElement('script');
        jqueryScript.src = jqueryFile;
        jqueryScript.async = true;
        jqueryScript.onerror = function(){
            reject();
        }
        jqueryScript.onload = function(){
            resolve();
        }
        document.head.appendChild(jqueryScript)
    })
}

var appendScriptTag = function(path, type) {
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = path;
    s.async = true;
    if(type) {
        document.head.appendChild(s)
    }
    else {
        document.body.appendChild(s)
    }
}

var appendAllScripts = function(callback) {
    Promise.all(jsFiles.map(function(v){
        return loadScript(v);
    })).then((values) => {
        console.log(values);
        callback();
    }).catch(function(e){
        console.log(e);
    })
    // jsFiles.forEach(src => {
    //     const script = document.createElement('script');
    //     script.src = src;
    //     script.async = true; // Ensures scripts are executed in order
    //     document.head.appendChild(script);
    // });
    
    //callback();
    // jsFiles.forEach(function(v){
    //     html += '<script src="'+v+'" async="true"></script>';
    // })
    // if(document.getElementById("nextBundle")) {
    //     nextBundle = JSON.parse(document.getElementById("nextBundle").textContent);
    //     nextBundle.forEach(function(v){
    //         html += '<script src="'+v+'" async></script>';
    //     })
    // }
    // allScripts.innerHTML = html;
    // document.body.appendChild(allScripts);
   //console.log(html);
    // if(document.getElementById("nextBundle")) {
    //     nextBundle = JSON.parse(document.getElementById("nextBundle").textContent);
    //     nextBundle.forEach(function(v){
    //         appendScriptTag(v);
    //     })
    // }
}

var loadDeferredStyles = function() {
    if(document.getElementById("deferred-styles")) {
        var addStylesNode = document.getElementById("deferred-styles");
        var replacement = document.createElement("div");
        replacement.innerHTML = addStylesNode.textContent;
        document.head.appendChild(replacement)
        addStylesNode.parentElement.removeChild(addStylesNode);
    }
    if(document.getElementById("deferred-styles2")) {
        var addStylesNode = document.getElementById("deferred-styles2");
        var replacement = document.createElement("div");
        replacement.innerHTML = addStylesNode.textContent;
        document.head.appendChild(replacement)
        addStylesNode.parentElement.removeChild(addStylesNode);
    }
}

var preLoadImage = function (obj) {
    return new Promise((resolve, reject) => {
        var img = new Image();
        img.src = obj.getAttribute("data-src");
        img.onload = function () {
            resolve(obj.getAttribute("data-src"));
        }
        img.onerror = function () {
            reject("Image not found");
        }
    });
}
  
window.addEventListener('load', function() {
    // if(localStorage.getItem("appLoad")) {
    //     appLoad();
    // }
    // else {
    //     setTimeout(function(){
    //         appLoad();
    //     }, 3500)
    // }
    appLoad();
});

var appLoad = function() {
    let nextHeadCount = document.createElement("meta");
    nextHeadCount.setAttribute("name", "next-head-count");
    nextHeadCount.setAttribute("content", "5");
    document.head.appendChild(nextHeadCount);
    loadScript("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js").then(function(){
        setTimeout(function(){
            appendAllScripts(function(){
                localStorage.setItem("appLoad", true);
                loadDom();
            });
        },1)
    })
 
    
    
    document.querySelectorAll(".preload-image").forEach(function (v) {
        preLoadImage(v).then(function (src) {
            v.style.backgroundImage = 'url(' + src + ')';
        }).catch(function (error) {
            console.log(error);
        })
    })
    document.querySelectorAll(".preload-src").forEach(function (v) {
        preLoadImage(v).then(function (src) {
            v.src = src;
        }).catch(function (error) {
            console.log(error);
        })
    })
    loadDeferredStyles();
    
    // if ('serviceWorker' in navigator) {
    //     var host = window.location.hostname;
    //     if(host === "localhost" || host === "stagingpwa.pbodev.info") {
    //         if(window.location.pathname.indexOf("/w/") === 0) {
    //             var appName = window.location.pathname.replace("/w/", "").split("/")[0];
    //             navigator.serviceWorker.register('/w/'+appName+'/sw.js');
    //         }
    //     }
    //     else {
    //         navigator.serviceWorker.register('/sw.js');
    //     }
    // }
    // if(document.querySelector(".app-container")) {
    //     document.querySelector(".nav-bar .others").addEventListener("click", showPopup);
    //     document.querySelector(".category-popup .close").addEventListener("click", showPopup);
    // }
}

var showPopup = function(event) {
    if(document.querySelector(".app-container")) {
        if (event.currentTarget.classList.contains("others")) {
            document.querySelector(".app-container").classList.add("show-popup");
        }
        else {
            document.querySelector(".app-container").classList.remove("show-popup");
            document.querySelectorAll(".other input").forEach(function (v) {
                v.value = "";
            })
            document.querySelectorAll(".other .all-category li").forEach(function (v) {
                v.classList.remove("hide")
            })
        }
    }
}

// var loadGoogleAnalytics = function(data) {
//     if(data) {
//         if(data.metaDetails.googleAnalytics)  {
//             const aDiv = document.createElement("div");
//             aDiv.innerHTML = data.metaDetails.googleAnalytics;
//             document.body.appendChild(aDiv);
//         }
//     }
// }

// var loadDynamicFiles = function(event) {
//   window.jQuery.getJSON("/static/react-loadable-manifest.json", function( data ) {
//     var appendFiles = [];
//     for(var key in data) {
//       data[key].forEach(function(v) {
//         if(appendFiles.indexOf(v.publicPath) === -1) {
//           appendFiles.push(v.publicPath);
//         }
//       })
//     }
//     appendFiles.forEach(function(v){
//       var head = document.getElementsByTagName('body')[0];
//       var script = document.createElement('script');
//       script.type = 'text/javascript';
//       script.src = "/_next/" + v; 
//       head.appendChild(script);
//     })
//   });
   
// }


function loadDom() {
    const noscriptElement = document.getElementById('nextScript');
  
    // Use a DOMParser to parse the inner HTML of the <noscript> tag
    const parser = new DOMParser();
    const doc = parser.parseFromString(noscriptElement.textContent, 'text/html');
  
    // Extract the <script> tags
    const scriptTags = doc.querySelectorAll('script');
    const b = document.createElement("script");
    b.setAttribute("id", "__NEXT_DATA__");
    b.setAttribute("type", "application/json");
    b.innerHTML = scriptTags[0].innerHTML;
    document.body.appendChild(b);
    
    //window.__NEXT_DATA__  = JSON.parse(scriptTags[0].innerHTML);
  
    // Extract the 'src' attributes
    const scriptSrcArray = Array.from(scriptTags).map(script => script.src);
  
    // Convert to JSON array string
    const jsonArray = JSON.parse(JSON.stringify(scriptSrcArray, null, 2));
  
    // Log the JSON array
    //console.log(jsonArray);
  
    jsonArray.forEach(function(v){
      if(v !== "") {
        appendScriptTag(v)
      }
      
    })
  }