local function SplitParagraphs(text)
    local paragraphs = {}
    for paragraph in string.gmatch(text, "([^\n]+)") do
        table.insert(paragraphs, paragraph)
    end
    return paragraphs
end

local function SplitSentences(paragraph)
    local sentences = {}
    for sentence in string.gmatch(paragraph, "([^%.%?!]+[%.%?!]?)[%s]*") do
        local trimmed = sentence:gsub("^%s+", ""):gsub("%s+$", "")
        if #trimmed > 0 then
            table.insert(sentences, trimmed)
        end
    end
    return sentences
end

function CzechQuestsAddon:TransformIntoParagraphs(original_text, translation_text)
    if original_text == "" or original_text == nil then
        return translation_text
    end

    local original_paragraphs = SplitParagraphs(original_text)
    local translation_paragraphs = {}

    local translation_sentences = SplitSentences(translation_text)
    local counter = 1

    for _, orig_paragraph in ipairs(original_paragraphs) do
        local orig_sentences = SplitSentences(orig_paragraph)

        local paragraph_sentence_count = #orig_sentences
        local collected = {}

        for i = 1, paragraph_sentence_count do
            if translation_sentences[counter] then
                table.insert(collected, translation_sentences[counter])
                counter = counter + 1
            else
                break
            end
        end

        table.insert(translation_paragraphs, table.concat(collected, " "))
    end

    local final_text = table.concat(translation_paragraphs, "\n")
    return final_text
end