(function (global) {
  const POLL_INTERVAL_MS = 2500;
  const TERMINAL_STATUSES = new Set(["completado", "fallido"]);
  const ACTIVE_STATUSES = new Set(["en_cola", "procesando"]);

  function init() {
    const view = document.querySelector("[data-epicrisis-status-view]");
    if (!view) return;
    if (String(view.dataset.statusVariant || "").trim().toLowerCase() !== "processing") return;

    const statusEndpoint = String(view.dataset.statusEndpoint || "").trim();
    const successHref = String(view.dataset.successHref || "").trim();
    if (!statusEndpoint || !successHref) return;

    const detailBody = view.querySelector("[data-epicrisis-status-detail-body]");
    const timerId = global.setInterval(async () => {
      try {
        const response = await global.fetch(statusEndpoint, {
          headers: { Accept: "application/json" },
          credentials: "same-origin",
        });
        if (!response.ok) return;

        const data = await response.json();
        const currentStatus = String(data?.epicrisis_status || "").trim().toLowerCase();

        if (detailBody && ACTIVE_STATUSES.has(currentStatus)) {
          detailBody.textContent = `Estado actual: ${currentStatus}`;
        }

        if (TERMINAL_STATUSES.has(currentStatus)) {
          global.clearInterval(timerId);
          global.location.href = String(data?.epicrisis_url || successHref).trim() || successHref;
        }
      } catch (error) {
        if (error?.code === "auth_expired" || error?.message === "AUTH_EXPIRED") {
          global.clearInterval(timerId);
          return;
        }
        global.clearInterval(timerId);
      }
    }, POLL_INTERVAL_MS);
  }

  document.addEventListener("DOMContentLoaded", init);
})(globalThis);
