const DEFAULT_TYPEWRITER_CHUNK_SIZE = 3

function findLineStart(chars, index) {
  let cursor = Math.max(0, index)
  while (cursor > 0 && chars[cursor - 1] !== '\n') {
    cursor -= 1
  }
  return cursor
}

function findNextParagraphStart(chars, index) {
  let cursor = Math.max(0, index)
  while (cursor < chars.length) {
    if (chars[cursor] === '\n' && chars[cursor + 1] && chars[cursor + 1] !== '|') {
      return cursor + 1
    }
    cursor += 1
  }
  return chars.length
}

function isMarkdownTableLine(chars, lineStart) {
  return chars.slice(lineStart, lineStart + 2).join('').trimStart().startsWith('|')
}

export function resolveStewardTypewriterNextIndex(chars = [], index = 0, chunkSize = DEFAULT_TYPEWRITER_CHUNK_SIZE) {
  const safeIndex = Math.max(0, Math.min(Number(index) || 0, chars.length))
  const lineStart = findLineStart(chars, safeIndex)
  if (isMarkdownTableLine(chars, lineStart) || chars[safeIndex + 1] === '|') {
    return findNextParagraphStart(chars, lineStart)
  }
  const safeChunkSize = Math.max(1, Number(chunkSize) || DEFAULT_TYPEWRITER_CHUNK_SIZE)
  return Math.min(chars.length, safeIndex + safeChunkSize)
}
