(function (global) {
  const app = (global.EpicrisisApp = global.EpicrisisApp || {});
  function escapeHtml(value) {
    return String(value ?? "")
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#39;");
  }

  function stripHtml(value) {
    const node = document.createElement("div");
    node.innerHTML = value || "";
    return (node.textContent || node.innerText || "").trim();
  }

  function deduplicarTextos(items) {
    const seen = new Set();
    const out = [];
    (items || []).forEach((raw) => {
      const texto = stripHtml(raw).replace(/\s+/g, " ").trim();
      if (!texto) return;
      const key = texto.toLowerCase();
      if (seen.has(key)) return;
      seen.add(key);
      out.push(texto);
    });
    return out;
  }

  function formatMachineDate(value) {
    return global.AppDateTime?.formatMachineDate(value) || "";
  }

  function localizeMachineDates(root = document) {
    global.AppDateTime?.localizeMachineDates(root);
  }

  app.utils = {
    escapeHtml,
    stripHtml,
    deduplicarTextos,
    formatMachineDate,
    localizeMachineDates,
  };
})(globalThis);
