<script>
  import { Turnstile } from "svelte-turnstile";

  let selectedBank = "";
  let depositTimeLeft = 60; //seconds
  let totalDepositTimeLeft = 600; //seconds
  let requestingReqs = false;
  let randomRequestId = 0;
  let timerInterval = null;
  let totalTimerInterval = null;
  let endTime = 0;
  let showReqs = false;

  let randomCard = "2200 2080 1111 1111";
  let cardHolder = "Андрей Витальевич В.";

  function randomRequstIdGenerator() {
    randomRequestId =
      Math.floor(Math.random() * (999999999 - 111111111 + 1)) + 111111111;
  }
  randomRequstIdGenerator();

  function genRandomCard() {
    let r = [2200];
    for (let i = 0; i < 3; i++) {
      r.push(Math.floor(Math.random() * (8888 - 1111 + 1)) + 1111);
    }
    return r.join(" ");
  }

  function startTimer() {
    endTime = Math.floor(Math.random() * (58 - 47 + 1)) + 47;
    timerInterval = setInterval(() => {
      depositTimeLeft--;
      if (depositTimeLeft === endTime) {
        clearInterval(timerInterval);
        depositTimeLeft = 0;
        showReqs = true;
        randomCard = genRandomCard();
        startTotalTimer();
        requestingReqs = false;
        return;
      }
      if (depositTimeLeft < 0) {
        clearInterval(timerInterval);
        depositTimeLeft = 0;
        return;
      }
    }, 1000);
  }

  function stopTimer() {
    clearInterval(timerInterval);
    depositTimeLeft = 60;
  }

  function startTotalTimer() {
    // endTime = Math.floor(Math.random() * (58 - 47 + 1)) + 47;
    timerInterval = setInterval(() => {
      totalDepositTimeLeft--;
      if (totalDepositTimeLeft < 0) {
        clearInterval(totalTimerInterval);
        totalDepositTimeLeft = 0;
        return;
      }
    }, 1000);
  }

  function stopTotalTimer() {
    clearInterval(totalTimerInterval);
    totalDepositTimeLeft = 600;
  }

  let captchaVerified = false;
  let captchaValue = undefined;

  let checkCaptchaInterval = setInterval(() => {
    const form = document.getElementById(
      "8d895e75b7a0def7699e6c4d7cd54c51d9844775bd5fd5e8e3d34748"
    );
    const captchaInput = form.querySelector("input");
    if (captchaInput.value !== "") {
      captchaVerified = true;
      captchaValue = captchaInput.value;
    } else {
      captchaVerified = true;
      captchaValue = undefined;
    }
  }, 500);

  let showAlertQuit = false;

  let loadedFile = "";
</script>

<div
  class="fixed inset-0 bg-slate-950 w-full h-full flex justify-center items-center gap-4 text-white"
