/**
 * Solo A-Z y 0-9 (sin guiones). Alineado con {@see \App\Support\LaundryScanCode::compact} (PHP).
 */
export function compactScanCode(code) {
  return String(code ?? "")
    .trim()
    .replace(/[^A-Z0-9]/gi, "")
    .toUpperCase();
}

/**
 * Normaliza códigos LMS/LMSB a forma compacta (solo letras y números).
 * Alineado con {@see \App\Support\LaundryScanInput::canonicalizeScannerCode} (PHP).
 */
export function canonicalizeScannerCode(raw) {
  let s = String(raw ?? "").trim();
  if (!s) return "";

  s = s.replace(/['`]/g, "-");

  let m = s.match(/^LMSB?['`\-_.\s](\d{8})['`\-_.\s]([A-Z0-9]+)$/i);
  if (m) {
    const prefix = /^LMSB/i.test(s) ? "LMSB" : "LMS";
    return `${prefix}${m[1]}${m[2].toUpperCase()}`;
  }

  m = s.match(/^LMSB(\d{8})([A-Z0-9]{4,})$/i);
  if (m) return `LMSB${m[1]}${m[2].toUpperCase()}`;

  m = s.match(/^LMS(\d{8})([A-Z0-9]{4,})$/i);
  if (m) return `LMS${m[1]}${m[2].toUpperCase()}`;

  if (/^LMS/i.test(s)) {
    return compactScanCode(s);
  }

  return s;
}

/**
 * Alineado con {@see \App\Support\LaundryScanInput::normalize} (PHP).
 */
export function normalizeLaundryScanInput(raw) {
  const s = String(raw ?? "").trim();
  if (!s) return "";

  const seg = s.match(/\/seguimiento\/([^/?#]+)/i);
  if (seg?.[1]) {
    try {
      return canonicalizeScannerCode(decodeURIComponent(seg[1]));
    } catch {
      return canonicalizeScannerCode(seg[1]);
    }
  }

  const fu = s.match(/[?&]folio_unico=([^&=#]+)/i);
  if (fu?.[1]) {
    try {
      return canonicalizeScannerCode(decodeURIComponent(fu[1]));
    } catch {
      return canonicalizeScannerCode(fu[1]);
    }
  }

  const fo = s.match(/[?&]folio=([^&=#]+)/i);
  if (fo?.[1]) {
    try {
      return canonicalizeScannerCode(decodeURIComponent(fo[1]));
    } catch {
      return canonicalizeScannerCode(fo[1]);
    }
  }

  return canonicalizeScannerCode(s);
}

/** Code128: folio compacto (LMS20260529…), sin guiones. */
export function ticketBarcodePayload(orden) {
  if (!orden || typeof orden !== "object") return "";
  const folio = String(orden.folio_unico ?? "").trim();
  if (!folio) return "";
  if (/^LMS/i.test(folio)) return compactScanCode(folio);
  return folio;
}

/** QR 2D: mismo folio compacto; respaldo codigo_qr legacy. */
export function ticketQrPayload(orden) {
  const folio = ticketBarcodePayload(orden);
  if (folio) return folio;
  return String(orden?.codigo_qr ?? "").trim();
}

/** Código de bolsa compacto para Code128. */
export function bagBarcodePayload(codigo) {
  const code = String(codigo ?? "").trim();
  if (!code) return "";
  if (/^LMS/i.test(code)) return compactScanCode(code);
  return code;
}
