<!DOCTYPE html>
<html lang="ru">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate, max-age=0" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Загрузка проекта vMix</title>
    <link rel="icon" href="/static/smith.ico" type="image/x-icon">
    <link rel="stylesheet" href="/static/styles.css?v=20260421_1" />
  </head>
  <body>
    <div id="matrixLoader" class="matrix-loader active" aria-hidden="false">
      <canvas id="matrixCanvas" class="matrix-canvas"></canvas>
      <div class="matrix-content">
        <div class="matrix-title" id="matrixTitle">Загрузка vMix</div>
        <div class="matrix-status" id="matrixStatusText">Подготовка проекта к скачиванию...</div>
        <div style="margin-top: 18px;">
          <a href="{{ back_url }}" class="btn btn-secondary">Назад к игре</a>
        </div>
      </div>
    </div>

    <script>
      (function () {
        const statusText = document.getElementById("matrixStatusText");
        const titleEl = document.getElementById("matrixTitle");
        const loader = document.getElementById("matrixLoader");
        const canvas = document.getElementById("matrixCanvas");
        const ctx = canvas ? canvas.getContext("2d") : null;

        let matrixAnimationId = null;
        let drops = [];
        let fontSize = 16;
        let columns = 0;
        let lastTime = 0;
        const fps = 18;
        const interval = 1000 / fps;
        const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ@$%#*+=<>";

        function resizeCanvas() {
          if (!canvas || !ctx) return;
          canvas.width = window.innerWidth;
          canvas.height = window.innerHeight;
          columns = Math.floor(canvas.width / fontSize);
          drops = Array(columns).fill(1);
        }

        function drawMatrix(time = 0) {
          if (!canvas || !ctx) return;
          if (time - lastTime < interval) {
            matrixAnimationId = requestAnimationFrame(drawMatrix);
            return;
          }
          lastTime = time;
          ctx.fillStyle = "rgba(0, 0, 0, 0.08)";
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          ctx.fillStyle = "#00ff66";
          ctx.font = `${fontSize}px monospace`;
          for (let i = 0; i < drops.length; i++) {
            const text = chars[Math.floor(Math.random() * chars.length)];
            ctx.fillText(text, i * fontSize, drops[i] * fontSize);
            if (drops[i] * fontSize > canvas.height && Math.random() > 0.975) {
              drops[i] = 0;
            }
            drops[i]++;
          }
          matrixAnimationId = requestAnimationFrame(drawMatrix);
        }

        function setState(state, title, message) {
          if (loader) {
            loader.classList.remove("is-error", "is-success");
            if (state) loader.classList.add(state);
          }
          if (titleEl) titleEl.textContent = title || "";
          if (statusText) statusText.textContent = message || "";
        }

        async function startDownload() {
          try {
            setState("", "Загрузка vMix", "Формирование проекта...");

            const response = await fetch("{{ download_url }}", {
              method: "GET",
              credentials: "same-origin"
            });

            if (!response.ok) {
              let errText = "Не удалось скачать vMix проект";
              try {
                const errJson = await response.json();
                errText = errJson.error || errText;
              } catch (_) {}
              throw new Error(errText);
            }

            setState("", "Загрузка vMix", "Скачивание проекта...");

            const blob = await response.blob();
            let filename = "project.vmix";
            const disposition = response.headers.get("Content-Disposition");

            if (disposition) {
              let match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
              if (match && match[1]) {
                filename = decodeURIComponent(match[1]);
              } else {
                match = disposition.match(/filename="([^"]+)"/i);
                if (match && match[1]) {
                  filename = match[1];
                }
              }
            }

            const blobUrl = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = blobUrl;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            a.remove();

            setState("is-success", "Готово", "Проект vMix успешно скачан. Возвращаемся во вкладку «Игра»...");

            setTimeout(() => {
              window.URL.revokeObjectURL(blobUrl);
              window.location.href = "{{ back_url }}";
            }, 1200);
          } catch (error) {
            setState("is-error", "Ошибка загрузки", error.message || "Не удалось скачать проект vMix");
          }
        }

        window.addEventListener("resize", resizeCanvas);
        resizeCanvas();
        drawMatrix();
        startDownload();
      })();
    </script>
  </body>
</html>
