// Helper function to generate unique IDs
function generateId() {
    return Math.random().toString(36).substr(2, 9);
}
function markdownToJSON(markdown) {
    const lines = markdown.split("\n");
    const root = {
        nodeData: {
            id: "root",
            title: lines[0].substring(2),
            desc: "",
            is_root: true,
            parent_id: undefined,
            children_count: 0,
            depth: 0,
            deleted: false,
            children: [],
        },
        linkData: {},
    };
    let lastNodes = [root.nodeData];
    let listDepth = 0;
    for (let i = 1; i < lines.length; i++) {
        const line = lines[i];
        const trimmedLine = line.trim();
        const leadingSpaces = line.length - line.trimStart().length;
        if (trimmedLine.startsWith("#")) {
            listDepth = 0; // Reset list depth when encountering a header
            let level = trimmedLine.split(" ")[0].length;
            let node = {
                id: generateId(),
                title: trimmedLine.substring(level + 1).trim(),
                desc: "",
                is_root: false,
                parent_id: lastNodes[lastNodes.length - 2]?.id || undefined,
                children_count: 0,
                depth: level,
                deleted: false,
                children: [],
            };
            while (lastNodes.length >= level) {
                lastNodes.pop();
            }
            lastNodes.push(node);
            lastNodes[lastNodes.length - 2].children.push(node);
            lastNodes[lastNodes.length - 2].children_count = lastNodes[lastNodes.length - 2].children.length;
        }
        else if (trimmedLine.startsWith("-")) {
            const listItemLevel = Math.floor(leadingSpaces / 2) + 1; // 2 spaces per level
            listDepth = listItemLevel;
            let node = {
                id: generateId(),
                title: trimmedLine.substring(1).trim(),
                desc: "",
                is_root: false,
                parent_id: lastNodes[lastNodes.length - 2]?.id || undefined,
                children_count: 0,
                depth: listItemLevel,
                deleted: false,
                children: [],
            };
            while (lastNodes.length >= listItemLevel + 1) {
                lastNodes.pop();
            }
            lastNodes.push(node);
            lastNodes[lastNodes.length - 2].children.push(node);
            lastNodes[lastNodes.length - 2].children_count = lastNodes[lastNodes.length - 2].children.length;
        }
        else if (trimmedLine.length !== 0) {
            lastNodes[lastNodes.length - 1].desc += "\n" + trimmedLine;
        }
    }
    return root;
}
// Export the function for use in other modules
export { markdownToJSON };
