import { templateFactory } from '../../template/template-factory.js';
import { Renderable } from '../../core/renderable.js';

const EMOJI_REGEX = /((?![\u{23}-\u1F6F3]([^\u{FE0F}]|$))\p{Emoji}(?:(?!\u{200D})\p{EComp}|(?=\u{200D})\u{200D}\p{Emoji})*)+/gmu;

/**
 * Surrounds the given text with a span element with aria-hidden attribute.
 * This is used to wrap emojis in a span to prevent them from being read by screen readers.
 * @param {string} text - The text to be wrapped.
 * @returns {string} - The text wrapped in a span element.
 */
const surroundEmojiWithSpan = (text) => {
  return text.replace(EMOJI_REGEX, (match) => `<span aria-hidden="true">${match}</span>`);
};

class Main extends Renderable {
  constructor (data) {
    super(data);
    this._template = templateFactory(this.data);
  }

  async render () {
    let renderedContent = await this._template.render();
    renderedContent = this.silenceEmoji(renderedContent);

    return `
      <main id="content" role="main">
        ${renderedContent}
      </main>
    `;
  }

  silenceEmoji (text) {
    const parts = text.split(/(<span[^>]+aria-hidden[^>]*>.*?<\/span>)/g);
    return parts.map(part => part.includes('aria-hidden') ? part : surroundEmojiWithSpan(part)).join('')
  };

  get text () {
    return this._template.text;
  }
}

export { Main };
