let iosUrl = $("#iosUrl").val()
  , apkUrl = $("#apkUrl").val()
  , android_install_type = $("#androidInstallType").val()
  , is_ios_template = $("#is_ios_template").val()
  , installBtn = document.getElementById("install-now")
  , deferredPrompt = null;
function isFacebookApp() {
    var e = navigator.userAgent.toLowerCase();
    return e.includes("fbav") || e.includes("fban") || e.includes("fb_iab") || e.includes("fb4a") || e.includes("facebook")
}
function isInstagramApp() {
    return navigator.userAgent.toLowerCase().includes("instagram")
}
function isKwaiApp() {
    var e = navigator.userAgent.toLowerCase();
    return e.includes("kwai") || e.includes("kwaibrowser") || e.includes("ksnebula")
}
function isTikTokBrowser() {
    var e = navigator.userAgent.toLowerCase();
    return e.includes("tiktok") || e.includes("musical.ly")
}
function isSamsungBrowser() {
    var e = navigator.userAgent.toLowerCase();
    return e.includes("samsungbrowser") || e.includes("samsung")
}
function isTelegramApp() {
    var e = navigator.userAgent.toLowerCase();
    return e.includes("telegram") || e.includes("tweb") || e.includes("webapp")
}
function isInAppWebview() {
    return isFacebookApp() || isInstagramApp() || isKwaiApp() || isTikTokBrowser() || isTelegramApp()
}
function openInChrome() {
    var e = window.location.href
      , a = e.replace(/^https?:\/\//i, "");
    window.location.href = "intent://" + a + "#Intent;scheme=https;package=com.android.chrome;S.browser_fallback_url=" + encodeURIComponent(e) + ";end"
}
function isIOS() {
    return ("1" == is_ios_template ? /iphone|ipad|ipod|mac/i : /iphone|ipad|ipod/i).test(navigator.userAgent)
}
function isPwaInstalled() {
    return window.matchMedia("(display-mode: standalone)").matches || !0 === window.navigator.standalone || "1" === StorageManager.get("pwa_installed")
}
function openPwa() {
    window.location.href = "/home.html"
}
function triggerApkInstall(e) {
    var a, t;
    e && ("1" !== StorageManager.get("apk_download_event") && (StorageManager.set("apk_download_event", "1"),
    reportEvent("apk_download_event")),
    a = $("#ot").val(),
    t = e.includes("?") ? "&" : "?",
    a && (e += t + "otp=" + a),
    (t = document.createElement("a")).href = e,
    t.download = "",
    document.body.appendChild(t),
    t.click(),
    document.body.removeChild(t))
}
function showRrapidInstallPopup() {
    $(".popup-rapid-install").show();
    let t, n = 0;
    $(".install-now__loading").css("display", "flex"),
    requestAnimationFrame(function e(a) {
        a -= t = t || a;
        a < 2e3 ? (n = Math.floor(a / 2e3 * 100),
        $("#install-now__loading").text(n + "%"),
        requestAnimationFrame(e)) : ($(".install-now__loading").css("display", "none"),
        $(".install-now__actived").fadeIn())
    })
}
function getCookie(e) {
    e = document.cookie.match(new RegExp("(^| )" + e + "=([^;]+)"));
    return e ? e[2] : null
}
function getFbclidFromFbc() {
    var e = getCookie("_fbc");
    return !e || (e = e.split(".")).length < 4 ? "" : e[3]
}
function getStableFingerprint() {
    var e = [screen.width, screen.height, window.devicePixelRatio || 1, navigator.language || "", Intl.DateTimeFormat().resolvedOptions().timeZone || ""].join("|");
    return CryptoJS.SHA256(e).toString()
}
function storageLocal() {
    var e, a = $("#appName").val(), t = $("#appIcon").val().startsWith("https:") ? $("#appIcon").val() : "https:" + $("#appIcon").val(), n = $("#ot").val(), o = $("#tt").val(), i = $("#pp").val(), r = $("#channel_type").val(), l = $("#pixel_id").val(), s = $("#ch").val();
    let p = $("#ad_click_id").val();
    (p = p || getFbclidFromFbc()) && (e = getStableFingerprint(),
    $.ajax({
        url: "/index/saveAdClickId",
        type: "POST",
        data: {
            ad_click_id: p,
            ch: s,
            fingerprint: e
        },
        success: function(e) {
            console.log("Ad Click ID saved successfully:", e)
        },
        error: function(e, a, t) {
            console.error("Error saving Ad Click ID:", t)
        }
    })),
    StorageManager.set("app_name", a),
    StorageManager.set("app_icon", t),
    StorageManager.set("ot", n),
    StorageManager.set("tt", o),
    StorageManager.set("pp", i),
    StorageManager.set("channel_type", r),
    StorageManager.set("pixel_id", l),
    StorageManager.set("ad_click_id", p),
    StorageManager.set("ch", s)
}
function createManifest() {
    var e = $("#appName").val()
      , a = $("#appIcon").val().startsWith("https:") ? $("#appIcon").val() : "https:" + $("#appIcon").val()
      , t = $("#ot").val()
      , n = $("#tt").val()
      , o = $("#pp").val()
      , i = $("#ch").val()
      , r = $("#channel_type").val()
      , l = $("#pixel_id").val()
      , s = $("#ad_click_id").val();
    let p = window.location.origin + "/home.html";
    t && (c = p.includes("?") ? "&" : "?",
    p += c + "ot=" + t),
    n && (c = p.includes("?") ? "&" : "?",
    p += c + "tt=" + n),
    o && (t = p.includes("?") ? "&" : "?",
    p += t + "pp=" + o),
    i && (c = p.includes("?") ? "&" : "?",
    p += c + "ch=" + i),
    r && (n = p.includes("?") ? "&" : "?",
    p += n + "channel_type=" + r),
    l && (t = p.includes("?") ? "&" : "?",
    p += t + "pixel_id=" + l),
    s && (o = p.includes("?") ? "&" : "?",
    p += o + "ad_click_id=" + s);
    var c = {
        name: e,
        short_name: e,
        start_url: p,
        display: "standalone",
        orientation: "any",
        background_color: "black",
        icons: [{
            src: a,
            sizes: "192x192",
            type: "image/png"
        }, {
            src: a,
            sizes: "512x512",
            type: "image/png"
        }]
    }
      , i = new Blob([JSON.stringify(c)],{
        type: "application/json"
    })
      , n = URL.createObjectURL(i)
      , r = document.createElement("link");
    r.rel = "manifest",
    r.href = n,
    document.head.appendChild(r)
}
function reportEventByJs() {
    var e, a = $("#channel_type").val();
    "fb" === a && (e = $("#event_id").val(),
    fbq("track", "CustomizeProduct", {}, {
        eventID: e
    })),
    "tiktok" === a && ttq.track("Download"),
    "kwai" === a && kwaiq.track("download")
}
function reportEvent(e) {
    var a = $("#ch").val();
    $.ajax({
        url: "/home/installEvent",
        type: "POST",
        data: {
            event: e,
            ch: a
        },
        success: function(e) {
            console.log("Install event reported successfully:", e)
        },
        error: function(e, a, t) {
            console.error("Error reporting install event:", t)
        }
    })
}
storageLocal(),
createManifest(),
$(".rb-mask-show").click(function() {
    $(".popup-rapid-install").hide(),
    $(".install-now__loading").show(),
    $(".install-now__actived").hide()
}),
$(".mask__close").click(function() {
    $(".van-popup--bottom").css("transform", "translate3d(0%, 100%, 0px)"),
    $(".van-overlay").fadeOut()
}),
$(".sdapk-cancel-frame").click(function() {
    $("#popup-app-download").hide(),
    $(".van-overlay").hide()
}),
$(".sdapk-install-frame").click(function() {
    $("#popup-app-download").hide(),
    $(".van-overlay").hide(),
    triggerApkInstall(apkUrl)
}),
$("#install_first_step, .install-first-step").click(function() {
    var e;
    isIOS() ? ("1" !== StorageManager.get("ios_click_install_event") && (StorageManager.set("ios_click_install_event", "1"),
    reportEvent("ios_click_install_event")),
    iosUrl ? triggerApkInstall(iosUrl) : ($(".van-popup--bottom").css("transform", "translate3d(0%, 0px, 0px)"),
    $(".van-overlay").fadeIn())) : (e = $("#is_adjust_or_appsflyer_channel").val(),
    isInAppWebview() && "1" !== e ? openInChrome() : 2 == android_install_type && apkUrl ? triggerApkInstall(apkUrl) : showRrapidInstallPopup())
}),
window.addEventListener("beforeinstallprompt", e => {
    e.preventDefault(),
    deferredPrompt = e,
    console.log("beforeinstallprompt event")
}
),
installBtn && installBtn.addEventListener("click", async () => {
    var e;
    "1" !== StorageManager.get("click_install_event") && (StorageManager.set("click_install_event", "1"),
    reportEvent("click_install_event")),
    deferredPrompt ? (deferredPrompt.prompt(),
    e = await deferredPrompt.userChoice,
    deferredPrompt = null,
    "accepted" === e.outcome ? (StorageManager.set("pwa_installed", "1"),
    reportEventByJs(),
    "1" !== StorageManager.get("pwa_install_success_event") && (StorageManager.set("pwa_install_success_event", "1"),
    reportEvent("pwa_install_success_event")),
    openPwa()) : "1" !== StorageManager.get("pwa_install_refuse_event") && (StorageManager.set("pwa_install_refuse_event", "1"),
    reportEvent("pwa_install_refuse_event"))) : isPwaInstalled() ? openPwa() : (reportEvent("pwa_install_no_prompt_event"),
    apkUrl && triggerApkInstall(apkUrl))
}
),
isIOS() && iosUrl && "1" == is_ios_template && setTimeout(function() {
    triggerApkInstall(iosUrl)
}, 1e4);
