how to fold by empty spaces

i am writing a custom language and i need to fold on each paragraph. a paragraph means a group of lines that has empty lines in between. the code below is my attempt. it can mark each paragraphs correctly but once i start folding them, it fails in a way that i cant really explain.

const foldExtension = foldService.of((state: EditorState, from: number, to: number) => {
            const line = state.doc.lineAt(from);
            
            if (line.number == 1) {
                return null;
            }
            
            const prevLine = state.doc.line(line.number - 1);
            
            if (prevLine.text.trim() != "" || line.text.trim() == "") {
                return null;
            }
            
            let foldStart = line.number + line.length + 1; // End of line instead of start of line.
            let foldEnd = to;
            let nextLine = line;
            
            while (nextLine.number < state.doc.lines) {
                nextLine = state.doc.line(nextLine.number + 1);
                
                if (nextLine.text == "") {
                    foldEnd = nextLine.from - 1;
                    break;
                }
            }
            
            const endLine = state.doc.lineAt(foldEnd);
            
            if (endLine.number - prevLine.number < 2) {
                return null;
            }
            
            return { from: foldStart, to: foldEnd };
        });

on load (correct):

folding the first paragraph (correct):

third paragraph (why does it fold the 2nd paragraph and merging with the 1st?):

with the help of chatgpt, it suggests this code below:

        const foldExtension = foldService.of((state: EditorState, from: number, to: number) => {
            const startLine = state.doc.lineAt(from); // First line in the selection
            let foldStart = from;
            let foldEnd = to;

            // Ensure fold starts at the beginning of a paragraph
            while (foldStart > 0) {
                const prevLine = state.doc.lineAt(foldStart - 1);
                if (!prevLine.text.trim()) break; // Stop at a blank line
                foldStart = prevLine.from;
            }

            // Find the end of the paragraph
            while (foldEnd < state.doc.length) {
                const nextLine = state.doc.lineAt(foldEnd + 1);
                if (!nextLine.text.trim()) break; // Stop at the next blank line
                foldEnd = nextLine.to;
            }

            // If the fold region is only one line, return null to skip folding
            if (state.doc.lineAt(foldStart).number === state.doc.lineAt(foldEnd).number) {
                return null;
            }

            // Return a fold covering the entire paragraph
            return { from: foldStart + startLine.length, to: foldEnd };
        });

folding works correctly:

but as you can see, it has the fold on every single lines.