export const sanitizeQrField = value => String(value || '').replace(/\|/g, ' ').trim();

export const buildNineFieldQr = ({ company, building, street, suburb, country, postcode, phone, reference, contactName }) => {
  const fields = [company, building, street, suburb, country, postcode, phone, reference, contactName].map(sanitizeQrField);
  const qr = fields.join('|');
  if (qr.split('|').length !== 9) throw new Error('QR must have exactly 9 fields (8 pipes).');
  return qr;
};

export const parseOrderAddress = order => {
  const raw = String(order?.original_address || order?.address || '').trim();
  const postcode = String(order?.postcode || '').trim();
  const parts = raw
    .split(',')
    .map(p => p.trim())
    .filter(Boolean);

  return {
    building: parts[0] || '',
    street: parts[1] || parts[0] || '',
    suburb: parts[2] || '',
    city: parts[3] || '',
    postcode,
    country: String(order?.country || 'NZ').trim() || 'NZ',
  };
};

export const compactDigits = value => String(value || '').replace(/\D/g, '');

export const getStockLabel = (stockIdToPrint, packieStocks) => {
  if (stockIdToPrint === 'custom') return 'Custom';
  const stock = packieStocks.find(s => String(s.id) === String(stockIdToPrint));
  if (stock?.quick_pick_enabled && (stock?.display_name || stock?.name)) return String(stock.display_name || stock.name);
  if (stock?.code || stock?.package_code) return String(stock.code || stock.package_code).toUpperCase();
  if (!stock?.name) return 'DL';
  const m = String(stock.name).match(/\b(DL|A5|A4|A3|A2)\b/i);
  return m ? m[1].toUpperCase() : stock.name;
};

export const zplSafe = v => String(v || '').replace(/[\^~]/g, ' ').replace(/\r?\n/g, ' ').trim();

export const escapeHtml = value => String(value || '')
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;')
  .replace(/'/g, '&#39;');

export const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
};

export const rgbToHex = (r, g, b) => {
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};
