/** ASCII-safe text and wrapping for thermal ESC/POS output. */

function sanitizeForPrinter(text) {
  return String(text || "")
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/\u2122/g, "(TM)")
    .replace(/\u00AE/g, "(R)")
    .replace(/\u00A9/g, "(C)")
    .replace(/\u00B7|\u2022|\u2219|\u2027/g, "-")
    .replace(/[\u2013\u2014]/g, "-")
    .replace(/[\u2018\u2019]/g, "'")
    .replace(/[\u201C\u201D]/g, '"')
    .replace(/[^\x09\x0A\x0D\x20-\x7E]/g, "");
}

function wrapForWidth(text, width) {
  const w = Math.max(8, width || 32);
  const t = sanitizeForPrinter(text).trim();
  if (!t) return [];
  if (t.length <= w) return [t];

  const out = [];
  let rest = t;
  while (rest.length > w) {
    let breakAt = rest.lastIndexOf(" ", w);
    if (breakAt < Math.floor(w * 0.35)) breakAt = w;
    out.push(rest.slice(0, breakAt).trim());
    rest = rest.slice(breakAt).trim();
  }
  if (rest) out.push(rest);
  return out;
}

function visibleLength(text) {
  return sanitizeForPrinter(text).length;
}

module.exports = {
  sanitizeForPrinter,
  wrapForWidth,
  visibleLength,
};
