/**
 * Convierte a mayúsculas inputs de texto y textareas dentro del contenedor (catálogos, POS, etc.).
 * Excluye: email, password, number, date, url y campos con data-no-uppercase.
 */

function shouldUppercase(el) {
  if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) {
    return false;
  }
  if (el.dataset.noUppercase !== undefined) {
    return false;
  }
  if (el instanceof HTMLTextAreaElement) {
    return true;
  }
  const type = (el.getAttribute("type") || "text").toLowerCase();
  const skip = new Set([
    "email",
    "password",
    "number",
    "date",
    "datetime-local",
    "time",
    "url",
    "color",
    "range",
    "hidden",
    "checkbox",
    "radio",
    "file",
    "button",
    "submit",
    "reset",
  ]);
  if (skip.has(type)) {
    return false;
  }
  return type === "text" || type === "tel" || type === "search" || type === "";
}

function applyUppercase(el) {
  const val = el.value;
  if (typeof val !== "string" || val === "") {
    return;
  }
  const upper = val.toUpperCase();
  if (val === upper) {
    return;
  }
  const start = el.selectionStart;
  const end = el.selectionEnd;
  el.value = upper;
  el.dispatchEvent(new Event("input", { bubbles: true }));
  if (typeof start === "number" && typeof end === "number") {
    try {
      el.setSelectionRange(start, end);
    } catch {
      /* readonly */
    }
  }
}

function onInput(event) {
  if (shouldUppercase(event.target)) {
    applyUppercase(event.target);
  }
}

function onBlur(event) {
  if (shouldUppercase(event.target)) {
    applyUppercase(event.target);
  }
}

export const uppercaseScope = {
  mounted(el) {
    el.classList.add("uppercase-input-scope");
    el.addEventListener("input", onInput);
    el.addEventListener("blur", onBlur, true);
  },
  unmounted(el) {
    el.classList.remove("uppercase-input-scope");
    el.removeEventListener("input", onInput);
    el.removeEventListener("blur", onBlur, true);
  },
};
