so...this is my app.py code along with the flowchart_generation.html code...i am gettign worse flowchart/worse mindmaps for any given input...please completely fix the prompt such that it should look better and visuallly good..as sometimes it generates a one line set of nodes in a single line which makes it worse ...
"
from flask import Flask, render_template, request, jsonify
import logging
import google.generativeai as genai
from google.generativeai.types import GenerationConfig
import re
import json
import os
from werkzeug.utils import secure_filename
from docx import Document
import PyPDF2
import tempfile

# Replace with your actual API key
api_key = ""

app = Flask(__name__)

# Configure the Google Generative AI API
genai.configure(api_key=api_key)

# Generation configurations
generation_config = GenerationConfig(
    temperature=0.9,
    top_p=1,
    top_k=1,
    max_output_tokens=2048,
    candidate_count=1
)

# Initialize the model for flowchart generation
model = genai.GenerativeModel('gemini-1.5-flash')

# Configure upload folder and allowed extensions
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'pdf', 'docx'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

def extract_text_from_docx(file_path):
    doc = Document(file_path)
    full_text = []
    for para in doc.paragraphs:
        full_text.append(para.text)
    return '\n'.join(full_text)

def extract_text_from_pdf(file_path):
    with open(file_path, 'rb') as f:
        pdfReader = PyPDF2.PdfReader(f)
        full_text = []
        for page in pdfReader.pages:
            full_text.append(page.extract_text())
    return '\n'.join(full_text)

def generate_flowchart(topic, chart_type, animation, detail_level, document_text=None):
    if document_text:
        topic_prompt = f"Generate a flowchart based on the following content:\n\n{document_text}\n\n"
    else:
        topic_prompt = f"Generate a {'mind map' if chart_type == 'mind_map' else 'flowchart'} for the topic/algorithm: \"{topic}\".\n\n"

    prompt = topic_prompt + f"""
The {chart_type.replace('_', ' ')} should be {'animated' if animation == 'animated' else 'static'} and {'simple' if detail_level == 'simple' else 'normal' if detail_level == 'normal' else 'detailed'}.

The output should be in JSON format with the following structure:

{{
    "nodes": [
        {{"id": 1, "label": "Start", "level": 0, "shape": "ellipse", "order": 1}},
        {{"id": 2, "label": "Step 1", "level": 1, "shape": "box", "order": 2}}
    ],
    "edges": [
        {{"from": 1, "to": 2, "order": 1}}
    ]
}}

**Important Guidelines:**

1. **Unique IDs:** Ensure each node has a unique integer `id`.
2. **Descriptive Labels:** Provide clear and concise labels for each node (`"label"`).
3. **Hierarchical Levels:** Use `level` to indicate the hierarchy (0 for the top level, 1 for the next level, etc.).
4. **Node Shapes:** Choose appropriate shapes using the `shape` field:
    - "ellipse": For start/end nodes
    - "box": For process steps
    - "diamond": For decision nodes
    - "hexagon": For preparation steps
    - "circle": For connectors (if needed)
5. **Edges:** Specify connections using the `from` and `to` fields in the `edges` array.
6. **Flow:** Ensure a logical and easy-to-follow flow.
7. **Comprehensiveness:** Include all major steps or concepts.
8. **Spacing:** Use a minimum horizontal spacing of 200 and vertical spacing of 150 between nodes to prevent overlapping.
9. **No Isolated Nodes:** All nodes should be connected in a coherent structure.
10. **Clear Visualization:** The flowchart/mind map should be visually clear and easily understandable. Avoid overly complex visualizations.
11. **Avoid Overlapping:** Make sure nodes don't overlap with each other (at any level) due to their size or placement.
12. **Spacing Considerations:** Adjust the spacing between nodes based on the node size and content to ensure adequate readability.
13. **Order Attribute:** For animated charts, include an integer "order" attribute for each node and edge, indicating the sequence in which they should appear during animation.

**Detail Level:**
- **Simple:** Include only the main concepts with minimal details.
- **Normal:** Provide a balanced amount of detail for each step.
- **Detailed:** Offer comprehensive information and sub-steps for each concept.

**Animation Guidelines (for Animated Charts):**
- Sequentially introduce nodes and edges based on the "order" attribute.
- Ensure that the animation follows the logical flow of the chart.

**Output Format:**
- Output only the JSON structure, no additional text or explanations.
- Ensure that the output is correctly formatted and adheres to the provided JSON structure.

**Example (Simple Algorithm):**

{{
    "nodes": [
        {{"id": 1, "label": "Start", "level": 0, "shape": "ellipse", "order": 1}},
        {{"id": 2, "label": "Get input", "level": 1, "shape": "box", "order": 2}},
        {{"id": 3, "label": "Process input", "level": 1, "shape": "box", "order": 3}},
        {{"id": 4, "label": "Output results", "level": 1, "shape": "box", "order": 4}},
        {{"id": 5, "label": "End", "level": 0, "shape": "ellipse", "order": 5}}
    ],
    "edges": [
        {{"from": 1, "to": 2, "order": 1}},
        {{"from": 2, "to": 3, "order": 2}},
        {{"from": 3, "to": 4, "order": 3}},
        {{"from": 4, "to": 5, "order": 4}}
    ]
}}
"""

    try:
        response = model.generate_content(prompt)
        # Extract JSON from response
        json_match = re.search(r'\{.*\}', response.text, re.DOTALL)
        if json_match:
            try:
                flowchart_data = json.loads(json_match.group())
                return flowchart_data
            except json.JSONDecodeError:
                return {"error": "Invalid JSON structure", "raw_response": response.text}
        else:
            return {"error": "No JSON object found in the response", "raw_response": response.text}
    except Exception as e:
        return {"error": f"Error generating flowchart: {str(e)}"}

