// `sanitize-html` is CommonJS; import via require so the default is callable at runtime.
import sanitizeHtml = require('sanitize-html');

const HTML_TAG_PATTERN = /<\/?[a-z][\s\S]*>/i;

const allowedTags = [
  'p',
  'br',
  'strong',
  'em',
  'ul',
  'ol',
  'li',
  'a',
  'blockquote',
  'span',
];

const allowedAttributes: Record<string, string[]> = {
  a: ['href', 'title', 'target', 'rel'],
  span: ['style'],
};

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

const normalisePlainTextMessage = (message: string) => {
  const trimmed = message.trim();

  if (!trimmed) {
    return '';
  }

  const paragraphs = trimmed.split(/\r?\n\r?\n/);

  return paragraphs
    .map((paragraph) => {
      const lines = paragraph.split(/\r?\n/).map((line) => escapeHtml(line));
      return `<p>${lines.join('<br />')}</p>`;
    })
    .join('');
};

const enrichAnchorTags = (
  tagName: string,
  attribs: Record<string, string | undefined>,
) => ({
  tagName,
  attribs: {
    ...attribs,
    target: attribs.target || '_blank',
    rel: attribs.rel || 'noopener noreferrer',
  },
});

export const formatSharedMessage = (message?: string) => {
  if (!message) {
    return '';
  }

  const source = HTML_TAG_PATTERN.test(message)
    ? message
    : normalisePlainTextMessage(message);

  return sanitizeHtml(source, {
    allowedTags,
    allowedAttributes,
    transformTags: {
      a: enrichAnchorTags,
    },
    exclusiveFilter: ({ text }) =>
      typeof text === 'string' && text.trim() === '',
  }).trim();
};

const decodeEntities = (value: string) =>
  value
    .replace(/&nbsp;/gi, ' ')
    .replace(/&amp;/gi, '&')
    .replace(/&quot;/gi, '"')
    .replace(/&#39;/gi, "'")
    .replace(/&lt;/gi, '<')
    .replace(/&gt;/gi, '>');

export const htmlToPlainText = (html: string) => {
  const withoutStyle = html.replace(/<style[\s\S]*?<\/style>/gi, '');
  const withoutScript = withoutStyle.replace(/<script[\s\S]*?<\/script>/gi, '');

  const withBreaks = withoutScript
    .replace(/<\/(p|div|h[1-6]|li|tr|table)>/gi, '$&\n')
    .replace(/<br\s*\/?>/gi, '\n')
    .replace(/<\/ul>/gi, '</ul>\n')
    .replace(/<\/ol>/gi, '</ol>\n');

  const withoutTags = withBreaks.replace(/<[^>]+>/g, '');
  const decoded = decodeEntities(withoutTags);

  return decoded
    .replace(/\r/g, '')
    .replace(/\t/g, ' ')
    .replace(/ +/g, ' ')
    .replace(/\n{3,}/g, '\n\n')
    .trim();
};
