console.log("Test loaded ");
        
        
        var botAvatar = "https://robohash.org/liberovelitdolores.bmp?size=50x50&set=set1";
        var userAvatar = "http://icons.iconarchive.com/icons/visualpharm/must-have/256/User-icon.png";


        var onMessageTask = [];

        var actSocket = new Rete.Socket("Action");
        var strSocket = new Rete.Socket("String");

        const JsRenderPlugin = {
            install(editor, params = {}) {
                editor.on("rendercontrol", ({
                    el,
                    control
                }) => {
                    if (control.render && control.render !== "js") return;

                    control.handler(el, editor);
                });
            }
        };

        class InputControl extends Rete.Control {
            constructor(key) {
                super(key);
                this.render = "js";
                this.key = key;
            }

            handler(el, editor) {
                var input = document.createElement("input");
                el.appendChild(input);

                var text = this.getData(this.key) || "Some message..";

                input.value = text;
                this.putData(this.key, text);
                input.addEventListener("change", () => {
                    this.putData(this.key, input.value);
                });
            }
        }

        class MessageComponent extends Rete.Component {
            constructor() {
                super("Message");
                // this.task = {
                //     outputs: {
                //         text: "output"
                //     }
                // };
            }

            builder(node) {
                // var inp1 = new Rete.Input("act", "Action", actSocket);
                var out = new Rete.Output("text", "Text", strSocket);
                var out1 = new Rete.Output("act", "Action", actSocket);
                var ctrl = new InputControl("text");

                return node.addControl(ctrl).addOutput(out).addOutput(out1);
            }

            worker(node, inputs,outputs) {
                return {
                    text: node.data.text
                };
            }
        }

        class WelComeMessageComponent extends Rete.Component {
            constructor() {
                super("Welcome Message");
                // this.task = {
                //     outputs: {
                //         text: "output"
                //     }
                // };
            }

            builder(node) {
                // var out = new Rete.Output("text", "Text", strSocket);
                var out1 = new Rete.Output("act", "Action", actSocket);
                var ctrl = new InputControl("text");

                return node
                    .addControl(ctrl)
                    .addOutput(out1)
            }

            worker(node, inputs) {
                return {
                    text: node.data.text
                };
            }
        }

        class OptionComponent extends Rete.Component {
            constructor() {
                super("Option");
                this.task = {
                    outputs: {
                        act: "option",
                    },
                    init(task){
                        onMessageTask.push(task);
                    }
                };
            }

            builder(node) {
                var inp1 = new Rete.Input("act", "Action", actSocket);
                var ctrl = new InputControl("optionName");
                var inp2 = new Rete.Input("text", "Text", strSocket);


                node.addControl(ctrl).addInput(inp1).addInput(inp2);
            }
            worker(node, inputs, outputs) {
                var text = inputs["text"] ? inputs["text"][0] : node.data.text;
            }
        }

        var components = [
            // new MessageSendComponent(),
            new MessageComponent(),
            new WelComeMessageComponent(),
            new OptionComponent()
        ];

        var container = document.getElementById("editor");
        var editor = new Rete.NodeEditor("demo@0.1.0", container);
        
        editor.use(VueRenderPlugin.default);
        editor.use(ConnectionPlugin.default);
        editor.use(ContextMenuPlugin.default);
        editor.use(JsRenderPlugin);
        editor.use(TaskPlugin);

        var engine = new Rete.Engine("demo@0.1.0");

        components.map(c => {
            editor.register(c);
            engine.register(c);
        });

        // To add the Created Chat Id
        let autosaveId = "null"

        editor
            .fromJSON(
                {
                    "id": "demo@0.1.0",
                    "nodes": {
                        "1": {
                            "id": 1,
                            "data": {
                                "text": "Welcome to the Chatbot! How can I assist you today?"
                            },
                            "inputs": {},
                            "outputs": {
                                "act": {
                                    "connections": [{
                                        "node": 2,
                                        "input": "act",
                                        "data": {}
                                    }]
                                }
                            },
                            "position": [-333, -586],
                            "name": "Welcome Message"
                        },
                        "2": {
                            "id": 2,
                            "data": {
                                "optionName": "Sales"
                            },
                            "inputs": {
                                "act": {
                                    "connections": [{
                                        "node": 1,
                                        "output": "act",
                                        "data": {}
                                    }]
                                },
                                "text": {
                                    "connections": [{
                                        "node": 3,
                                        "output": "text",
                                        "data": {}
                                    }]
                                }
                            },
                            "outputs": {},
                            "position": [296, -545],
                            "name": "Option"
                        },
                        "3": {
                            "id": 3,
                            "data": {
                                "text": "Hello World"
                            },
                            "inputs": {},
                            "outputs": {
                                "text": {
                                    "connections": [{
                                        "node": 2,
                                        "input": "text",
                                        "data": {}
                                    }]
                                },
                                "act": {
                                    "connections": []
                                }
                            },
                            "position": [-8, -366],
                            "name": "Message"
                        }
                    }
                }
            )
            .then(() => {

                editor.on("error", err => {
                    alertify.error(err.message);
                });

                editor.on("process connectioncreated connectionremoved nodecreated", async function(data) {
                        if (engine.silent) return;
                        onMessageTask = [];
                        await engine.abort();
                        await engine.process(editor.toJSON());
                    }
                );
                // editor.on("nodecreate", async function(data) {
                //     if(data.name == "Welcome Message"){
                //         setTimeout(() => {
                //             editor.removeNode(editor.nodes[data.id-1])
                //         }, 1000);

                //     }
                // }
                // )
                editor.on('connectionpick', async function(data) {
                        // when changing options remove the focus
                        let ele = document.querySelector('.node.welcome-message').querySelector('input');
                        ele.focus();
                        ele.blur()
                })
                let seletedPopup = true
                editor.on('selectnode',async function(data){
                    setTimeout(() => {
                        if(seletedPopup){
                            new bootstrap.Offcanvas(document.querySelector("#offcanvasRight")).show()
                            if(data.node.name != "Option"){
                                document.querySelector("#offcanvasRight textarea").value = data.node.data.text
                                document.querySelector("#offcanvasRight .conversationEditorBtn").onclick = ()=>{
                                    data.node.data.text = document.querySelector("#offcanvasRight textarea").value
                                    data.e.target.closest('.node').querySelector("input").value = document.querySelector("#offcanvasRight textarea").value
                                }
                            }else{
                                document.querySelector("#offcanvasRight textarea").value = data.node.data.optionName
                                document.querySelector("#offcanvasRight .conversationEditorBtn").onclick = ()=>{
                                    data.node.data.optionName = document.querySelector("#offcanvasRight textarea").value
                                    data.e.target.closest('.node').querySelector("input").value = document.querySelector("#offcanvasRight textarea").value
                                }
                            }
                        }
                    }, 200);
                })
                editor.on('nodetranslate',async function(data){
                    seletedPopup = false
                    setTimeout(() => {
                        seletedPopup = true
                    }, 200);
                })
                // To remove the contextmenu From the WelCome Message
                editor.nodes.forEach((node)=>{
                    if(node.name == "Welcome Message"){
                        node.vueContext.$el.addEventListener('contextmenu',(event)=>{
                            event.preventDefault();
                            event.stopPropagation();
                        })
                    }
                })
                editor.on('contextmenu',async function(data){
                    setTimeout(() => {
                        const items = document.querySelectorAll('.context-menu .item');
                        let welcomeMessageDiv = null;
                        items.forEach(item => {
                            if (item.textContent.trim() === 'Welcome Message') {
                                welcomeMessageDiv = item;
                            }
                        });
                        welcomeMessageDiv?.classList.add("d-none")
                    }, 10);
                    seletedPopup = false
                    setTimeout(() => {
                        seletedPopup = true
                    }, 200);
                })

                editor.on('connectioncreated', function(data) {
                    const outputNode = data.output.node;
                    const inputNode = data.input.node;

                    // Iterate through all nodes to find potential conflicting connections
                    for (const node of editor.nodes) {
                        if (node.name === "Option") {
                            const actionConnections = node.inputs.get('act').connections;
                            const textConnections = node.inputs.get('text').connections;

                            // Check if the same message node is connected via both action and text sockets
                            const actionConnectedNodes = actionConnections.map(c => c.output.node.id);
                            const textConnectedNodes = textConnections.map(c => c.output.node.id);

                            const commonConnectedNodes = actionConnectedNodes.filter(id => textConnectedNodes.includes(id));

                            if (commonConnectedNodes.length > 0) {
                                editor.removeConnection(data);
                                swal({
                                    title: `{{lang('Cannot connect', 'alerts')}}`,
                                    text: "{{lang('Cannot connect Option node to the same Message node via both Action and Text sockets.', 'alerts')}}",
                                    icon: "error",
                                })
                                break;
                            }
                        }
                    }
                });

                let denouncing
                editor.on('connectioncreated connectionremoved nodecreated keyup', async function(data){

                    // For the Auto Save
                    // clearTimeout(denouncing)

                    // if(autosaveId == 'null'){
                    //     document.querySelector("#liveChatFlowBtn").disabled = true
                    // }

                    // denouncing = setTimeout(()=>{
                    //     let AutoSaveData = {
                    //         chatId :autosaveId,
                    //         chat : JSON.stringify(editor.toJSON()),
                    //         responseName : document.querySelector('.responseFlowName').innerText
                    //     }

                    //     document.querySelector(".autoSavedSpiner .spinner4").classList.remove("d-none")
                    //     document.querySelector(".autoSavedSpiner b").classList.add("d-none")
                    //     // fetch('',{
                    //     //     headers: {
                    //     //         'Accept': 'application/json',
                    //     //         'Content-Type': 'application/json',
                    //     //         'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    //     //     },
                    //     //     method: "POST",
                    //     //     body: JSON.stringify(AutoSaveData)
                    //     // })
                    //     // .then(function(response) {
                    //     //     if (response.ok) {
                    //     //         return response.json();
                    //     //     } else {
                    //     //         throw new Error('Network response was not ok');
                    //     //     }
                    //     // })
                    //     // .then(function(data) {
                    //     //     if (data.success) {
                    //     //         document.querySelector(".autoSavedSpiner .spinner4").classList.add("d-none")
                    //     //         document.querySelector(".autoSavedSpiner b").classList.remove("d-none")
                    //     //         if(autosaveId == "null"){
                    //     //             autosaveId = data.success.id
                    //     //             document.querySelector('.tryItOutBtn').setAttribute("onclick",document.querySelector(".tryItOutBtn").getAttribute('onclick').replace('null',data.success.id))
                    //     //             document.querySelector('.tryItOutBtn').removeAttribute("disabled")
                    //     //         }
                    //     //         document.querySelector("#liveChatFlowBtn").disabled = false
                    //     //     }
                    //     // })
                    //     // .catch(function(error) {
                    //     //     console.error('Fetch error:', error);
                    //     // });
                    // },5000)
                })

                editor.trigger("process");
                editor.view.resize();
                AreaPlugin.zoomAt(editor);
            });

            // for the chat Active
        // document.querySelector("#liveChatFlowBtn").onclick = ()=>{
        //     swal({
        //         title: `{{lang('Are you sure you want to continue?', 'alerts')}}`,
        //         text: "{{lang('This Flow will maked was default', 'alerts')}}",
        //         icon: "warning",
        //         buttons: true,
        //         dangerMode: true,
        //         }).then((res)=>{
        //             if(res){
        //                 let SaveData = {
        //                                 chatId : autosaveId,
        //                                 chat : JSON.stringify(editor.toJSON())
        //                             }
        //                 fetch('',{
        //                     headers: {
        //                         'Accept': 'application/json',
        //                         'Content-Type': 'application/json',
        //                         'X-CSRF-TOKEN': '{{ csrf_token() }}'
        //                     },
        //                     method: "POST",
        //                     body: JSON.stringify(SaveData)
        //                 })
        //                 .then(function(response) {
        //                     if (response.ok) {
        //                         return response.json();
        //                     } else {
        //                         throw new Error('Network response was not ok');
        //                     }
        //                 })
        //                 .then(function(data) {
        //                     if (data.success) {
        //                         toastr.success(data.success);
        //                         document.querySelector(".autoSavedSpiner .spinner4").classList.add("d-none")
        //                         document.querySelector(".autoSavedSpiner b").classList.remove("d-none")
        //                         if(autosaveId == "null"){
        //                             autosaveId = data.flow.id
        //                         }
        //                         document.querySelector("#liveChatFlowBtn").disabled = false
        //                     }
        //                 })
        //                 .catch(function(error) {
        //                     console.error('Fetch error:', error);
        //                 });
        //             }
        //         })
        // }

        // Remove the localStorage when usr click the try it out
        document.querySelector(".tryItOutBtn").addEventListener("click",()=>{
                localStorage.removeItem("LiveChatCust")
        })
