import sanitizeHtml from 'sanitize-html';

const opts = {
  allowedTags: [
    'b', 'i', 'em', 'strong', 'u', 's', 'p', 'br', 'span', 'div',
    'ul', 'ol', 'li', 'a', 'h1', 'h2', 'h3', 'h4', 'blockquote', 'hr', 'small',
    'font',
  ],
  allowedAttributes: {
    a: ['href', 'target', 'rel'],
    span: ['style'],
    div: ['style'],
    p: ['style'],
    h1: ['style'], h2: ['style'], h3: ['style'], h4: ['style'],
    font: ['size', 'color', 'face'],
  },
  allowedStyles: {
    '*': {
      'color': [/^#(0x)?[0-9a-f]+$/i, /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/],
      'text-align': [/^left$|^right$|^center$|^justify$/],
      'font-size': [/^\d+(?:px|em|rem|%)$/],
      'font-weight': [/^\d+$|^bold$|^normal$/],
      'font-style': [/^italic$|^normal$/],
      'background-color': [/^#(0x)?[0-9a-f]+$/i, /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/],
    },
  },
  transformTags: {
    a: sanitizeHtml.simpleTransform('a', { rel: 'noopener noreferrer', target: '_blank' }),
  },
};

export function sanitizeRich(html) {
  if (!html) return '';
  return sanitizeHtml(html, opts);
}
