<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Download from PC — QRPorter</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <link rel="icon" href="{{ url_for('static', filename='assets/icon.png') }}" type="image/png" />
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" />
</head>
<body>
  <div class="wrap">
    <div class="card">
      <div class="head">
        <img src="{{ url_for('static', filename='assets/icon.png') }}" alt="QRPorter" />
        <h1>Download from PC</h1>
      </div>
      <p class="desc">Download the file shared from the computer to this device.</p>

      <div class="section">
        <div class="row">
          <div>
            <label>File</label>
            <div class="filename">{{ filename }}</div>
            <div class="hint">Tap the button below to start downloading.</div>
          </div>
        </div>

        <div class="actions">
          <button class="btn" id="btnDownload">Download</button>
        </div>

        <!-- Progress UI -->
        <div class="progress-wrap">
          <progress id="downloadProgress" value="0" max="100"></progress>
          <span id="downloadPercent" class="progress-label"></span>
        </div>

        <div id="status" class="status"></div>
      </div>

      <div class="footer">
        <span>QRPorter</span>
      </div>
    </div>
  </div>

  <script>
    const token = "{{ token }}";
    const filename = "{{ filename }}";
    const downloadUrl = `/download/${token}/${encodeURIComponent(filename)}`;

    const btn = document.getElementById("btnDownload");
    const statusEl = document.getElementById("status");
    const progressEl = document.getElementById("downloadProgress");
    const percentEl = document.getElementById("downloadPercent");

    function resetProgress() {
      progressEl.value = 0;
      progressEl.removeAttribute('data-indeterminate');
      percentEl.textContent = "";
    }

    function saveBlob(blob, name) {
      const a = document.createElement("a");
      const url = URL.createObjectURL(blob);
      a.href = url;
      a.download = name || "file";
      document.body.appendChild(a);
      a.click();
      a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
    }

    btn.addEventListener("click", async () => {
      resetProgress();
      statusEl.textContent = "Starting download…";
      statusEl.className = "status";
      btn.disabled = true;

      try {
        const res = await fetch(downloadUrl, { method: "GET" });
        if (!res.ok) {
          const txt = await res.text();
          statusEl.textContent = txt || "Download failed.";
          statusEl.className = "status err";
          btn.disabled = false;
          return;
        }

        const total = Number(res.headers.get("Content-Length")) || 0;
        if (!total) {
          // Indeterminate if size unknown
          progressEl.setAttribute('data-indeterminate', 'true');
          percentEl.textContent = "";
        } else {
          progressEl.value = 0;
          percentEl.textContent = "0%";
        }

        const reader = res.body.getReader();
        const chunks = [];
        let received = 0;

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          chunks.push(value);
          received += value.byteLength;

          if (total) {
            const pct = Math.min(100, Math.round((received / total) * 100));
            progressEl.value = pct;
            percentEl.textContent = pct + "%";
          }
        }

        const blob = new Blob(chunks, { type: "application/octet-stream" });
        saveBlob(blob, filename);

        statusEl.textContent = "Download complete.";
        statusEl.className = "status ok";
        progressEl.value = 100;
        percentEl.textContent = "100%";
      } catch (e) {
        statusEl.textContent = "Network error.";
        statusEl.className = "status err";
      } finally {
        btn.disabled = false;
      }
    });
  </script>
</body>
</html>
