let locale;
const ember = window.Ember.A(window.Ember.Namespace.NAMESPACES).filter((n) => {
  return n.modulePrefix === "hotline-frontend";
})[0];
function sendMessage(message) {
  locale == "tr"
    ? ember.__container__
        .lookup("service:live-translation")
        .setProperties({ dontTranslateThisMessage: 1 })
    : ember.__container__
        .lookup("service:live-translation")
        .setProperties({ dontTranslateThisMessage: 0 });

  window.fcAgent.events.publish("send_message", {
    message: message,
    unforce: false,
  });
}
const AbonelikBilgileri = (res) => {
  const trialStart = new Date(res?.data?.trial_starts_at).toLocaleString();
  const trialEnd = new Date(res?.data?.trial_ends_at).toLocaleString();
  const subscriptionStart = new Date(
    res?.data?.subscription?.purchased_at
  ).toLocaleString();
  const subscriptionEnd = new Date(
    res?.data?.subscription?.expiration_time
  ).toLocaleString();
  const restorePurchase = res?.data?.subscription?.auto_renew
    ? "Açık"
    : "Kapalı";
  const commentStatus = res?.data?.app_rated ? "✅" : "❌";
  const subscriptionStatus = res?.data?.status;
  const spammer = res?.data?.spammer;

  const className =
    subscriptionStatus === "subscriber"
      ? "subscriber"
      : "expired"
      ? "expired"
      : "FRAUD BANNED"
      ? "expired"
      : "INSULT BANNED"
      ? "expired"
      : "grace_period"
      ? "grace"
      : "trial"
      ? "grace"
      : "Bilgi Bulunamadı";

  if (subscriptionStatus == "FRAUD BANNED") {
    document.querySelector(".canlidestek").style.backgroundColor = "#ae0000";
  }
  if (subscriptionStatus == "INSULT BANNED") {
    document.querySelector(".canlidestek").style.backgroundColor = "#ae0000";
  }
  if (spammer) {
    document.querySelector(".canlidestek").style.backgroundColor = "#ae0000";
  }

  return `
    <div class="abonelik">
      <div class="abonelik-title ${className}">${subscriptionStatus}</div>
      <div class="abonelik-bilgi">
        <div class="standart-title">Deneme Başlangıç</div>
        <div id="trial_starts" class="standart-text">${trialStart}</div>
      </div>
      <div class="abonelik-bilgi">
        <div class="standart-title">Deneme Bitiş</div>
        <div id="trial_ends" class="standart-text">${trialEnd}</div>
      </div>
      <div class="abonelik-bilgi">
        <div class="standart-title">Abonelik Başlangıç</div>
        <div id="sub_start" class="standart-text">${subscriptionStart}</div>
      </div>
      <div class="abonelik-bilgi">
        <div class="standart-title">Abonelik Bitiş</div>
        <div id="sub_ends" class="standart-text">${subscriptionEnd}</div>
      </div>
      <div class="abonelik-bilgi">
        <div class="standart-title">Abonelik Yenileme</div>
        <div id="sub_renews" class="standart-text">${restorePurchase}</div>
      </div>
      <div class="abonelik-bilgi">
        <div class="standart-title">Yorum durumu</div>
        <div id="app_rated" class="standart-text">${commentStatus}</div>
      </div>
    </div>
    `;
};
const User = (res, uuid) => {
  const Image = document.querySelector(".user-pic").cloneNode(true);
  const Location = document.querySelector(".user-location").cloneNode(true);
  const Email = uuid;
  const Link =
    "https://panel.appmob.pw/lightpanel/resources/devices/" + res.data.id;

  return `
  <div class="canlidestek-user">
    <a href="${Link}" class="user-imagee" id="open-in-panel2" target="_blank">${Image.innerHTML}</a>
    <a href="${Link}" class="location" id="open-in-panel" target="_blank">${Location.innerHTML}</a>
    <a class="user-id" id="user-id" target="_blank">${Email}</a>
  </div>
`;
};
const QRCode = (res) => {
  function message(paired) {
    if (paired) {
      return qrLinkText[locale] ?? qrLinkText["en"];
    } else {
      return whyQR[locale] ?? whyQR["en"];
    }
  }

  const qrLinkText = {
    en: `Your QR code link is below.`,
    tr: `QR kod bağlantınız aşağıdadır.`,
    id: `Tautan kode QR Anda ada di bawah.`,
    ms: `Pautan kod QR anda ada di bawah.`,
    de: `Ihr QR-Code-Link ist unten.`,
    fr: `Votre lien QR code est ci-dessous.`,
    it: `Il tuo link al codice QR è sotto.`,
    es: `El enlace de su código QR se encuentra a continuación.`,
    pt: `O link do código QR está abaixo.`,
    ar: `رابط رمز الاستجابة السريعة الخاص بك أدناه.`,
    ru: `Ссылка на ваш QR-код находится ниже.`,
  };
  const whyQR = {
    en: `Due to the latest privacy update of WhatsApp, it is not possible to follow the people you do not interact with (Messaging and Voice Call). However, by scanning your QR Code, the people with whom you have chatted or made a voice call will continue to be actively followed.`,
    tr: `WhatsApp'ın son gizlilik güncellemesi nedeniyle etkileşimde bulunmadığınız (Mesajlaşma ve Sesli Arama) kişileri takip etmeniz mümkün değildir. Ancak QR Kodunuzu okutarak sohbet ettiğiniz veya sesli arama yaptığınız kişiler aktif olarak takip edilmeye devam edecektir.`,
    id: `Karena pembaruan privasi WhatsApp terbaru, Anda tidak dapat mengikuti orang yang tidak berinteraksi dengan Anda (Pesan dan Panggilan Suara). Namun, dengan memindai Kode QR Anda, orang yang Anda ajak mengobrol atau melakukan panggilan suara akan terus diikuti secara aktif.`,
    ms: `Disebabkan kemas kini privasi terkini WhatsApp, anda tidak boleh mengikuti orang yang anda tidak berinteraksi (Mesej dan Panggilan Suara). Walau bagaimanapun, dengan mengimbas Kod QR anda, orang yang anda telah bersembang atau membuat panggilan suara akan terus diikuti secara aktif.`,
    de: `Aufgrund des neuesten Datenschutz-Updates von WhatsApp ist es nicht möglich, Personen zu folgen, mit denen Sie nicht interagieren (Messaging und Voice Call). Durch das Scannen Ihres QR-Codes werden die Personen, mit denen Sie gechattet oder einen Sprachanruf getätigt haben, jedoch weiterhin aktiv verfolgt.`,
    fr: `En raison de la dernière mise à jour de confidentialité de WhatsApp, il n'est pas possible de suivre les personnes avec lesquelles vous n'interagissez pas (Messagerie et Appel vocal). Cependant, en scannant votre QR Code, les personnes avec qui vous avez discuté ou passé un appel vocal continueront d'être activement suivies.`,
    it: `A causa dell'ultimo aggiornamento sulla privacy di WhatsApp, non è possibile seguire le persone con cui non si interagisce (messaggi e chiamate vocali). Tuttavia, scansionando il tuo QR Code, le persone con cui hai chattato o effettuato una chiamata vocale continueranno ad essere seguite attivamente.`,
    es: `Debido a la última actualización de privacidad de WhatsApp, no es posible seguir a las personas con las que no interactúas (Mensajería y Llamada de voz). Sin embargo, al escanear su código QR, las personas con las que ha chateado o realizado una llamada de voz seguirán siendo seguidas activamente.`,
    pt: `Devido à última atualização de privacidade do WhatsApp, não é possível seguir as pessoas com quem você não interage (mensagens e chamadas de voz). No entanto, ao escanear seu QR Code, as pessoas com quem você conversou ou fez uma chamada de voz continuarão a ser seguidas ativamente.`,
    ar: `نظرًا لتحديث الخصوصية الأخير لتطبيق WhatsApp ، لا يمكن متابعة الأشخاص الذين لا تتفاعل معهم (المراسلة والمكالمات الصوتية). ومع ذلك ، من خلال مسح رمز الاستجابة السريعة الخاص بك ضوئيًا ، سيستمر متابعة الأشخاص الذين تحدثت معهم أو أجريت مكالمة صوتية بنشاط.`,
    ru: `Из-за последнего обновления конфиденциальности WhatsApp невозможно следить за людьми, с которыми вы не взаимодействуете (обмен сообщениями и голосовой вызов). Однако при сканировании вашего QR-кода люди, с которыми вы общались в чате или совершали голосовой вызов, будут по-прежнему активно отслеживаться.`,
  };

  let componentLoader = document.querySelector(".qrcodestatus");

  if (!componentLoader) {
    setTimeout(function () {
      QRCode(res);
    }, 500);
  } else {
    if (res.data.qr_paired) {
      componentLoader.classList.add("active");
    }
    componentLoader.addEventListener("click", () => {
      sendMessage(
        message(res.data.qr_paired) +
          "\n" +
          `
----------------------------------------------------
👉 ${res.data.qr_link} 👈
----------------------------------------------------
      `
      );
    });
  }
  return `
    <div class="qrcodestatus">
        <div class="qrcodestatus_qr">
          <svg
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            xmlns:xlink="http://www.w3.org/1999/xlink"
            x="0px"
            y="0px"
            viewBox="0 0 1000 1000"
            enable-background="new 0 0 1000 1000"
            xml:space="preserve"
          >
            <metadata>
              Svg Vector Icons : http://www.onlinewebfonts.com/icon
            </metadata>
            <g>
              <path
                d="M535,990H605v-70.1H535V990z M395,395V10H10v385h70.1V465h70.1V395H395z M80.1,325.1v-245h245v245H80.1z M150,255h105V150H150V255z M605,10v385h385V10H605z M919.9,325.1h-245v-245h245V325.1z M850,150H745v105h105V150z M255,745H150v105h105V745z M10,535h70.1v-70.1H10V535z M150,465v70.1H220V465H150z M220,605H10v385h385V605H290V535h-70.1V605H220z M325.1,674.9v245h-245v-245H325.1z M535,45h-70.1v105H535V45z M535,220h-70.1v70.1H535V220z M674.9,465h-70.1h-70.1V360h-70.1v105H290v70.1h174.9H535H605v70.1h70.1v-70.1V465H674.9z M745,674.9v-70.1h-70.1v70.1H745z M535,605h-70.1v105H535V605z M465,780v140h70.1V780H465z M605,919.9h70.1V710H605V919.9z M815.1,674.9H990v-70.1H815.1V674.9z M919.9,535H990v-70.1h-70.1V535z M885,465H745v70.1h140V465z M745,780h70.1v-70.1H745V780z M919.9,780h-35V850H955V780h35v-70.1h-70.1V780z M745,850v70.1h70.1V850H745z M815.1,990H990v-70.1H815.1V990z"
              />
            </g>
          </svg>
        </div>
        <div class="qrcodestatus_text positive">QR kod okutulmuş</div>
        <div class="qrcodestatus_text negative">QR kod okutulmamış</div>
      </div>
    `;
};
const Locales = (res) => {
  const languages = [
    ["en", "English"],
    ["tr", "Türkçe"],
    ["ru", "Rusça"],
    ["de", "Almanca"],
    ["ar", "Arapça"],
    ["it", "İtalyanca"],
    ["fr", "Fransızca"],
    ["pt", "Portekizce"],
    ["es", "İspanyolca"],
    ["id", "Indonesia"],
    ["ms", "Malezya"],
  ];
  let componentLoader = document.querySelector("#location-select");

  if (!componentLoader) {
    setTimeout(function () {
      Locales(res);
    }, 500);
  } else {
    locale = res.data.locale.split("-")[0].split("_")[0];
    componentLoader.value = locale;

    componentLoader.addEventListener("change", (e) => {
      locale = e.target.value;
    });
  }

  return `
  <div class="row">
    <div class="col-md-12">
      <select name="location-select" id="location-select">
        ${languages.map((item, index) => {
          return `<option key="${item[index]}" value="${item[0]}">${item[1]}</option>`;
        })}
      </select>
    </div>
  </div>
  `;
};
const FastMessages = (res, uuid) => {
  const subscriptionInfo = {
    en: (data) => {
      var text = {
        text1: "Your subscription information is as follows.",
        text2: "Subscription start date : ",
        text3: "Subscription expiration date : ",
        text4: "Trial start date : ",
        text5: "Trial end date : ",
        text6: "Automatic renewal : ",
        text7: "✅",
        text8: "❌",
        text9: "Your Trial Version information is as follows.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */
      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    tr: (data) => {
      var text = {
        text1: "Abonelik bilgileriniz aşağıdaki gibidir.",
        text2: "Abonelik başlangıç tarihi : ",
        text3: "Abonelik bitiş tarihi : ",
        text4: "Deneme sürümü başlangıç tarihi: ",
        text5: "Deneme sürümü bitiş tarihi : ",
        text6: "Otomatik Yenileme : ",
        text7: "✅",
        text8: "❌",
        text9: "Deneme Sürümü bilgileriniz aşağıdaki gibidir.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */
      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    id: (data) => {
      var text = {
        text1: "Informasi langganan Anda adalah sebagai berikut.",
        text2: "Tanggal mulai berlangganan:",
        text3: "Tanggal kedaluwarsa langganan: ",
        text4: "Tanggal mulai percobaan: ",
        text5: "Tanggal akhir uji coba: ",
        text6: "Perpanjangan otomatis: ",
        text7: "✅",
        text8: "❌",
        text9: "Informasi Versi Percobaan Anda adalah sebagai berikut.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */
      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    ms: (data) => {
      var text = {
        text1: "Maklumat langganan anda adalah seperti berikut.",
        text2: "Tarikh mula langganan: ",
        text3: "Tarikh tamat tempoh langganan: ",
        text4: "Tarikh mula percubaan: ",
        text5: "Tarikh tamat percubaan: ",
        text6: "Pembaharuan automatik: ",
        text7: "✅",
        text8: "❌",
        text9: "Maklumat Versi Percubaan anda adalah seperti berikut.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */
      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    de: (data) => {
      var text = {
        text1: "Ihre Abonnementinformationen lauten wie folgt.",
        text2: "Startdatum des Abonnements : ",
        text3: "Ablaufdatum des Abonnements : ",
        text4: "Startdatum der Testversion : ",
        text5: "Enddatum der Testversion : ",
        text6: "Automatische Erneuerung : ",
        text7: "✅",
        text8: "❌",
        text9: "Ihre Testversionsinformationen lauten wie folgt.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */

      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    fr: (data) => {
      var text = {
        text1: "Les informations de votre abonnement sont les suivantes.",
        text2: "Date de début de l'abonnement : ",
        text3: "Date d'expiration de l'abonnement : ",
        text4: "Date de début d'essai : ",
        text5: "Date de fin d'essai : ",
        text6: "Renouvellement automatique : ",
        text7: "✅",
        text8: "❌",
        text9: "Les informations de votre version d'essai sont les suivantes.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */

      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    it: (data) => {
      var text = {
        text1: "Le informazioni sull'abbonamento sono le seguenti.",
        text2: "Data di inizio abbonamento : ",
        text3: "Data di scadenza dell'abbonamento : ",
        text4: "Data di inizio della prova : ",
        text5: "Data di fine prova : ",
        text6: "Rinnovo automatico : ",
        text7: "✅",
        text8: "❌",
        text9: "Le informazioni sulla versione di prova sono le seguenti.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */

      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    es: (data) => {
      var text = {
        text1: "La información de su suscripción es la siguiente.",
        text2: "Fecha de inicio de la suscripción : ",
        text3: "Fecha de vencimiento de la suscripción : ",
        text4: "Fecha de inicio del ensayo : ",
        text5: "Fecha de finalización del ensayo : ",
        text6: "Renovación Automática : ",
        text7: "✅",
        text8: "❌",
        text9: "La información de su versión de prueba es la siguiente.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */

      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    pt: (data) => {
      var text = {
        text1: "Suas informações de assinatura são as seguintes.",
        text2: "Data de início da assinatura : ",
        text3: "Data de expiração da assinatura : ",
        text4: "Data de início do teste : ",
        text5: "Data de término do teste : ",
        text6: "Renovação automática : ",
        text7: "✅",
        text8: "❌",
        text9: "As informações da sua versão de avaliação são as seguintes.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */

      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    ar: (data) => {
      var text = {
        text1: "معلومات اشتراكك على النحو التالي.",
        text2: "تاريخ بدء الاشتراك : ",
        text3: "تاريخ انتهاء الاشتراك : ",
        text4: "تاريخ بدء المحاكمة : ",
        text5: "تاريخ انتهاء النسخة التجريبية : ",
        text6: "تجديد تلقائي : ",
        text7: "✅",
        text8: "❌",
        text9: "معلومات الإصدار التجريبي الخاص بك هي كما يلي.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */

      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
    ru: (data) => {
      var text = {
        text1: "Ваша информация о подписке выглядит следующим образом.",
        text2: "Дата начала подписки : ",
        text3: "Срок действия подписки : ",
        text4: "Дата начала пробного периода : ",
        text5: "Дата окончания пробного периода : ",
        text6: "Автоматическое продление : ",
        text7: "✅",
        text8: "❌",
        text9: "Информация о пробной версии выглядит следующим образом.",
      };
      /**
       Hello, all apps in the store have been interrupted due to the latest update of WhatsApp.
       We fixed the issues and the app is up and running.
       Thank you for your understanding and patience and we deeply apologize for the downtime.
       */

      if (data.subscription) {
        return `${
          text.text1 +
          "\n" +
          text.text2 +
          "\n" +
          moment
            .tz(data.subscription.purchased_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text3 +
          "\n" +
          moment
            .tz(data.subscription.expiration_time, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text6 +
          (data.subscription.auto_renew ? text.text7 : text.text8)
        }`;
      } else {
        return `${
          text.text9 +
          "\n" +
          text.text4 +
          "\n" +
          moment
            .tz(data.trial_starts_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss") +
          "\n" +
          text.text5 +
          "\n" +
          moment
            .tz(data.trial_ends_at, data.timezone)
            .format("DD/MM/YYYY - HH:mm:ss")
        }`;
      }
    },
  };
  const rateUs = {
    en: "We have a small request from you.😇If you are satisfied with us, you will support us by writing a comment and rating us on the app store.✍\nThank you very much for this behavior.😍",
    tr: "Sizden küçük bir ricamız var.😇Bizden memnun kaldıysanız uygulama mağazasından yorum yazarak ve puan vererek bize destek olursunuz.✍\nBu davranışın için çok teşekkür ederim.😍",
    id: "Kami memiliki permintaan kecil dari Anda.😇Jika Anda puas dengan kami, Anda akan mendukung kami dengan menulis komentar dan memberi peringkat pada kami di app store.✍Terima kasih banyak atas perilaku ini.😍",
    ms: "Kami mempunyai sedikit permintaan daripada anda.😇Jika anda berpuas hati dengan kami, anda akan menyokong kami dengan menulis ulasan dan menilai kami di gedung aplikasi.✍Terima kasih banyak atas tingkah laku ini.😍",
    de: "Wir haben eine kleine Bitte von Ihnen.😇Wenn Sie mit uns zufrieden sind, unterstützen Sie uns, indem Sie einen Kommentar schreiben und uns im App Store bewerten.✍\nVielen Dank für dieses Verhalten.😍",
    fr: "Nous avons une petite demande de votre part.😇Si vous êtes satisfait de nous, vous nous soutiendrez en écrivant un commentaire et en nous notant sur l'App Store.✍\nMerci beaucoup pour ce comportement.😍",
    it: "Abbiamo una piccola richiesta da parte tua.😇Se sei soddisfatto di noi, ci sosterrai scrivendo un commento e valutandoci sull'app store.✍Grazie mille per questo comportamento.😍",
    es: "Tenemos una pequeña solicitud tuya.😇Si estás satisfecho con nosotros, nos apoyarás escribiendo un comentario y calificándonos en la tienda de aplicaciones.✍\nMuchas gracias por este comportamiento.😍",
    pt: "Temos um pequeno pedido seu.😇Se você está satisfeito conosco, você nos apoiará escrevendo um comentário e nos avaliando na loja de aplicativos.✍\nMuito obrigado por este comportamento.😍",
    ar: "😍شكرا جزيلا لك على هذا السلوك.\n✍ لدينا طلب صغير منك.😇 إذا كنت راضيًا عنا ، فستدعمنا من خلال كتابة تعليق وتقييمنا على متجر التطبيقات. ",
    ru: "У нас есть небольшая просьба от вас.😇Если вы довольны нами, вы поддержите нас, написав комментарий и оценив нас в магазине приложений.✍Большое спасибо за такое поведение.😍",
  };
  const fastMessages = {
    en: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1:
          "Currently, the following profiles are being tracked successfully:",
        text2: "We are waiting for a 'Token' from the contacts below:",
        text3: `
      In the QR code scanning process, we will only receive a 'token' information needed to start the tracking.
  
      Token will be created automatically when you have interacted with the contact via chat or voice call. Your contact needs to respond. NOTE: You can follow the people who sent you a message in last 3 weeks.
  
      After this process your tracking will start please wait for a while.`,
        text4:
          "ℹ️ It takes about 30 minutes for new numbers to start tracking.",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    fr: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1: "Actuellement, les profils suivants sont suivis avec succès :",
        text2: "Nous attendons un 'Token' des contacts ci-dessous :",
        text3: `
      Dans le processus de numérisation du code QR, nous ne recevrons qu'une information «token» nécessaire pour démarrer le suivi.
  
      Le jeton sera créé automatiquement lorsque vous aurez interagi avec le contact via le chat ou l'appel vocal. Votre contact doit répondre.
  
      Après ce processus, votre suivi commencera, veuillez patienter un moment. REMARQUE : Vous pouvez suivre les personnes qui vous ont envoyé un message au cours des 3 dernières semaines.`,
        text4:
          "ℹ️ Il faut environ 30 minutes pour que les nouveaux numéros commencent à être suivis.",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    tr: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1: "Şu anda aşağıdaki profiller başarıyla takip ediliyor:",
        text2: "Aşağıdaki kişilerden 'Token' bekliyoruz:",
        text3: `
      QR kod tarama işleminde, yalnızca izlemeye başlamak için gerekli olan bir 'token' bilgisi alacağız.
  
      Kişiyle sohbet veya sesli arama yoluyla etkileşime geçtiğinizde token otomatik olarak oluşturulacaktır. Kişinizin yanıt vermesi gerekiyor.
  
      Bu işlemin ardından takibiniz başlayacaktır, lütfen biraz bekleyiniz. NOT: Son 3 hafta içerisinde size mesaj gönderen kişileri takip edebilirsiniz.`,
        text4:
          "ℹ️ Yeni numaraların izlemeye başlaması tahminen 30 dakika sürer.",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    id: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1: "Saat ini, profil berikut berhasil dilacak:",
        text2: "Kami menunggu 'Token' dari kontak di bawah ini:",
        text3: `
      Dalam proses pemindaian kode QR, kami hanya akan menerima informasi 'token' yang diperlukan untuk memulai pelacakan.
  
      Token akan dibuat secara otomatis ketika Anda telah berinteraksi dengan kontak tersebut melalui obrolan atau panggilan suara. Kontak Anda perlu merespons.
  
      Setelah proses ini pelacakan Anda akan dimulai harap tunggu beberapa saat. CATATAN: Anda dapat mengikuti orang yang mengirimi Anda pesan dalam 3 minggu terakhir.`,
        text4: "ℹ️ Dibutuhkan sekitar 30 menit agar nomor baru mulai melacak.",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    ms: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1: "Pada masa ini, profil berikut berjaya dijejaki:",
        text2: "Kami sedang menunggu 'Token' daripada kenalan di bawah:",
        text3: `
      Dalam proses pengimbasan kod QR, kami hanya akan menerima maklumat 'token' yang diperlukan untuk memulakan penjejakan.
  
      Token akan dibuat secara automatik apabila anda telah berinteraksi dengan kenalan melalui sembang atau panggilan suara. Kenalan anda perlu membalas.
  
      Selepas proses ini penjejakan anda akan bermula sila tunggu sebentar. NOTA: Anda boleh mengikuti orang yang menghantar mesej kepada anda dalam 3 minggu lepas.`,
        text4:
          "ℹ️ Ia mengambil masa kira-kira 30 minit untuk nombor baharu mula dijejaki.",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    de: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1: "Derzeit werden die folgenden Profile erfolgreich verfolgt:",
        text2: "Wir warten auf einen 'Token' von den folgenden Kontakten:",
        text3: `
      Beim Scannen des QR-Codes erhalten wir nur eine „Token“-Information, die zum Starten des Trackings erforderlich ist.
  
      Das Token wird automatisch erstellt, wenn Sie mit dem Kontakt per Chat oder Sprachanruf interagiert haben. Ihr Kontakt muss antworten.
  
      Nach diesem Vorgang beginnt Ihr Tracking, bitte warten Sie eine Weile. HINWEIS: Sie können den Personen folgen, die Ihnen in den letzten 3 Wochen eine Nachricht gesendet haben.`,
        text4:
          "ℹ️ Es dauert ungefähr 30 Minuten, bis die Verfolgung neuer Nummern beginnt.",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    ar: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1: "حاليًا ، يتم تتبع الملفات الشخصية التالية بنجاح",
        text2: "نحن في انتظار 'رمز' من جهات الاتصال أدناه:",
        text3: `في عملية مسح رمز الاستجابة السريعة ، سوف نتلقى فقط معلومات "الرمز المميز" اللازمة لبدء التتبع.
  
      سيتم إنشاء الرمز تلقائيًا عندما تتفاعل مع جهة الاتصال عبر الدردشة أو المكالمة الصوتية. يحتاج الاتصال الخاص بك إلى الرد.
  
      بعد هذه العملية سيبدأ التتبع الخاص بك ، يرجى الانتظار لفترة من الوقت. يمكنك متابعة الأشخاص الذين أرسلت لك رسالة في الأسابيع الثلاثة الماضية`,
        text4:
          "ℹ️ يستغرق الأمر حوالي 30 دقيقة حتى تبدأ الأرقام الجديدة في التتبع.",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    es: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1:
          "Actualmente, los siguientes perfiles están siendo rastreados con éxito",
        text2: "Estamos esperando un 'Token' de los siguientes contactos:",
        text3: `
      En el proceso de escaneo del código QR, solo recibiremos la información de un 'token' necesaria para iniciar el seguimiento.
  
      El token se creará automáticamente cuando haya interactuado con el contacto a través de chat o llamada de voz. Su contacto necesita responder.
  
      Después de este proceso, comenzará su seguimiento, espere un momento. NOTA: Puedes seguir a las personas que te enviaron un mensaje en las últimas 3 semanas.`,
        text4:
          "ℹ️ Los números nuevos tardan unos 30 minutos en comenzar a rastrearse.",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    ru: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1: "В настоящее время успешно отслеживаются следующие профили",
        text2: "Ждем «Токен» от контактов ниже:",
        text3: `
      В процессе сканирования QR-кода мы получим только информацию о «токенах», необходимую для начала отслеживания.
  
      Токен будет создан автоматически, когда вы взаимодействуете с контактом через чат или голосовой вызов. Ваш контакт должен ответить.
  
      После этого процесса ваше отслеживание начнется, пожалуйста, подождите некоторое время. ПРИМЕЧАНИЕ. Вы можете подписаться на людей, которые отправили вам сообщение за последние 3 недели.`,
        text4: "ℹ️ Отслеживание новых номеров занимает около 30 минут. ",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    it: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1:
          "Attualmente, i seguenti profili vengono tracciati correttamente",
        text2: "Stiamo aspettando un 'Token' dai contatti di seguito:",
        text3: `
      Nel processo di scansione del codice QR, riceveremo solo un'informazione "token" necessaria per avviare il tracciamento.
  
      Il token verrà creato automaticamente dopo aver interagito con il contatto tramite chat o chiamata vocale. Il tuo contatto deve rispondere.
  
      Dopo questo processo inizierà il monitoraggio, attendere qualche istante. NOTA: puoi seguire le persone che ti hanno inviato un messaggio nelle ultime 3 settimane.`,
        text4:
          "ℹ️ Occorrono circa 30 minuti perché i nuovi numeri inizino a tracciare. ",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
    pt: (contactsValidText, contactsInvalidText) => {
      var text = {
        text1: "Atualmente, os seguintes perfis são rastreados corretamente",
        text2: "Aguardamos um 'Token' dos contatos abaixo:",
        text3: `
      No processo de digitalização do código QR, receberemos apenas uma informação 'token' necessária para iniciar o rastreamento.
  
      O token será criado automaticamente quando você interagir com o contato via chat ou chamada de voz. Seu contato precisa responder.
  
      Após esse processo seu rastreamento será iniciado aguarde um pouco. NOTA: Você pode seguir as pessoas que lhe enviaram uma mensagem nas últimas 3 semanas.`,
        text4:
          "ℹ️ Demora cerca de 30 minutos para que novos números comecem a ser rastreados. ",
      };
      return `
              ${contactsValidText ? text.text1 + "\n" + contactsValidText : ""}
              ${
                contactsInvalidText
                  ? text.text2 + "\n" + contactsInvalidText + "\n" + text.text3
                  : ""
              }
              `;
    },
  };

  const subscriptionInfoButton = document.querySelector("#subscriptioninfo");
  const rateUsButton = document.querySelector("#rateus");
  const fastMessageButton = document.querySelector("#fastmeassage");
  const restorePurchaseButton = document.querySelector("#restorebutton");

  if (
    !subscriptionInfoButton &&
    !rateUsButton &&
    !fastMessageButton &&
    !restorePurchaseButton
  ) {
    setTimeout(function () {
      FastMessages(res, uuid);
    }, 500);
  } else {
    subscriptionInfoButton.addEventListener("click", () => {
      let subscriptionMessage =
        subscriptionInfo[locale] ?? subscriptionInfo["en"];
      sendMessage(subscriptionMessage(res.data));
    });
    rateUsButton.addEventListener("click", () => {
      let rateUsMessage = rateUs[locale] ?? rateUs["en"];
      sendMessage(rateUsMessage);
    });
    fastMessageButton.addEventListener("click", () => {
      let fastMessage = fastMessages[locale] ?? fastMessages["en"];
      const contactsValid = res.data.contacts.filter(
        (contact) => contact.tracked
      );
      const contactsInvalid = res.data.contacts.filter(
        (contact) => !contact.tracked
      );
      const contactsValidText = contactsValid
        .map((contact) => {
          return `✅ ` + "/" + contact.number + "/" + " (" + contact.name + ")";
        })
        .join("\n");

      const contactsInvalidText = contactsInvalid
        .map((contact) => {
          return `🔄 ` + "/" + contact.number + "/" + " (" + contact.name + ")";
        })
        .join("\n");
      sendMessage(fastMessage(contactsValidText, contactsInvalidText).trim());
    });
    restorePurchaseButton.addEventListener("click", () => {
      fetch(
        "https://panel.appmob.pw/cli/gather-info/device/" + uuid + "/restore"
      )
        .then((res) => {
          return res.json();
        })
        .then((res) => {
          alert(res.message);
        })
        .catch((err) => {
          console.log(err);
        });
    });
  }

  return `
  <div class="row">
    <div class="col-md-6">
      <div id="subscriptioninfo" class="buttonn">Subscription İnfo</div>
    </div>
    <div class="col-md-6">
      <div id="rateus" class="buttonn">Rate Us</div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-6">
      <div id="fastmeassage" class="buttonn">Fast Message</div>
    </div>
    <div class="col-md-6">
      <div id="restorebutton" class="buttonn restorebutton">
        Restore Purchase
      </div>
    </div>
  </div>
  `;
};
const Contacts = (res) => {
  const switchButton = document.querySelector("#switch");
  const contacts = document.querySelector("#contacts");
  const deletedContacts = document.querySelector("#deleted-contacts");

  let switchStatus = true;

  if (!switchButton && !contacts && !deletedContacts) {
    setTimeout(function () {
      Contacts(res);
    }, 500);
  } else {
    switchButton.addEventListener("click", () => {
      if (switchStatus) {
        contacts.classList.remove("is-active");
        deletedContacts.classList.add("is-active");
        switchButton.innerHTML = "Aktif Numaraları Göster";
      } else {
        contacts.classList.add("is-active");
        deletedContacts.classList.remove("is-active");
        switchButton.innerHTML = "Silinmiş Numaraları Göster";
      }
      switchStatus = !switchStatus;
    });

    for (const contact of res.data.contacts) {
      contacts.innerHTML += `
        <li class="${!contact.tracked && "expired"}">
          <div class="item-veri">
            <div class="contact-left">
              <div class="status">
                ${contact.tracked ? "✅️" : "❌"}
              </div>
              <a href="https://wa.me/${
                contact.number
              }" class="number" target="_blank">
                ${contact.number}
              </a>
              <div class="contact-right">
                <div class="name">
                  ${contact.name}
                </div>
              </div>
            </div>
            <a class="contact-delete" target="_blank">
              ${contact.blacklist ? "☠️" : "🔍"}
            </a>
          </div>
          <div class="name-description">
            ${contact.description} <br/>
            Online : ${contact.notify_online ? "🟢" : "🔴"} 
            Offline : ${contact.notify_offline ? "🟢" : "🔴"} 
            
          </div>
        </li>
      `;
    }
    for (const contact of res.data.contacts_deleted) {
      deletedContacts.innerHTML += `
        <li class="${!contact.tracked && "expired"}">
          <div class="item-veri">
            <div class="contact-left">
              <div class="status">
                ${contact.tracked ? "✅️" : "❌"}
              </div>
              <a href="https://wa.me/${
                contact.number
              }" class="number" target="_blank">
                ${contact.number}
              </a>
              <div class="contact-right">
                <div class="name">
                  ${contact.name}
                </div>
              </div>
            </div>
            <a class="contact-delete" target="_blank">
              ${contact.blacklist ? "☠️" : "🔍"}
            </a>
          </div>
          <div class="name-description">
            ${contact.description} <br/>
          </div>
        </li>
      `;
    }
  }
  return `
    <div id="switch" class="buttonn">Silinmiş Numaraları Göster</div>
    <ul id="contacts" class="contacts is-active"></ul>
    <ul id="deleted-contacts" class="contacts"></ul>
    ${ContactDetails(res)}
  `;
};
function contactFiiling(contact) {
  $(".contact-name").text(contact.name);
  $(".contact-number").text(contact.number);
  $(".contact-number").attr("href", "https://wa.me/" + contact.number);
  $(".contact-tracking").text(contact.tracked ? "✅️ Takip Başarılı" : "❌");
  $(".contact-attached").text(
    contact.attached_at ? new Date(contact.attached_at).toLocaleString() : "---"
  );
  document
    .querySelectorAll(".contact-item")[5]
    .querySelector(".contact-item-detay").innerHTML = moment(
    contact.attached_at
  ).fromNow();
  $(".contact-created").text(
    contact.created_at ? new Date(contact.created_at).toLocaleString() : "---"
  );
  document
    .querySelectorAll(".contact-item")[6]
    .querySelector(".contact-item-detay").innerHTML = moment(
    contact.created_at
  ).fromNow();
  $(".contact-presence").text(
    contact.last_presence
      ? new Date(contact.last_presence).toLocaleString()
      : "---"
  );
  document
    .querySelectorAll(".contact-item")[3]
    .querySelector(".contact-item-detay").innerHTML = moment(
    contact.last_presence
  ).fromNow();
  $(".contact-lastonline").text(
    contact.last_online_at
      ? new Date(contact.last_online_at).toLocaleString()
      : "---"
  );
  document
    .querySelectorAll(".contact-item")[4]
    .querySelector(".contact-item-detay").innerHTML = moment(
    contact.last_online_at
  ).fromNow();
  $(".contact-service").text(contact.service_name);
  $(".contact-service").attr(
    "href",
    "https://panel.appmob.pw/lightpanel/resources/whatsapp-services/" +
      contact.service_name
  );
}
const ContactDetails = (res) => {
  const contactButtons = document.querySelectorAll(".contact-delete");
  const contactDetail = document.querySelector(".contact-detay");
  const overlay = document.querySelector(".overlay");

  if (!contactButtons && !contactDetail && !overlay) {
    setTimeout(function () {
      ContactDetails(res);
    }, 500);
  } else {
    contactButtons.forEach((item, index) => {
      item.addEventListener("click", () => {
        overlay.classList.add("is-active");
        contactDetail.classList.add("is-active");
        contactFiiling(res.data.contacts[index]);
      });
    });
    overlay?.addEventListener("click", () => {
      overlay.classList.remove("is-active");
      contactDetail.classList.remove("is-active");
    });
  }

  return `
    <div class="contact-detay">
      <div class="contact-header">
        <div class="contact-header-name">Contact Detail</div>
      </div>
      <div class="contact-body">
        <ul class="contact-list">
          <li class="contact-item">
            <div class="contact-item-name">Contact Name</div>
            <div class="contact-item-icerik contact-name"></div>
          </li>
          <li class="contact-item">
            <div class="contact-item-name">Number</div>
            <a
              href="#"
              target="_blank"
              class="contact-item-name bold contact-number"
            ></a>
          </li>
          <!-- <li class="contact-item"> <div class="contact-item-name">Notification Status</div> <span>Yenüz Yapılmadı</span> </li> -->
          <li class="contact-item">
            <div class="contact-item-name">Tracking</div>
            <div class="contact-item-name bold contact-tracking"></div>
          </li>
          <li class="contact-item">
            <div class="contact-item-name">Presence</div>
            <div class="contact-item-name bold contact-presence"></div>
            <div class="contact-item-detay"></div>
          </li>
          <li class="contact-item">
            <div class="contact-item-name">Last Online/Offline</div>
            <div class="contact-item-name bold contact-lastonline"></div>
            <div class="contact-item-detay"></div>
          </li>
          <li class="contact-item">
            <div class="contact-item-name">Attached At</div>
            <div class="contact-item-name bold contact-attached"></div>
            <div class="contact-item-detay">aaaaa</div>
          </li>
          <li class="contact-item">
            <div class="contact-item-name">Created At</div>
            <div class="contact-item-name bold contact-created"></div>
            <div class="contact-item-detay"></div>
          </li>
          <li class="contact-item">
            <div class="contact-item-name">Update Priority</div>
            <div class="contact-item-name bold contact-last">
              Update Priority
            </div>
          </li>
          <li class="contact-item">
            <div class="contact-item-name">Decide</div>
            <div class="contact-item-name bold contact-last">Decide</div>
          </li>
          <li class="contact-item">
            <div class="contact-item-name">Service Name</div>
            <a
              href=""
              target="_blank"
              class="contact-item-name bold contact-service"
              >2022-02-22 20:05:42</a
            >
          </li>
        </ul>
      </div>
    </div>
    <div class="overlay"></div>
  `;
};
const SendMail = (res, uuid) => {
  let mailInput = document.querySelector("#canlidestekmail");
  let mailButton = document.querySelector(".mailbutton");

  if (!mailInput && !mailButton) {
    setTimeout(function () {
      SendMail(res, uuid);
    }, 500);
  } else {
    mailInput.value = res.data.export_email;
    mailButton.addEventListener("click", () => {
      const email = mailInput.value;
      document.querySelector(".abonelik-overlay").classList.add("is-active");

      fetch(
        "https://panel.appmob.pw/cli/gather-info/device/" +
          uuid +
          "/export?email=" +
          email
      )
        .then((res) => {
          return res.json();
        })
        .then((res) => {
          document
            .querySelector(".abonelik-overlay")
            .classList.remove("is-active");
          console.log("Mail Gönderildi...");
        })
        .catch((err) => {
          document
            .querySelector(".abonelik-overlay")
            .classList.remove("is-active");
          console.log("Mail Gönderilemedi...", err);
        });
    });
  }

  return `
    <div class="mail">
      <input type="text" class="mailtext" name="" id="canlidestekmail" />
      <input type="button" class="mailbutton" value="Mail Gönder" />
    </div>
    <div class="abonelik-overlay">Mail Gönderiliyor Lütfen Bekleyiniz...</div>
    <br />
  `;
};
const SendNotify = (res, uuid) => {
  let notifyButton = document.querySelector(".notify-button");

  if (!notifyButton) {
    setTimeout(function () {
      SendNotify(res, uuid);
    }, 500);
  } else {
    notifyButton.addEventListener("click", () => {
      const subject = document.querySelector("#notifytitle").value;
      const body = document.querySelector("#notifytext").value;
      fetch(
        "https://panel.appmob.pw/cli/gather-info/device/" +
          uuid +
          "/push?subject=" +
          subject +
          "&body=" +
          body,
        { method: "POST" }
      )
        .then((res) => {
          return res.json();
        })
        .then((res) => {
          alert("Bildirim Gönderildi...");
        });
    });
  }

  return `
    <div class="testbildirimi">
      <div class="h4" style="color: white">Test Bildirimi At</div>
      <input
        type="text"
        name=""
        id="notifytitle"
        placeholder="Test Bildirimi Başlığı"
        style="
          width: 100%;
          margin-bottom: 10px;
          border-radius: 10px;
          padding: 5px 15px;
        "
      />
      <textarea
        placeholder="Test Bildirmi İçeriği"
        name=""
        id="notifytext"
        style="
          width: 100%;
          margin-bottom: 10px;
          border-radius: 10px;
          padding: 5px 15px;
        "
      ></textarea>
      <input
        type="button"
        value="Test Bildirimi Gönder"
        class="notify-button"
        style="
          width: 100%;
          margin-bottom: 10px;
          border-radius: 10px;
          padding: 5px 15px;
        "
      />
    </div>
    <br />
    <br />
    <br />
    <br />
  `;
};
const KeyPressAction = () => {
  function KeyPress(e) {
    var evtobj = window.event ? event : e;
    if (evtobj.keyCode == 55 && evtobj.shiftKey) {
      ember.__container__
        .lookup("service:live-translation")
        .setProperties({ dontTranslateThisMessage: 1 });
    }
  }
  document.onkeydown = KeyPress;

  function KeyPressEnter(e) {
    var evtobj = window.event ? event : e;
    if (
      (evtobj.keyCode == 13 && locale == "tr") ||
      (evtobj.keyCode == 13 && locale == "en")
    ) {
      setTimeout(function () {
        ember.__container__
          .lookup("service:live-translation")
          .setProperties({ dontTranslateThisMessage: 1 });
      }, 1000);
      console.log(locale);
    }
  }

  document.onkeydown = KeyPressEnter;
};
const design = (res, uuid) => {
  return `
    <div class="canlidestek">
      ${User(res, uuid)}
      ${AbonelikBilgileri(res)}
      ${QRCode(res)}
      ${Locales(res)}
      ${FastMessages(res, uuid)}
      ${Contacts(res)}
      ${SendMail(res, uuid)}
      ${SendNotify(res, uuid)}
    </div>
    ${KeyPressAction()}
  `;
};
const findMail = () => {
  const url = window.location.href;
  const ids = url.substring(url.lastIndexOf("/") + 1);
  const userData = `https://mdenizkaba.myfreshworks.com/crm/messaging/app/agent/inbox/conversation/fetch?appId=736259526219502&ids=${ids}&excludeCampaign=false&rand=1682678197637&limit=20`;
  fetch(userData)
    .then((response) => response.json())
    .then((data) => {
      let mail = data?.conversations[0].participants[1].email;
      connect(mail);
    })
    .catch((error) => {
      console.error(error);
    });
};
const reset = () => {
  const messagesBox = document.querySelector(".messages");
  messagesBox.onclick = () => {
    setTimeout(main, 1000);
  };
};
const main = () => {
  let pageLoader = document.querySelector(".user-meta-data");

  if (!pageLoader) {
    setTimeout(main, 500);
  } else {
    findMail();
    reset();
  }
};
const connect = (mail) => {
  const body = document.querySelector(".user-meta");

  let uuid = mail.substr(0, mail.indexOf("@"));

  fetch("https://panel.appmob.pw/cli/gather-info/device/" + uuid)
    .then((res) => {
      return res.json();
    })
    .then((res) => {
      body.innerHTML = design(res, uuid);
    })
    .catch((err) => {
      console.log(err);
    });
};

main();
