const BLOCK_TAGS = [
  'address', 'article', 'aside', 'blockquote', 'canvas', 'dd', 'div', 'dl',
  'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form',
  'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  'header', 'hr', 'li', 'main', 'nav', 'noscript', 'ol', 'output',
  'p', 'pre', 'section', 'table', 'tfoot', 'thead', 'tbody',
  'tr', 'td', 'th', 'ul', 'video',
];

const BLOCK_RE = new RegExp(`^</?(?:${BLOCK_TAGS.join('|')})[\\s>\\/]`, 'i');

/**
 * Converts WordPress-style double-newline content into <p> tags,
 * mirroring the behaviour of PHP's wpautop().
 */
export function wpautop(html: string): string {
  if (!html) return '';

  // Normalise line endings
  let text = html.replace(/\r\n/g, '\n').replace(/\r/g, '\n');

  // Collapse 3+ consecutive newlines to 2
  text = text.replace(/\n{3,}/g, '\n\n');

  const chunks = text.split(/\n\n/);

  const processed = chunks.map((chunk) => {
    chunk = chunk.trim();
    if (!chunk) return '';

    // Already a block-level element — leave untouched
    if (BLOCK_RE.test(chunk)) return chunk;

    // Convert remaining single newlines to <br />
    chunk = chunk.replace(/\n/g, '<br />\n');

    return `<p>${chunk}</p>`;
  });

  return processed.filter(Boolean).join('\n\n');
}
