(() => {
  const overlay = document.getElementById("kapoPayOverlay");
  if (!overlay) return;

  const body = document.body;
  const methodsEl = document.getElementById("kapoPayMethods");
  const loadingEl = document.getElementById("kapoPayLoading");
  const errorEl = document.getElementById("kapoPayError");
  const titleEl = document.getElementById("kapoPayTitle");

  const qrSection = document.getElementById("kapoPayQr");
  const qrTitle = document.getElementById("kapoPayQrTitle");
  const qrSub = document.getElementById("kapoPayQrSub");
  const qrImg = document.getElementById("kapoPayQrImg");
  const qrLink = document.getElementById("kapoPayQrLink");
  const copyBtn = document.getElementById("kapoPayCopy");

  let configCache = null;
  let lastFocused = null;
  const configUrl = new URL("config.json", window.location.href).toString();

  function setHidden(el, hidden) {
    if (!el) return;
    if (hidden) el.setAttribute("hidden", "");
    else el.removeAttribute("hidden");
  }

  function openModal() {
    lastFocused = document.activeElement;
    setHidden(overlay, false);
    body.style.overflow = "hidden";
    const closeBtn = overlay.querySelector("[data-pay-close]");
    if (closeBtn) closeBtn.focus();
    loadConfigOnce().then(renderFromConfig).catch((err) => {
      const msg =
        (err && err.message ? err.message : "Error cargando config.json.") +
        " URL: " +
        configUrl;
      showErrorDetails(msg);
    });
  }

  function closeModal() {
    setHidden(overlay, true);
    body.style.overflow = "";
    setHidden(qrSection, true);
    if (methodsEl) setHidden(methodsEl, false);
    if (lastFocused && typeof lastFocused.focus === "function") lastFocused.focus();
  }

  function showError() {
    if (loadingEl) setHidden(loadingEl, true);
    if (methodsEl) setHidden(methodsEl, true);
    if (errorEl) setHidden(errorEl, false);
  }

  function showErrorDetails(message) {
    console.error("[kapo-pay] " + message);
    if (errorEl) {
      errorEl.textContent = message;
      setHidden(errorEl, false);
    }
    if (loadingEl) setHidden(loadingEl, true);
    if (methodsEl) setHidden(methodsEl, true);
  }

  async function loadConfigOnce() {
    if (configCache) return configCache;
    const inline = document.getElementById("kapoPayConfig");
    if (inline && inline.textContent && inline.textContent.trim()) {
      try {
        configCache = JSON.parse(inline.textContent);
        return configCache;
      } catch {
        throw new Error("Config embebido inválido (JSON) en #kapoPayConfig.");
      }
    }
    if (location.protocol === "file:") {
      throw new Error(
        "No se encontró config embebido (#kapoPayConfig). Abre con servidor o embebe el JSON."
      );
    }
    const res = await fetch(configUrl, { cache: "no-store" });
    if (!res.ok) {
      throw new Error("No se pudo cargar config.json (" + res.status + ").");
    }
    try {
      configCache = await res.json();
    } catch (e) {
      throw new Error("config.json inválido (JSON).");
    }
    return configCache;
  }

  function clearChildren(el) {
    while (el && el.firstChild) el.removeChild(el.firstChild);
  }

  function asText(value, fallback = "") {
    return typeof value === "string" ? value : fallback;
  }

  function renderFromConfig(cfg) {
    if (errorEl) setHidden(errorEl, true);
    if (loadingEl) setHidden(loadingEl, true);
    if (!methodsEl) return;

    clearChildren(methodsEl);

    const title = asText(cfg?.title, "Elige tu método de pago");
    if (titleEl) titleEl.textContent = title;

    const methods = Array.isArray(cfg?.methods) ? cfg.methods : [];
    if (!methods.length) return showError();

    for (const method of methods) {
      const btn = document.createElement("button");
      btn.type = "button";
      btn.className = "kapo-pay-method";

      const label = document.createElement("div");
      label.className = "kapo-pay-method-label";
      label.textContent = asText(method?.label, "Método");

      const desc = document.createElement("p");
      desc.className = "kapo-pay-method-desc";
      desc.textContent = asText(method?.description, "");

      btn.appendChild(label);
      btn.appendChild(desc);

      btn.addEventListener("click", () => {
        const type = asText(method?.type, "link");
        if (type === "qr") {
          const img = asText(method?.image, "qr.png");
          qrImg.src = img;
          qrTitle.textContent = asText(method?.label, "Pagar con QR");
          qrSub.textContent = asText(method?.description, "Escanea el código con tu app.");

          const url = asText(method?.url, "");
          if (url) {
            qrLink.href = url;
            setHidden(qrLink, false);
            setHidden(copyBtn, false);
          } else {
            setHidden(qrLink, true);
            setHidden(copyBtn, true);
          }

          setHidden(methodsEl, true);
          setHidden(qrSection, false);
          return;
        }

        const url = asText(method?.url, "");
        if (!url) return;
        window.location.href = url;
      });

      methodsEl.appendChild(btn);
    }

    setHidden(methodsEl, false);
  }

  // Click targets that should open modal (book + buy_order)
  function handlePayClick(e) {
    if (!e.isTrusted) return;
    const target = e.target && e.target.closest ? e.target.closest("[data-pay-modal=\"1\"]") : null;
    if (!target) return;
    e.preventDefault();
    openModal();
  }

  // Overlay interactions
  overlay.addEventListener("click", (e) => {
    const card = overlay.querySelector(".kapo-pay-card");
    if (card && !card.contains(e.target)) closeModal();
  });
  overlay.addEventListener("click", (e) => {
    if (e.target && e.target.closest && e.target.closest("[data-pay-close]")) closeModal();
    if (e.target && e.target.closest && e.target.closest("[data-pay-back]")) {
      setHidden(qrSection, true);
      setHidden(methodsEl, false);
    }
  });
  document.addEventListener("keydown", (e) => {
    if (overlay.hasAttribute("hidden")) return;
    if (e.key === "Escape") closeModal();
  });

  copyBtn?.addEventListener("click", async () => {
    const url = qrLink?.href;
    if (!url || url === "#") return;
    try {
      await navigator.clipboard.writeText(url);
      copyBtn.textContent = "Copiado";
      setTimeout(() => (copyBtn.textContent = "Copiar enlace"), 1200);
    } catch {
      // ignore
    }
  });

  document.addEventListener("click", handlePayClick, true);
})();
