"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.parseMessageBody = exports.default = exports.decodeHTMLEntities = void 0;
var _react = _interopRequireDefault(require("react"));
var _reactNative = require("react-native");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
let elementKeyCounter = 0;
const decodeHTMLEntities = text => {
  const entities = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#39;': "'",
    '&nbsp;': ' ',
    '&ndash;': '–',
    '&mdash;': '—',
    '&hellip;': '…',
    '&#8209;': '-'
  };
  return text.replace(/&[a-zA-Z0-9#]+;/g, m => entities[m] || m);
};
exports.decodeHTMLEntities = decodeHTMLEntities;
const styles = {
  bold: {
    fontWeight: 'bold'
  },
  italic: {
    fontStyle: 'italic'
  },
  strike: {
    textDecorationLine: 'line-through'
  },
  link: {
    color: '#0a66c2',
    textDecorationLine: 'underline'
  },
  codeInlineBox: {
    backgroundColor: '#f1f3f4',
    borderRadius: 3,
    paddingVertical: 1,
    paddingHorizontal: 4
  },
  codeInlineText: {
    fontFamily: _reactNative.Platform.select({
      ios: 'Menlo',
      android: 'monospace'
    }),
    fontSize: 13,
    color: '#333'
  },
  codeBlock: {
    backgroundColor: '#f6f8fa',
    padding: 12,
    borderRadius: 6,
    borderWidth: 1,
    borderColor: '#e1e4e8',
    marginVertical: 8
  },
  codeBlockText: {
    fontFamily: _reactNative.Platform.select({
      ios: 'Menlo',
      android: 'monospace'
    }),
    fontSize: 14,
    color: '#24292f',
    lineHeight: 20
  },
  h: [{
    fontWeight: 'bold',
    fontSize: 32,
    marginTop: 24,
    marginBottom: 16
  }, {
    fontWeight: 'bold',
    fontSize: 24,
    marginTop: 20,
    marginBottom: 14
  }, {
    fontWeight: 'bold',
    fontSize: 20,
    marginTop: 16,
    marginBottom: 12
  }, {
    fontWeight: 'bold',
    fontSize: 18,
    marginTop: 14,
    marginBottom: 10
  }, {
    fontWeight: 'bold',
    fontSize: 16,
    marginTop: 12,
    marginBottom: 8
  }, {
    fontWeight: 'bold',
    fontSize: 14,
    marginTop: 12,
    marginBottom: 8
  }],
  quote: {
    borderLeftWidth: 3,
    borderLeftColor: '#ccc',
    paddingLeft: 10,
    marginVertical: 4
  },
  paragraph: {
    marginVertical: 6
  },
  hr: {
    height: 1,
    backgroundColor: '#e1e4e8',
    marginVertical: 20
  },
  listItemRow: {
    flexDirection: 'row',
    alignItems: 'flex-start'
  },
  listMarker: {
    minWidth: 22,
    paddingTop: 2
  },
  checkboxRow: {
    flexDirection: 'row',
    alignItems: 'flex-start'
  },
  checkboxBox: {
    width: 16,
    height: 16,
    marginRight: 8,
    marginTop: 2,
    borderRadius: 3,
    borderWidth: 1,
    borderColor: '#bbb',
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center'
  },
  checkboxTick: {
    fontSize: 12,
    color: '#0a66c2'
  },
  tableContainer: {
    marginVertical: 12
  },
  tableInner: {
    borderWidth: 1,
    borderColor: '#d0d7de',
    borderRadius: 6,
    overflow: 'hidden',
    backgroundColor: '#fff'
  },
  tableRow: {
    flexDirection: 'row'
  },
  th: {
    flex: 1,
    paddingVertical: 10,
    paddingHorizontal: 12,
    backgroundColor: '#f6f8fa',
    borderRightWidth: 1,
    borderRightColor: '#d0d7de'
  },
  td: {
    flex: 1,
    paddingVertical: 10,
    paddingHorizontal: 12,
    borderTopWidth: 1,
    borderTopColor: '#e7e9ec',
    borderRightWidth: 1,
    borderRightColor: '#eef0f2'
  },
  lastCell: {
    borderRightWidth: 0
  },
  cellText: {
    color: '#24292f',
    fontSize: 14,
    lineHeight: 20
  }
};
const renderTextWithLinks = text => {
  const urlRegex = /(https?:\/\/[\w.-]+(?:\.[\w.-]+)+[\w\-\._~:\/?#[\]@!\$&'()\*\+,;=.]+)/g;
  const nodes = [];
  let lastIndex = 0;
  if (!text) {
    return nodes;
  }
  let match;
  while ((match = urlRegex.exec(text)) !== null) {
    const url = match[0];
    const start = match.index;
    if (start > lastIndex) {
      nodes.push(text.slice(lastIndex, start));
    }
    nodes.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Pressable, {
      onPress: () => _reactNative.Linking.openURL(url),
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
        style: styles.link,
        children: url
      })
    }, `link-${elementKeyCounter++}`));
    lastIndex = start + url.length;
  }
  if (lastIndex < text.length) {
    nodes.push(text.slice(lastIndex));
  }
  return nodes;
};
const parseInline = txt => {
  const elements = [];
  let remaining = decodeHTMLEntities(txt);
  const pattern = /(\*\*\*|\*\*|\*|`)(.*?)\1/;
  while (remaining.length > 0) {
    const match = remaining.match(pattern);
    if (!match) {
      elements.push(...renderTextWithLinks(remaining));
      break;
    }
    const fullMatch = match[0];
    const matchIndex = match.index ?? 0;
    const delimiter = match[1];
    const content = match[2];
    if (matchIndex > 0) {
      elements.push(...renderTextWithLinks(remaining.substring(0, matchIndex)));
    }
    if (delimiter === '`') {
      elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: styles.codeInlineBox,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          style: styles.codeInlineText,
          children: content
        })
      }, `code-${elementKeyCounter++}`));
    } else if (delimiter === '***') {
      elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
        style: styles.bold,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          style: styles.italic,
          children: parseInline(content)
        }, `i-${elementKeyCounter++}`)
      }, `bi-${elementKeyCounter++}`));
    } else if (delimiter === '**') {
      elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
        style: styles.bold,
        children: parseInline(content)
      }, `b-${elementKeyCounter++}`));
    } else if (delimiter === '*') {
      elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
        style: styles.italic,
        children: parseInline(content)
      }, `i-${elementKeyCounter++}`));
    }
    remaining = remaining.substring(matchIndex + fullMatch.length);
  }
  return elements;
};
const isTableSeparatorLine = line => {
  const trimmed = line.trim();
  return /^\|?[\s]*[\-\:]+[\s\|\-\:]*\|?[\s]*$/.test(trimmed) && trimmed.includes('-');
};
const parseTableRow = line => {
  const decodedLine = decodeHTMLEntities(line.trim()).replace(/\u00A0/g, ' ');
  const cleaned = decodedLine.replace(/^\||\|$/g, '');
  const cells = cleaned.split(/(?<!\\)\|/).map(c => c.replace(/\\\|/g, '|').trim());
  return cells.length > 0 ? cells : [''];
};
const renderMarkdownTableRN = (headers, separator, dataRows) => {
  const aligns = headers.map((_, idx) => {
    const seg = (separator[idx] || '').trim();
    const left = seg.startsWith(':');
    const right = seg.endsWith(':');
    if (left && right) {
      return 'center';
    }
    if (right) {
      return 'right';
    }
    return 'left';
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.ScrollView, {
    horizontal: true,
    bounces: false,
    showsHorizontalScrollIndicator: false,
    style: styles.tableContainer,
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
      style: styles.tableInner,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: styles.tableRow,
        children: headers.map((h, cIdx) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: [styles.th, cIdx === headers.length - 1 && styles.lastCell],
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
            style: [styles.cellText, {
              fontWeight: '700',
              textAlign: aligns[cIdx]
            }],
            children: parseInline(h)
          })
        }, `th-${elementKeyCounter++}-${cIdx}`))
      }), dataRows.map((row, rIdx) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: styles.tableRow,
        children: headers.map((_, cIdx) => {
          const cell = row[cIdx] ?? '';
          return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
            style: [styles.td, cIdx === headers.length - 1 && styles.lastCell],
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
              style: [styles.cellText, {
                textAlign: aligns[cIdx]
              }],
              children: parseInline(cell)
            })
          }, `td-${elementKeyCounter++}-${cIdx}`);
        })
      }, `tr-${elementKeyCounter++}-${rIdx}`))]
    })
  }, `table-${elementKeyCounter++}`);
};
const parseMessageBody = text => {
  if (typeof text !== 'string') {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {});
  }
  const lines = text.split('\n');
  const elements = [];
  elementKeyCounter = 0;
  let listBuffer = [];
  let inCodeBlock = false;
  let codeLang = '';
  let codeLines = [];
  const flushList = () => {
    if (listBuffer.length === 0) {
      return;
    }
    const renderListItems = (items, depth) => {
      const result = [];
      let i = 0;
      while (i < items.length) {
        const item = items[i];
        if (item.depth === depth) {
          const subItems = [];
          let j = i + 1;
          while (j < items.length && items[j].depth > depth) {
            subItems.push(items[j]);
            j++;
          }
          const nested = subItems.length > 0 ? renderListItems(subItems, depth + 1) : null;
          let contentEl;
          if (item.type === 'checkbox') {
            contentEl = /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
              style: styles.checkboxRow,
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
                style: [styles.checkboxBox, item.checked && {
                  backgroundColor: '#e8f3ff',
                  borderColor: '#0a66c2'
                }],
                children: item.checked ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
                  style: styles.checkboxTick,
                  children: "\u2713"
                }) : null
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
                style: {
                  flex: 1
                },
                children: parseInline(item.content)
              })]
            }, `checkbox-${elementKeyCounter++}`);
          } else {
            contentEl = /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
              style: styles.listItemRow,
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
                style: styles.listMarker,
                children: '\u2022'
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
                style: {
                  flex: 1
                },
                children: parseInline(item.content)
              })]
            }, `ulitem-${elementKeyCounter++}`);
          }
          result.push(/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
            style: {
              marginBottom: 6,
              marginLeft: depth * 16
            },
            children: [contentEl, nested]
          }, `liwrap-${elementKeyCounter++}`));
          i = j;
        } else {
          i++;
        }
      }
      return result;
    };
    const listContent = renderListItems(listBuffer, 0);
    elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
      style: {
        marginVertical: 8
      },
      children: listContent
    }, `list-${elementKeyCounter++}`));
    listBuffer = [];
  };
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmedLine = line.trim();
    if (trimmedLine.startsWith('```')) {
      flushList();
      inCodeBlock = !inCodeBlock;
      if (!inCodeBlock) {
        elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: styles.codeBlock,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
            style: styles.codeBlockText,
            selectable: true,
            children: codeLines.join('\n')
          })
        }, `pre-${elementKeyCounter++}`));
        codeLang = '';
      } else {
        codeLang = trimmedLine.slice(3).trim();
        codeLines = [];
      }
      continue;
    }
    if (inCodeBlock) {
      codeLines.push(line);
      continue;
    }
    const headingMatch = trimmedLine.match(/^(#{1,6})\s+(.*)/);
    if (headingMatch) {
      flushList();
      const level = Math.min(6, Math.max(1, headingMatch[1].length));
      const content = headingMatch[2];
      elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
        style: styles.h[level - 1],
        children: parseInline(content)
      }, `h-${elementKeyCounter++}`));
      continue;
    }
    if (/^(\*|\-|\_){3,}$/.test(trimmedLine)) {
      flushList();
      elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: styles.hr
      }, `hr-${elementKeyCounter++}`));
      continue;
    }
    if (trimmedLine.includes('|') && trimmedLine !== '' && !isTableSeparatorLine(trimmedLine) && !trimmedLine.match(/^\s*-?\s*\[[\sxX]\]/)) {
      let separatorIndex = i + 1;
      while (separatorIndex < lines.length && lines[separatorIndex].trim() === '') {
        separatorIndex++;
      }
      if (separatorIndex < lines.length && isTableSeparatorLine(lines[separatorIndex].trim())) {
        flushList();
        const rows = [];
        const headers = parseTableRow(trimmedLine);
        const headerCount = headers.length;
        rows.push(headers);
        const sep = parseTableRow(lines[separatorIndex].trim());
        let current = separatorIndex + 1;
        while (current < lines.length) {
          const nextLine = lines[current].trim();
          if (nextLine === '') {
            current++;
            continue;
          }
          if (nextLine.includes('|') && !isTableSeparatorLine(nextLine) && !nextLine.match(/^\s*-?\s*\[[\sxX]\]/)) {
            let rowCells = parseTableRow(nextLine);
            while (rowCells.length < headerCount) {
              rowCells.push('');
            }
            rowCells = rowCells.slice(0, headerCount);
            rows.push(rowCells);
            current++;
          } else {
            break;
          }
        }
        const dataRows = rows.slice(1);
        elements.push(renderMarkdownTableRN(headers, sep, dataRows));
        i = current - 1;
        continue;
      }
    }
    const listMatch = line.match(/^(\s*)(?:-|\*|\+)?\s*(\[[\sxX]\])\s*(.*)/);
    if (listMatch) {
      const leadingSpace = listMatch[1];
      const checkboxPart = listMatch[2];
      const content = listMatch[3];
      const depth = Math.floor(leadingSpace.length / 2);
      const checked = checkboxPart.toLowerCase() === '[x]';
      listBuffer.push({
        type: 'checkbox',
        content: decodeHTMLEntities(content),
        depth,
        checked
      });
      continue;
    }
    const bulletMatch = line.match(/^(\s*)([-*+])\s+(.*)/);
    if (bulletMatch && bulletMatch[3].trim() !== '') {
      const depth = Math.floor(bulletMatch[1].length / 2);
      listBuffer.push({
        type: 'ul',
        content: decodeHTMLEntities(bulletMatch[3]),
        depth
      });
      continue;
    }
    if (trimmedLine !== '') {
      flushList();
      elements.push(/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: styles.paragraph,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          children: parseInline(trimmedLine)
        })
      }, `p-${elementKeyCounter++}`));
    } else {
      flushList();
    }
  }
  flushList();
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
    style: {},
    children: elements
  });
};
exports.parseMessageBody = parseMessageBody;
var _default = exports.default = parseMessageBody;
//# sourceMappingURL=parseMessageBody.js.map