@app.route('/')
def index():
    return render_template('flowchart.html')

@app.route('/get_flowchart_data', methods=['POST'])
def get_flowchart_data():
    data = request.form
    topic = data.get('topic')
    chart_type = data.get('type', 'flowchart')
    animation = data.get('animation', 'static')
    detail_level = data.get('detail_level', 'normal')

    document_text = None
    file = request.files.get('file')
    if file and file.filename:
        if allowed_file(file.filename):
            filename = secure_filename(file.filename)
            # Create a temporary file and save the uploaded file
            temp_fd, temp_path = tempfile.mkstemp()
            try:
                with os.fdopen(temp_fd, 'wb') as temp_file:
                    temp_file.write(file.read())
                if filename.lower().endswith('.docx'):
                    document_text = extract_text_from_docx(temp_path)
                elif filename.lower().endswith('.pdf'):
                    document_text = extract_text_from_pdf(temp_path)
                else:
                    return jsonify({"error": "Unsupported file type."}), 400
            finally:
                # Make sure to close and remove the temporary file
                os.remove(temp_path)
        else:
            return jsonify({"error": "Unsupported file type."}), 400
    elif file and not file.filename:
        # No file uploaded
        file = None
    else:
        file = None

    if not topic and not document_text:
        return jsonify({"error": "Please provide a topic or upload a document."}), 400

    flowchart_data = generate_flowchart(topic, chart_type, animation, detail_level, document_text)

    if 'error' in flowchart_data:
        return jsonify({"error": flowchart_data['error'], "raw_response": flowchart_data.get("raw_response", "")}), 500

    # Prepare the data for vis-network
    nodes = [{
        "id": node["id"],
        "label": node["label"],
        "shape": node.get("shape", "box"),
        "order": node.get("order", 1),
        "level": node.get("level", 0)
    } for node in flowchart_data.get('nodes', [])]
    edges = [{
        "from": edge["from"],
        "to": edge["to"],
        "id": f"{edge['from']}-{edge['to']}",
        "order": edge.get("order", 1)
    } for edge in flowchart_data.get('edges', [])]

    # Ensure nodes and edges are sorted for consistent animation
    nodes = sorted(nodes, key=lambda x: x['order'])
    edges = sorted(edges, key=lambda x: x['order'])

    return jsonify({
        "nodes": nodes,
        "edges": edges,
        "animation": animation,
        "chart_type": chart_type
    })

if __name__ == '__main__':
    app.run(debug=True)
