import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
/**
 * This is a simplified version of html to adf conversion,
 * used specifically for SL RovoChatAction prompt message,
 * and does not support all ADF offered via @atlaskit/adf-utils
 *
 * Support: p, ul, li, text, b, strong, code, inlineCard (replace a hyperlink)
 */

import { code, doc, inlineCard, p, b, ul, li, text } from '@atlaskit/adf-utils/builders';
var INLINE_TAG_NAMES = ['b', 'strong', 'code', 'a', 'inlineCard'];
var BLOCK_TAG_NAMES = ['p', 'ul', 'ol', 'li'];

/**
 *   Group      Captures                Example
 *  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 *   match[1]   Self-closing tag name   br from <br/> or <img src="x"/>
 *   match[2]   Opening tag name        div from <div> or <div class="x">
 *   match[3]   Closing tag name        div from </div>
 *   match[4]   Text content            Hello world
 */
var htmlRegex = /<\s*(\w+)[^>]*?\s*\/\s*>|<\s*(\w+)[^>]*>|<\s*\/\s*(\w+)\s*>|([^<]+)/g;
var decodeHtmlEntities = function decodeHtmlEntities() {
  var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  return text.replace(/&nbsp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#39;/g, "'");
};
var tokenizeHtml = function tokenizeHtml(html) {
  var tokens = [];
  var match;
  while ((match = htmlRegex.exec(html)) !== null) {
    var selfClosingTag = match[1];
    var openingTag = match[2];
    var closingTag = match[3];
    var textContent = match[4];
    if (selfClosingTag) {
      tokens.push({
        type: 'selfClosing',
        tagName: selfClosingTag.toLowerCase()
      });
    } else if (openingTag) {
      tokens.push({
        type: 'open',
        tagName: openingTag.toLowerCase()
      });
    } else if (closingTag) {
      tokens.push({
        type: 'close',
        tagName: closingTag.toLowerCase()
      });
    } else if (textContent) {
      if (textContent !== null && textContent !== void 0 && textContent.trim()) {
        tokens.push({
          type: 'text',
          content: decodeHtmlEntities(textContent)
        });
      }
    }
  }
  return tokens;
};
var buildListItem = function buildListItem() {
  var content = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  // Check if content has only text/inline elements
  var hasOnlyInlineContent = content.every(function (node) {
    return node.type === 'text' || node.type === 'hardBreak' || !node.type;
  });
  if (hasOnlyInlineContent) {
    // Wrap text content in a paragraph
    return li([p.apply(void 0, _toConsumableArray(content))]);
  }

  // Content has block elements (like nested lists), use as-is
  return li(content);
};
var blockToAdf = function blockToAdf(tagName) {
  var content = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  switch (tagName) {
    case 'p':
      return p.apply(void 0, _toConsumableArray(content));
    case 'ul':
      return ul.apply(void 0, _toConsumableArray(content));
    case 'li':
      return buildListItem(content);
  }
};
var inlineToAdf = function inlineToAdf(tagName, content) {
  switch (tagName) {
    case 'b':
    case 'strong':
      return b(content);
    case 'code':
      return code(content);
    case 'a':
    case 'inlineCard':
      return inlineCard({
        url: content
      });
    default:
      return text(content);
  }
};
var parseTokensToAdf = function parseTokensToAdf(tokens) {
  var stack = [{
    type: 'root',
    content: []
  }];
  var currentMarks = [];
  var _loop = function _loop() {
    var token = tokens[i];
    var current = stack[stack.length - 1];
    switch (token.type) {
      case 'text':
        if (token.content) {
          var _currentMarks;
          var inlineAdfNode = inlineToAdf((_currentMarks = currentMarks) === null || _currentMarks === void 0 || (_currentMarks = _currentMarks[0]) === null || _currentMarks === void 0 ? void 0 : _currentMarks.type, token.content);
          current.content.push(inlineAdfNode);
        }
        break;
      case 'open':
        if (INLINE_TAG_NAMES.includes(token.tagName)) {
          currentMarks.push({
            type: token.tagName
          });
        } else if (BLOCK_TAG_NAMES.includes(token.tagName)) {
          stack.push({
            type: token.tagName,
            content: []
          });
        }
        break;
      case 'close':
        // Inline formatting
        if (token.tagName && INLINE_TAG_NAMES.includes(token.tagName)) {
          currentMarks = currentMarks.filter(function (m) {
            return m.type !== token.tagName;
          });
        }
        // Block elements
        else if (stack.length > 1) {
          var closed = stack.pop();
          var parent = stack[stack.length - 1];
          var adfNode = blockToAdf(closed === null || closed === void 0 ? void 0 : closed.type, closed === null || closed === void 0 ? void 0 : closed.content);
          if (adfNode) {
            parent.content.push(adfNode);
          }
        }
        break;
    }
  };
  for (var i = 0; i < tokens.length; i++) {
    _loop();
  }

  // Return root content
  return stack[0].content;
};

/**
 * Convert HTML string to ADF format
 *
 * This is a simplified version specific for RovoChatAction prompt message
 * and does not support all ADF offered via @atlaskit/adf-utils
 */
var htmlToAdf = function htmlToAdf(html) {
  try {
    var tokens = tokenizeHtml(html);
    var adfContent = parseTokensToAdf(tokens);
    return doc.apply(void 0, _toConsumableArray(adfContent));
  } catch (_unused) {
    return html;
  }
};
export default htmlToAdf;