>
  <div class="flex flex-col w-[70%] gap-8">
    <div
      class="w-full flex h-16 justify-center items-center bg-slate-900 rounded-3xl"
    >
      <p class="text-xl">Заявка №{randomRequestId}</p>
    </div>
    <div class="flex w-full gap-16">
      <div class="flex flex-col w-full gap-8">
        <p class="text-3xl font-bold">Выберите банк</p>
        <div class="flex">
          <button
            on:click={() => {
              selectedBank = "sber";
            }}
            class={"w-full rounded-3xl flex items-center gap-8 ring-2 py-4 px-4 " +
              (selectedBank === "sber"
                ? "ring-indigo-600 bg-slate-900 cursor-default"
                : "ring-slate-600 hover:ring-slate-300")}
          >
            <div class="bg-transparent w-10 h-10 flex-shrink-0">
              <img src="media/sber-logo.png" alt="sber" />
            </div>
            <div class="w-full flex justify-center items-center pr-16">
              <p class="text-xl">Сбер</p>
            </div>
          </button>
        </div>
        <div class="flex w-full justify-center">
          <form id="8d895e75b7a0def7699e6c4d7cd54c51d9844775bd5fd5e8e3d34748">
            <Turnstile siteKey="0x4AAAAAAAdVbiLiWPGwxHjN" />
          </form>
        </div>
        {#if selectedBank === "sber" && captchaVerified}
          <button
            on:click={() => {
              if (requestingReqs || showReqs) {
                showAlertQuit = true;
              } else {
                requestingReqs = true;
                showReqs = false;
                depositTimeLeft = 60;
                startTimer();
              }
            }}
            class={(requestingReqs || showReqs
              ? "bg-slate-950 ring-indigo-800 hover:bg-slate-900"
              : "bg-indigo-800 hover:bg-indigo-700 ring-transparent") +
              " w-full font-semibold text-xl flex gap-1 justify-center items-center text-center p-4  rounded-3xl  transition-all duration-75 ring-2 ring-inset  focus:outline-none focus:ring-inset focus:ring-1 focus:ring-white"}
          >
            {requestingReqs || showReqs ? "Отмена" : "Запросить реквизиты"}
          </button>
          {#if requestingReqs}
            <div class="flex justify-center items-center w-full">
              <p>
                Реквизиты появятся не позже, чем через {Math.floor(
                  depositTimeLeft / 60
                ).toLocaleString("en-US", {
                  minimumIntegerDigits: 2,
                  useGrouping: false,
                }) +
                  ":" +
                  Math.floor(depositTimeLeft % 60).toLocaleString("en-US", {
                    minimumIntegerDigits: 2,
                    useGrouping: false,
                  })}
              </p>
            </div>
          {/if}
          {#if showReqs}
            <div class="w-full flex p-8 rounded-3xl bg-indigo-950">
              <div class="flex flex-col gap-2">
                <p class="text-lg">Номер карты для перевода</p>
                <div class="flex gap-4 justify-center items-center">
                  <p class="text-4xl font-bold">{randomCard}</p>
                  <button
                    class="relative w-11 h-10 p-2 rounded-full bg-indigo-900 group hover:bg-indigo-800"
                  >
                    <div
                      class="absolute bg-transparent ring-2 ring-white top-2 left-3 w-4 h-5 rounded-[3px]"
                    ></div>
                    <div
                      class="absolute bg-indigo-900 ring-2 ring-white top-3 group-hover:bg-indigo-800 left-4 w-4 h-5 rounded-[3px]"
                    ></div>
                  </button>
                </div>
                <p class="text-lg">Получатель: {cardHolder}</p>
                <p class="text-lg mt-4">
                  Время на оплату {Math.floor(
                    totalDepositTimeLeft / 60
                  ).toLocaleString("en-US", {
                    minimumIntegerDigits: 2,
                    useGrouping: false,
                  }) +
                    ":" +
                    Math.floor(totalDepositTimeLeft % 60).toLocaleString(
                      "en-US",
                      {
                        minimumIntegerDigits: 2,
                        useGrouping: false,
                      }
                    )}
                </p>
              </div>
            </div>
            <button on:click={()=>{
              document.getElementById('loaded-file').click();
            }}
            class={"bg-indigo-800 hover:bg-indigo-700 ring-transparent" +
              " w-full font-semibold text-xl flex gap-1 justify-center items-center text-center p-4  rounded-3xl  transition-all duration-75 ring-2 ring-inset  focus:outline-none focus:ring-inset focus:ring-1 focus:ring-white"}
            >Загрузить чек</button>
            <p class="text-xl font-semibold">Загружен файл: {loadedFile}</p>
            <button
              on:click={() => {}}
              disabled={loadedFile === ""}
              class={(false
                ? "bg-slate-950 ring-indigo-800 hover:bg-slate-900"
                : "bg-green-800 hover:bg-green-700 ring-transparent") +
                " w-full font-semibold text-xl flex gap-1 disabled:bg-slate-950 disabled:ring-2 disabled:ring-inset disabled:ring-red-800 justify-center items-center text-center p-4  rounded-3xl  transition-all duration-75 ring-2 ring-inset  focus:outline-none focus:ring-inset focus:ring-1 focus:ring-white"}
            >
              {"Я оплатил"}
            </button>
            <input on:change={(e)=>{
              loadedFile = e.target.files[0].name;
            }} id="loaded-file" type="file" hidden accept=".png, .jpg, .jpeg, .pdf">
          {/if}
        {/if}
      </div>
      <div class="flex w-full">
        <div
          class="flex flex-col w-full flex-grow-0 bg-slate-900 p-8 gap-2 h-[302px] rounded-3xl"
        >
          <div class="flex items-center justify-start gap-2 text-lg">
            <div class="w-2 h-2 bg-white rounded-full flex-shrink-0"></div>
            <p>Дождитесь выдачи реквизитов</p>
          </div>
          <div class="flex items-center justify-start gap-2 text-lg">
            <div class="w-2 h-2 bg-white rounded-full flex-shrink-0"></div>
            <p>Скопируйте реквизиты</p>
          </div>
          <div class="flex items-center justify-start gap-2 text-lg">
            <div class="w-2 h-2 bg-white rounded-full flex-shrink-0"></div>
            <p>Откройте приложение своего банка</p>
          </div>
          <div class="flex items-center justify-start gap-2 text-lg">
            <div class="w-2 h-2 bg-white rounded-full flex-shrink-0"></div>
            <p>
              Переведите <span class=" underline">точную сумму</span> на указанный
              реквизит
            </p>
          </div>
          <div class="flex items-center justify-start gap-2 text-lg">
            <div class="w-2 h-2 bg-white rounded-full flex-shrink-0"></div>
            <p>После успешного перевода нажмите "Я оплатил"</p>
          </div>
          <div class="flex items-center justify-start gap-2 text-lg mt-4">
            <button
              on:click={() => {
                showAlertQuit = true;
              }}
              class="bg-slate-900 ring-2 ring-slate-800 rounded-3xl hover:ring-red-800 p-2 px-8"
              >Отменить заявку</button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

{#if showAlertQuit}
  <div
    class="fixed bg-slate-950 inset-0 w-full h-full bg-opacity-70 flex justify-center items-center text-white"
  >
    <div
      class="flex flex-col p-8 relative bg-slate-950 rounded-3xl gap-8 max-w-[30%] ring-2 ring-slate-800"
    >
      <p class="font-semibold text-4xl">Отмена заявки</p>
      <p class="text-2xl text-red-100">
        Вы действительно хотите отменить заявку на пополнение?
      </p>
      <p class="text-xl">
        Если Вы уже оплатили эту заявку, то нажмите на кнопку "Я оплатил". При
        возникновении проблем с оплатой напишите нам в поддержку.
      </p>
      <div class="flex justify-end gap-8">
        <button
          on:click={() => {
            requestingReqs = false;
            showReqs = false;
            stopTimer();
            stopTotalTimer();
            showAlertQuit = false;
          }}
          class="text-xl p-4 bg-slate-950 ring-2 ring-slate-800 rounded-3xl hover:ring-red-800"
          >Да, отменить</button
        >
        <button
          on:click={() => {
            showAlertQuit = false;
          }}
          class="text-xl font-semibold p-4 bg-indigo-800 hover:bg-indigo-700 rounded-3xl px-8"
          >Нет</button
        >
      </div>
    </div>
  </div>
{/if}
