/**
 * Normalisasi nomor WA ke format internasional tanpa tanda + (untuk wa.me).
 * Input: "08123...", "+628123...", "628123..."
 * Output: "628123..."
 */
export function normalizeWa(input) {
  if (!input) return '';
  let s = String(input).replace(/[^\d+]/g, '');
  if (s.startsWith('+')) s = s.slice(1);
  if (s.startsWith('0')) s = '62' + s.slice(1);
  if (s.startsWith('8')) s = '62' + s; // jaga-jaga jika user input mulai 8
  return s;
}

export function isValidWa(input) {
  const n = normalizeWa(input);
  return /^\d{10,15}$/.test(n);
}

/**
 * Render template WA dengan placeholder.
 * Placeholder yang didukung: {nama}, {kelas}, {link}, {nis}
 */
export function renderTemplate(template, vars) {
  if (!template) return '';
  return template.replace(/\{(\w+)\}/g, (m, key) => (vars[key] ?? m));
}

export function buildWaUrl(nomor, text) {
  const n = normalizeWa(nomor);
  const encoded = encodeURIComponent(text || '');
  return `https://wa.me/${n}?text=${encoded}`;
}