"
""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flowchart & Mind Map Generator</title>
    <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/vis-network@9.1.2/dist/vis-network.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vanta@latest/dist/vanta.waves.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/progressbar.js"></script>
    <style>
        :root {
            --primary: #00ff88;
            --secondary: #00ccff;
            --background: #0a0a0a;
            --surface: rgba(255, 255, 255, 0.05);
            --text: #ffffff;
            --error: #ff4757;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Space Grotesk', sans-serif;
        }

        body, html {
            height: 100%;
            background-color: var(--background);
            color: var(--text);
            overflow-x: hidden;
        }

        #vanta-background {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            gap: 2rem;
        }

        h1 {
            font-size: 4rem;
            text-align: center;
            background: linear-gradient(45deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            margin: 2rem 0;
            font-weight: 700;
            letter-spacing: -1px;
            opacity: 0;
            transform: translateY(-20px);
            animation: titleAnimation 1s cubic-bezier(0.4, 0, 0.2, 1) forwards;
        }

        @keyframes titleAnimation {
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .input-group {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
            padding: 2rem;
            background: var(--surface);
            border-radius: 20px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            animation: fadeIn 0.8s ease-out;
        }

        .input-field {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .input-field label {
            font-size: 1rem;
            font-weight: 500;
            color: var(--text);
            opacity: 0.9;
        }

        .input-field input,
        .input-field select {
            padding: 1rem;
            border-radius: 12px;
            border: 2px solid rgba(255, 255, 255, 0.1);
            background: rgba(255, 255, 255, 0.05);
            color: var(--text);
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .input-field input:focus,
        .input-field select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 20px rgba(0, 255, 136, 0.2);
        }

        #generate-btn {
            margin: 2rem auto;
            padding: 1rem 3rem;
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--background);
            background: linear-gradient(45deg, var(--primary), var(--secondary));
            border: none;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            transform-origin: center;
            animation: pulseButton 2s infinite;
        }

        @keyframes pulseButton {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        #generate-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0, 255, 136, 0.3);
        }

        #flowchart-container {
            width: 100%;
            height: 70vh;
            background: var(--surface);
            border-radius: 20px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            position: relative;
            display: none;
            overflow: hidden;
        }

        #flowchart {
            width: 100%;
            height: 100%;
        }

        #loading-animation {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            display: none;
        }

        .loader-text {
            margin-top: 1rem;
            font-size: 1.2rem;
            color: var(--text);
            opacity: 0;
            animation: fadeInOut 2s infinite;
        }

        @keyframes fadeInOut {
            0%, 100% { opacity: 0.5; }
            50% { opacity: 1; }
        }

        .control-buttons {
            position: absolute;
            bottom: 2rem;
            left: 50%;
            transform: translateX(-50%);
            display: none;
            gap: 1rem;
            background: rgba(0, 0, 0, 0.5);
            padding: 1rem;
            border-radius: 50px;
            backdrop-filter: blur(10px);
        }

        .control-buttons button {
            padding: 0.8rem 1.5rem;
            border: none;
            border-radius: 25px;
            background: linear-gradient(45deg, var(--primary), var(--secondary));
            color: var(--background);
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .control-buttons button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 255, 136, 0.3);
        }

        .zoom-btn {
            position: absolute;
            top: 1rem;
            width: 40px;
            height: 40px;
            border: none;
            border-radius: 50%;
            background: linear-gradient(45deg, var(--primary), var(--secondary));
            color: var(--background);
            font-size: 1.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        #zoom-in-btn { left: 1rem; }
        #zoom-out-btn { left: 4rem; }

        #fullscreen-btn {
            position: absolute;
            top: 1rem;
            right: 1rem;
            padding: 0.8rem 1.5rem;
            border: none;
            border-radius: 25px;
            background: linear-gradient(45deg, var(--primary), var(--secondary));
            color: var(--background);
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        #error-message {
            color: var(--error);
            text-align: center;
            padding: 1rem;
            border-radius: 10px;
            background: rgba(255, 71, 87, 0.1);
            border: 1px solid rgba(255, 71, 87, 0.3);
            display: none;
            animation: shake 0.5s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
        }

        @keyframes shake {
            10%, 90% { transform: translateX(-1px); }
            20%, 80% { transform: translateX(2px); }
            30%, 50%, 70% { transform: translateX(-4px); }
            40%, 60% { transform: translateX(4px); }
        }

        ::-webkit-scrollbar {
            width: 10px;
        }

        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 5px;
        }

        ::-webkit-scrollbar-thumb {
            background: linear-gradient(45deg, var(--primary), var(--secondary));
            border-radius: 5px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(45deg, var(--secondary), var(--primary));
        }

        @media (max-width: 768px) {
            h1 {
                font-size: 2.5rem;
            }

            .container {
                padding: 1rem;
            }

            .input-group {
                grid-template-columns: 1fr;
            }

            #flowchart-container {
                height: 60vh;
            }

            .control-buttons {
                flex-wrap: wrap;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div id="vanta-background"></div>
    <div class="container">
        <h1>Flowchart & Mind Map Generator</h1>
        <form id="generate-form" enctype="multipart/form-data">
            <div class="input-group">
                <div class="input-field">
                    <label for="topic-input">Enter Topic or Algorithm Name</label>
                    <input type="text" id="topic-input" name="topic" placeholder="e.g., Dijkstra's Algorithm">
                </div>
                <div class="input-field">
                    <label for="file-input">Or Upload Document (PDF or Word)</label>
                    <input type="file" id="file-input" name="file" accept=".pdf,.docx">
                </div>
                <div class="input-field">
                    <label for="type-select">Select Type</label>
                    <select id="type-select" name="type">
                        <option value="flowchart">Flowchart</option>
                        <option value="mind_map">Mind Map</option>
                    </select>
                </div>
                <div class="input-field">
                    <label for="animation-select">Choose Animation</label>
                    <select id="animation-select" name="animation">
                        <option value="static">Static</option>
                        <option value="animated">Animated</option>
                    </select>
                </div>
                <div class="input-field">
                    <label for="detail-select">Detail Level</label>
                    <select id="detail-select" name="detail_level">
                        <option value="simple">Simple</option>
                        <option value="normal">Normal</option>
                        <option value="detailed">Detailed</option>
                    </select>
                </div>
            </div>
        </form>
        <button id="generate-btn">Generate</button>
        <div id="flowchart-container">
            <div id="flowchart"></div>
            <div id="loading-animation">
                <div id="progress-bar"></div>
                <div class="loader-text">Generating Flowchart...</div>
            </div>
            <button class="zoom-btn" id="zoom-in-btn">+</button>
            <button class="zoom-btn" id="zoom-out-btn">−</button>
            <button id="fullscreen-btn">Fullscreen</button>
            <div class="control-buttons" id="animation-controls">
                <button id="start-animation-btn">Start Animation</button>
                <button id="play-btn">Play</button>
                <button id="pause-btn">Pause</button>
                <button id="back-btn">← Back</button>
                <button id="forward-btn">Forward →</button>
            </div>
        </div>
        <div id="error-message"></div>
    </div>
    <script>
        // Initialize Vanta Background with more dynamic waves
        VANTA.WAVES({
            el: "#vanta-background",
            mouseControls: true,
            touchControls: true,
            gyroControls: false,
            minHeight: 200.00,
            minWidth: 200.00,
            scale: 1.00,
            scaleMobile: 1.00,
            color: 0x00ff88,
            shininess: 150.00,
            waveHeight: 40.00,
            waveSpeed: 0.75,
            zoom: 0.65
        });

        // Animation control variables
        let animationInterval = null;
        let animationData = {};
        let progressBar = null;
        let isAnimated = false;

        document.getElementById('generate-btn').addEventListener('click', function () {
            var topic = document.getElementById('topic-input').value.trim();
            var fileInput = document.getElementById('file-input');
            var chartType = document.getElementById('type-select').value;
            var animation = document.getElementById('animation-select').value;
            var detailLevel = document.getElementById('detail-select').value;

            if (!topic && !fileInput.files.length) {
                gsap.to('#error-message', {duration: 0.5, opacity: 1, display: 'block', ease: 'power2.inOut'});
                document.getElementById('error-message').innerText = "Please enter a topic or upload a document.";
                return;
            }

            gsap.to('#flowchart-container', {duration: 0.5, opacity: 1, display: 'block', ease: 'power2.inOut'});
            gsap.to('#loading-animation', {duration: 0.3, opacity: 1, display: 'block', ease: 'power2.inOut'});
            gsap.to('#error-message', {duration: 0.3, opacity: 0, display: 'none', ease: 'power2.inOut'});

            initializeProgressBar();

            var formData = new FormData(document.getElementById('generate-form'));

            fetch('/get_flowchart_data', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                gsap.to('#loading-animation', {duration: 0.3, opacity: 0, display: 'none', ease: 'power2.inOut'});
                if (data.error) {
                    gsap.to('#error-message', {duration: 0.5, opacity: 1, display: 'block', ease: 'power2.inOut'});
                    document.getElementById('error-message').innerText = "Error: " + data.error;
                } else {
                    animationData = data;
                    isAnimated = animationData.animation === 'animated';
                    gsap.to('#error-message', {duration: 0.3, opacity: 0, display: 'none', ease: 'power2.inOut'});
                    drawFlowchart(data);
                }
            })
            .catch(error => {
                gsap.to('#loading-animation', {duration: 0.3, opacity: 0, display: 'none', ease: 'power2.inOut'});
                gsap.to('#error-message', {duration: 0.5, opacity: 1, display: 'block', ease: 'power2.inOut'});
                document.getElementById('error-message').innerText = "An unexpected error occurred.";
                console.error('Error:', error);
            });
        });

        function initializeProgressBar() {
            if (progressBar) {
                progressBar.destroy();
            }
            progressBar = new ProgressBar.Circle('#progress-bar', {
                color: '#e94560',
                trailColor: '#fff',
                trailWidth: 5,
                duration: 2000,
                easing: 'easeInOut',
                strokeWidth: 8,
                from: { color: '#e94560', width: 8 },
                to: { color: '#ff2e63', width: 8 },
                // Set default step function for all animate calls
                step: function(state, circle) {
                    circle.path.setAttribute('stroke', state.color);
                    circle.path.setAttribute('stroke-width', state.width);
                }
            });

            progressBar.animate(1.0);  // Animate progress bar from 0 to 100%
        }

        function drawFlowchart(data) {
            var container = document.getElementById('flowchart');

            // Destroy any existing network instance
            if (window.network) {
                window.network.destroy();
            }

            var nodes = new vis.DataSet([]);
            var edges = new vis.DataSet([]);

            window.nodesDataset = nodes;
            window.edgesDataset = edges;

            var options = {
                layout: {
                    hierarchical: {
                        enabled: true,
                        direction: 'UD',
                        sortMethod: 'directed',
                        nodeSpacing: 150,        // Reduced from 200
                        levelSeparation: 150,    // Reduced from 200
                        treeSpacing: 200         // Added to control spacing between parallel branches
                    }
                },
                nodes: {
                    // Previous node options remain
                    scaling: {
                        min: 20,
                        max: 60,
                        label: { enabled: true }
                    },
                    size: 35  // Default node size
                },
                edges: {
                    // Previous edge options remain
                    smooth: {
                        type: 'cubicBezier',
                        forceDirection: 'vertical',
                        roundness: 0.3,          // Reduced from 0.4
                    }
                },
                interaction: {
                    dragNodes: true,
                    dragView: true,
                    zoomView: true,
                    hover: true,
                    tooltipDelay: 100,
                    hideEdgesOnDrag: false,
                    navigationButtons: true,
                    keyboard: true
                },
                physics: {
                    enabled: false
                },
                autoResize: true,
                height: '100%',
                width: '100%'
            };

            var network = new vis.Network(container, { nodes: nodes, edges: edges }, options);
            window.network = network;


            // Fit the network to the container with padding
            network.on("stabilizationIterationsDone", function () {
                network.fit({
                    animation: {
                        duration: 1000,
                        easingFunction: 'easeInOutQuad'
                    },
                    padding: {
                        top: 50,
                        bottom: 50,
                        left: 50,
                        right: 50
                    }
                });
            });

            // Reset animation variables
            clearInterval(animationInterval);
            animationData.currentStep = 0;

            if (data.animation === 'animated') {
                document.getElementById('animation-controls').style.display = 'flex';
                initializeAnimation(data);
            } else {
                document.getElementById('animation-controls').style.display = 'none';
                nodes.add(data.nodes);
                edges.add(data.edges);
            }

            
            // Add double-click event to reset zoom and position
            network.on("doubleClick", function () {
                network.fit({
                    animation: {
                        duration: 1000,
                        easingFunction: 'easeInOutQuad'
                    }
                });
            });

             // Add mouse wheel event for smoother zooming
             container.addEventListener("wheel", function(event) {
                if (event.deltaY < 0) {
                    network.moveTo({
                        scale: network.getScale() * 1.1,
                        animation: {
                            duration: 100,
                            easingFunction: 'easeInOutQuad'
                        }
                    });
                } else {
                    network.moveTo({
                        scale: network.getScale() * 0.9,
                        animation: {
                            duration: 100,
                            easingFunction: 'easeInOutQuad'
                        }
                    });
                }
                event.preventDefault();
            });
        }

        function initializeAnimation(data) {
            resetAnimation();
            animationData.steps = [];

            // Combine nodes and edges and sort them based on the 'order' attribute
            let combinedElements = data.nodes.map(node => ({type: 'node', element: node, order: node.order}))
                .concat(data.edges.map(edge => ({type: 'edge', element: edge, order: edge.order})));

            combinedElements.sort((a, b) => a.order - b.order);

            animationData.steps = combinedElements;
        }

        function resetAnimation() {
            // Clear current nodes and edges
            window.nodesDataset.clear();
            window.edgesDataset.clear();
            // Reset animation step
            animationData.currentStep = 0;
        }

        function playAnimation() {
            pauseAnimation(); // Ensure no previous interval is running
            animationInterval = setInterval(() => {
                if (animationData.currentStep >= animationData.steps.length) {
                    clearInterval(animationInterval);
                    animationInterval = null;
                    return;
                }
                animateStep(animationData.currentStep);
                animationData.currentStep++;
            }, 800);
        }

        function pauseAnimation() {
            if (animationInterval) {
                clearInterval(animationInterval);
                animationInterval = null;
            }
        }

        function forwardAnimation() {
            if (animationData.currentStep < animationData.steps.length) {
                animateStep(animationData.currentStep);
                animationData.currentStep++;
            }
        }

        function backwardAnimation() {
            if (animationData.currentStep > 0) {
                animationData.currentStep--;
                revertStep(animationData.currentStep);
            }
        }

        function animateStep(step) {
            let stepData = animationData.steps[step];
            if (stepData.type === 'node') {
                window.nodesDataset.add(stepData.element);
                // Highlight the node briefly
                window.network.selectNodes([stepData.element.id]);
                setTimeout(() => {
                    window.network.unselectAll();
                }, 500);
            } else if (stepData.type === 'edge') {
                window.edgesDataset.add(stepData.element);
            }
        }

        function revertStep(step) {
            let stepData = animationData.steps[step];
            if (stepData.type === 'node') {
                window.nodesDataset.remove(stepData.element.id);
            } else if (stepData.type === 'edge') {
                window.edgesDataset.remove(stepData.element.id);
            }
        }

        // Event Listeners for Control Buttons
        document.getElementById('start-animation-btn').addEventListener('click', () => {
            resetAnimation();
            playAnimation();
        });

        document.getElementById('play-btn').addEventListener('click', playAnimation);
        document.getElementById('pause-btn').addEventListener('click', pauseAnimation);
        document.getElementById('forward-btn').addEventListener('click', forwardAnimation);
        document.getElementById('back-btn').addEventListener('click', backwardAnimation);

         // Modify zoom button handlers
         document.getElementById('zoom-in-btn').addEventListener('click', () => {
            window.network.moveTo({
                scale: window.network.getScale() * 1.2,
                animation: {
                    duration: 300,
                    easingFunction: 'easeInOutQuad'
                }
            });
        });

        document.getElementById('zoom-out-btn').addEventListener('click', () => {
            window.network.moveTo({
                scale: window.network.getScale() * 0.8,
                animation: {
                    duration: 300,
                    easingFunction: 'easeInOutQuad'
                }
            });
        });

        
        // Add window resize handler
        window.addEventListener('resize', () => {
            if (window.network) {
                window.network.fit({
                    animation: {
                        duration: 1000,
                        easingFunction: 'easeInOutQuad'
                    }
                });
            }
        });

        // Fullscreen functionality
        const flowchartContainer = document.getElementById('flowchart-container');
        const fullscreenButton = document.getElementById('fullscreen-btn');

        fullscreenButton.addEventListener('click', () => {
            if (document.fullscreenElement) {
                document.exitFullscreen();
            } else {
                flowchartContainer.requestFullscreen();
            }
        });
    </script>
</body>
</html>
"