(() => {
  const requestId = new URLSearchParams(location.search).get("id") || "";
  const statusElement = document.getElementById("status");
  const filenameInput = document.getElementById("filename");
  const saveDirInput = document.getElementById("saveDir");
  const sourceInput = document.getElementById("source");
  const sizeElement = document.getElementById("size");
  const mimeElement = document.getElementById("mime");
  const sourceTypeElement = document.getElementById("sourceType");
  const startButton = document.getElementById("start");
  const queueButton = document.getElementById("queue");
  const cancelButton = document.getElementById("cancel");

  startButton.addEventListener("click", () => submit("start-pending-download", "시작 중..."));
  queueButton.addEventListener("click", () => submit("queue-pending-download", "큐에 추가 중..."));
  cancelButton.addEventListener("click", cancel);
  filenameInput.addEventListener("keydown", submitOnEnter);
  saveDirInput.addEventListener("keydown", submitOnEnter);

  load();

  async function load() {
    if (!requestId) {
      fail("요청 없음");
      return;
    }

    try {
      const response = await send({ type: "get-pending-download", requestId });
      if (!response.ok) {
        throw new Error(response.error || "요청 실패");
      }

      const request = response.request || {};
      filenameInput.value = request.filename || pickFilename(request.url) || "download";
      saveDirInput.value = request.saveDir || response.defaults?.defaultSaveDir || "";
      sourceInput.value = request.url || "";
      sourceInput.title = request.url || "";
      sizeElement.textContent = formatBytes(Number(request.totalBytes || request.fileSize || 0));
      mimeElement.textContent = request.mime || guessType(request.url) || "-";
      sourceTypeElement.textContent = [sourceLabel(request.source), request.qualityLabel || ""].filter(Boolean).join(" · ");
      statusElement.textContent = "대기";
      setDisabled(false);
      filenameInput.focus();
      filenameInput.select();
    } catch (error) {
      fail(error.message);
    }
  }

  async function submit(type, message) {
    setDisabled(true, message);
    try {
      const response = await send({
        type,
        requestId,
        filename: filenameInput.value,
        saveDir: saveDirInput.value
      });
      if (!response.ok) {
        throw new Error(response.error || "처리 실패");
      }

      window.close();
    } catch (error) {
      setDisabled(false, error.message);
    }
  }

  async function cancel() {
    cancelButton.disabled = true;
    try {
      await send({ type: "cancel-pending-download", requestId });
    } finally {
      window.close();
    }
  }

  function submitOnEnter(event) {
    if (event.key === "Enter") {
      event.preventDefault();
      submit("start-pending-download", "시작 중...");
    }
  }

  function setDisabled(disabled, message = "") {
    statusElement.textContent = message || statusElement.textContent;
    startButton.disabled = disabled;
    queueButton.disabled = disabled;
    cancelButton.disabled = disabled;
    filenameInput.disabled = disabled;
    saveDirInput.disabled = disabled;
  }

  function fail(message) {
    statusElement.textContent = message || "오류";
    startButton.disabled = true;
    queueButton.disabled = true;
  }

  function send(message) {
    return new Promise((resolve) => {
      chrome.runtime.sendMessage(message, (response) => {
        if (chrome.runtime.lastError) {
          resolve({ ok: false, error: chrome.runtime.lastError.message });
          return;
        }

        resolve(response || { ok: false, error: "응답 없음" });
      });
    });
  }

  function pickFilename(url) {
    try {
      const pathname = new URL(url || "").pathname;
      return decodeURIComponent(pathname.split("/").filter(Boolean).pop() || "");
    } catch {
      return "";
    }
  }

  function guessType(url) {
    const name = pickFilename(url).toLowerCase();
    if (/\.(mp4|m4v|webm|mkv|mov|avi)$/.test(name)) {
      return "video";
    }

    if (/\.(mp3|m4a|flac|wav|ogg)$/.test(name)) {
      return "audio";
    }

    return "";
  }

  function sourceLabel(source) {
    return {
      "manual-url": "직접 입력",
      "link-click": "링크",
      "chrome-download": "Chrome 다운로드",
      "video-direct": "영상 원본",
      "video-hls": "영상 HLS",
      "video-dash": "영상 DASH"
    }[source] || source || "-";
  }

  function formatBytes(value) {
    if (!Number.isFinite(value) || value <= 0) {
      return "-";
    }

    if (value >= 1024 * 1024 * 1024) {
      return `${(value / 1024 / 1024 / 1024).toFixed(2)} GB`;
    }

    if (value >= 1024 * 1024) {
      return `${(value / 1024 / 1024).toFixed(1)} MB`;
    }

    if (value >= 1024) {
      return `${(value / 1024).toFixed(1)} KB`;
    }

    return `${value} B`;
  }
})();
