(() => {
  const dropZone = document.getElementById("dropZone");
  const dropInner = document.getElementById("dropInner");
  const fileInput = document.getElementById("fileInput");
  const pickBtn = document.getElementById("pickBtn");
  const fileChip = document.getElementById("fileChip");
  const fileName = document.getElementById("fileName");
  const clearFile = document.getElementById("clearFile");
  const form = document.getElementById("wmForm");
  const runBtn = document.getElementById("runBtn");
  const opacity = document.getElementById("opacity");
  const opacityVal = document.getElementById("opacityVal");
  const step = document.getElementById("step");
  const stepVal = document.getElementById("stepVal");
  const status = document.getElementById("status");
  const statusDot = document.getElementById("statusDot");
  const statusText = document.getElementById("statusText");
  const progress = document.getElementById("progress");
  const result = document.getElementById("result");
  const resultTitle = document.getElementById("resultTitle");
  const resultMeta = document.getElementById("resultMeta");
  const downloadBtn = document.getElementById("downloadBtn");

  let selected = null;

  function setFile(file) {
    if (!file) {
      selected = null;
      fileChip.classList.add("hidden");
      runBtn.disabled = true;
      return;
    }
    if (file.type !== "application/pdf" && !file.name.toLowerCase().endsWith(".pdf")) {
      showStatus("err", "PDF 파일만 사용할 수 있습니다.");
      return;
    }
    selected = file;
    fileName.textContent = file.name;
    fileChip.classList.remove("hidden");
    runBtn.disabled = false;
    result.classList.add("hidden");
    showStatus("ok", `선택됨 · ${(file.size / 1024 / 1024).toFixed(2)} MB`);
  }

  function showStatus(kind, text) {
    status.classList.remove("hidden");
    statusDot.className = "status-dot " + (kind || "");
    statusText.textContent = text;
  }

  pickBtn.addEventListener("click", () => fileInput.click());
  dropInner.addEventListener("click", (e) => {
    if (e.target === pickBtn || e.target.closest("button")) return;
    if (e.target.closest(".file-chip")) return;
    fileInput.click();
  });
  fileInput.addEventListener("change", () => setFile(fileInput.files?.[0] || null));
  clearFile.addEventListener("click", (e) => {
    e.stopPropagation();
    fileInput.value = "";
    setFile(null);
    status.classList.add("hidden");
  });

  ["dragenter", "dragover"].forEach((ev) => {
    dropZone.addEventListener(ev, (e) => {
      e.preventDefault();
      e.stopPropagation();
      dropZone.classList.add("dragover");
    });
  });
  ["dragleave", "drop"].forEach((ev) => {
    dropZone.addEventListener(ev, (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (ev === "dragleave" && e.target !== dropZone) return;
      dropZone.classList.remove("dragover");
    });
  });
  dropZone.addEventListener("drop", (e) => {
    const f = e.dataTransfer?.files?.[0];
    if (f) setFile(f);
  });

  opacity.addEventListener("input", () => {
    opacityVal.textContent = Number(opacity.value).toFixed(2);
  });
  if (step && stepVal) {
    step.addEventListener("input", () => {
      stepVal.textContent = String(step.value);
    });
  }

  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    if (!selected) return;

    const fd = new FormData(form);
    fd.set("file", selected, selected.name);
    fd.set("no_legal", form.no_legal.checked ? "true" : "false");

    runBtn.disabled = true;
    progress.classList.remove("hidden");
    result.classList.add("hidden");
    showStatus("busy", "워터마크 생성 중…");

    try {
      const res = await fetch("/api/watermark", { method: "POST", body: fd });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.detail || data.message || `오류 ${res.status}`);

      showStatus("ok", "완료 — 다운로드하세요");
      result.classList.remove("hidden");
      resultTitle.textContent = data.filename || "watermarked.pdf";
      resultMeta.textContent = `페이지 ${data.pages} · 법률 페이지 ${
        (data.legal_pages || []).join(", ") || "없음"
      } · ${data.mark || "BSD CLASS LICENSE"}`;
      downloadBtn.href = data.download;
      downloadBtn.setAttribute("download", data.filename || "watermarked.pdf");
    } catch (err) {
      showStatus("err", err.message || "처리 실패");
    } finally {
      progress.classList.add("hidden");
      runBtn.disabled = !selected;
    }
  });
})();
