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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
import React, { useState, useCallback, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import ReactFlow, {
    MiniMap,
    Controls,
    Background,
    useNodesState,
    useEdgesState,
    addEdge,
    isNode,
    MarkerType,
    BackgroundVariant,
    applyEdgeChanges,
    applyNodeChanges
} from 'reactflow';
import { FaArrowLeft, FaSave, FaTrash, FaPlay, FaTimes, FaPencilAlt, FaCheck, FaPause, FaVolumeUp, FaUserCog, FaPlus } from 'react-icons/fa';
import { TiFlowMerge } from "react-icons/ti";
import { RiRobot2Fill } from "react-icons/ri";
import { BsToggle2Off, BsToggle2On } from "react-icons/bs";
import AgentModal from './AgentModal';
import WorkflowToast from './WorkflowToast';
import NodeSelectionPanel from './NodeSelectionPanel';
import InputNodeModal from './InputNodeModal';
import customNodeTypes from './CustomNodes'; // Import our custom node types
import CustomEdge, { customEdgeTypes } from './CustomEdge'; // Import our custom edge component
import 'reactflow/dist/style.css';
import './WorkflowEditor.css';

const initialNodes = [];
const initialEdges = [];

const DEFAULT_AGENTS = [
    { id: 'researcher', name: 'Research Agent', status: 'Default', isDefault: true },
    { id: 'believer', name: 'Believer Agent', status: 'Default', isDefault: true },
    { id: 'skeptic', name: 'Skeptic Agent', status: 'Default', isDefault: true }
];

// Define toast type
const initialToastState = {
    message: '',
    type: 'success'
};

// Define node data types with proper interface
const createNodeData = (label, additionalData = {}) => {
    // Create basic data object with default values
    const data = {
        label,
        description: '',
        ...additionalData
    };

    return data;
};

// Create a typed node creator function
const createNode = (id, position, data, nodeType = 'default') => {
    const node = {
        id,
        position,
        data,
        type: nodeType
    };

    return node;
};

// Connection validation rules
const isValidConnection = (connection, nodes) => {
    const { source, target } = connection;

    // Get source and target nodes
    const sourceNode = nodes.find(node => node.id === source);
    const targetNode = nodes.find(node => node.id === target);

    if (!sourceNode || !targetNode) return false;

    // Get node types
    const sourceType = sourceNode.type;
    const targetType = targetNode.type;

    // Define connection rules
    // 1. Input Node can only output to Researcher nodes
    if (sourceType === 'input' && targetType !== 'researcher') {
        return false;
    }

    // 2. Researcher Node can take input from Input nodes and output to Agent nodes or Insights nodes
    if (sourceType === 'researcher' && (targetType !== 'agent' && targetType !== 'insights')) {
        return false;
    }
    if (targetType === 'researcher' && sourceType !== 'input') {
        return false;
    }

    // 3. Agent Nodes can only output to Insights nodes
    if (sourceType === 'agent' && targetType !== 'insights') {
        return false;
    }

    // 4. Insights Node can only take inputs from Agent nodes or Researcher nodes and output to Notify or Publish
    if (sourceType === 'insights' && targetType !== 'notify' && targetType !== 'output') {
        return false;
    }
    if (targetType === 'insights' && sourceType !== 'agent' && sourceType !== 'researcher') {
        return false;
    }

    // 5. Notify and Publish nodes can only take input from Insights
    if ((targetType === 'notify' || targetType === 'output') && sourceType !== 'insights') {
        return false;
    }

    return true;
};

const WorkflowEditor = () => {
    const { workflowId } = useParams();
    const navigate = useNavigate();
    const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
    const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
    const [workflowName, setWorkflowName] = useState('');
    const [isEditingName, setIsEditingName] = useState(workflowId === '-1');
    const [tempWorkflowName, setTempWorkflowName] = useState('');
    const [isAgentModalOpen, setIsAgentModalOpen] = useState(false);
    const [agents, setAgents] = useState(DEFAULT_AGENTS);
    const [isLoadingAgents, setIsLoadingAgents] = useState(false);
    const [selectedAgent, setSelectedAgent] = useState(null);
    const [toast, setToast] = useState(initialToastState);
    const [isInsightsEnabled, setIsInsightsEnabled] = useState(false);
    const [podcastText, setPodcastText] = useState('');
    const [selectedVoice, setSelectedVoice] = useState('alloy');
    const [selectedEmotion, setSelectedEmotion] = useState('neutral');
    const [voiceSpeed, setVoiceSpeed] = useState(1.0);
    const [isGenerating, setIsGenerating] = useState(false);
    const [audioUrl, setAudioUrl] = useState('');
    const [isPlaying, setIsPlaying] = useState(false);
    const [currentTime, setCurrentTime] = useState(0);
    const [duration, setDuration] = useState(0);
    const [successMessage, setSuccessMessage] = useState('');
    const audioRef = useRef(null);

    // New state variables for workflow execution
    const [executionState, setExecutionState] = useState({});
    const [isExecuting, setIsExecuting] = useState(false);
    const [workflowInsights, setWorkflowInsights] = useState("");

    // State for ReactFlow instance
    const [rfInstance, setRfInstance] = useState(null);

    // Default edge options for animated flow
    const defaultEdgeOptions = {
        type: 'custom',
        animated: true,
        style: { stroke: '#6366f1', strokeWidth: 2 }, // Default color, will be overridden contextually
        markerEnd: {
            type: MarkerType.ArrowClosed,
            color: '#6366f1', // Default color, will be overridden contextually
            width: 20,
            height: 20,
        }
    };

    // Edge types definition
    const edgeTypes = { ...customEdgeTypes };

    const voices = [
        { id: 'alloy', name: 'Alloy' },
        { id: 'echo', name: 'Echo' },
        { id: 'fable', name: 'Fable' },
        { id: 'onyx', name: 'Onyx' },
        { id: 'nova', name: 'Nova' },
        { id: 'shimmer', name: 'Shimmer' }
    ];

    const emotions = [
        { id: 'neutral', name: 'Neutral' },
        { id: 'happy', name: 'Happy' },
        { id: 'sad', name: 'Sad' },
        { id: 'excited', name: 'Excited' },
        { id: 'calm', name: 'Calm' }
    ];

    const onConnect = useCallback(
        (params) => {
            // Check if connection is valid
            if (isValidConnection(params, nodes)) {
                // Get the source node to determine edge color
                const sourceNode = nodes.find(n => n.id === params.source);

                // Set color based on source node type
                let edgeColor = '#6366f1'; // Default color (purple)
                if (sourceNode) {
                    switch (sourceNode.type) {
                        case 'input':
                            edgeColor = '#6366F1'; // Input -> purple
                            break;
                        case 'researcher':
                            edgeColor = '#4C1D95'; // Researcher -> deep purple
                            break;
                        case 'agent':
                            edgeColor = '#10B981'; // Agent -> green
                            break;
                        case 'insights':
                            edgeColor = '#F59E0B'; // Insights -> amber
                            break;
                        default:
                            edgeColor = '#6366f1'; // Default
                    }
                }

                // Create an animated edge with styling
                const edge = {
                    ...params,
                    type: 'custom', // Use our custom edge type
                    animated: true,
                    style: { stroke: edgeColor, strokeWidth: 2 },
                    markerEnd: {
                        type: MarkerType.ArrowClosed,
                        color: edgeColor,
                        width: 20,
                        height: 20,
                    },
                    data: { sourceType: sourceNode ? sourceNode.type : 'unknown' }
                };

                setEdges((eds) => addEdge(edge, eds));
            } else {
                // Show error message about invalid connection
                setToast({
                    message: 'Invalid connection: Node types cannot be connected in this way',
                    type: 'error'
                });
            }
        },
        [nodes, setEdges, setToast]
    );

    const onNodeClick = useCallback((event, node) => {
        // Check if the clicked node is an input node
        if (node.type === 'input') {
            setSelectedInputNode(node.id);
            setIsInputModalOpen(true);
        }
    }, []);

    const handleSaveWorkflow = async () => {
        if (!workflowName.trim()) {
            setToast({
                message: 'Please enter a workflow name',
                type: 'error'
            });
            return;
        }

        try {
            const token = localStorage.getItem('token');
            const workflowData = {
                name: workflowName,
                description: '',
                nodes: nodes,
                edges: edges
            };

            const url = workflowId === '-1'
                ? 'http://localhost:8000/api/workflows'
                : `http://localhost:8000/api/workflows/${workflowId}`;

            const method = workflowId === '-1' ? 'POST' : 'PUT';

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(workflowData)
            });

            if (!response.ok) {
                throw new Error('Failed to save workflow');
            }

            const savedWorkflow = await response.json();

            // Update workflowId if this was a new workflow
            if (workflowId === '-1') {
                navigate(`/workflows/workflow/${savedWorkflow.id}`, { replace: true });
            }

            setToast({
                message: 'Workflow saved successfully!',
                type: 'success'
            });
        } catch (error) {
            console.error('Error saving workflow:', error);
            setToast({
                message: 'Failed to save workflow',
                type: 'error'
            });
        }
    };

    const handleClearWorkflow = () => {
        setNodes([]);
        setEdges([]);
    };

    const handleExecuteWorkflow = async () => {
        // Prevent multiple executions
        if (isExecuting) {
            setToast({
                message: 'Workflow is already executing',
                type: 'info'
            });
            return;
        }

        // Initial validation
        if (nodes.length === 0) {
            setToast({
                message: 'No nodes to execute in the workflow',
                type: 'error'
            });
            return;
        }

        // Check for input nodes
        const inputNodes = nodes.filter(node => node.type === 'input');
        if (inputNodes.length === 0) {
            setToast({
                message: 'Workflow must contain at least one input node',
                type: 'error'
            });
            return;
        }

        // Check for missing connections
        const unconnectedNodes = nodes.filter(node => {
            if (node.type === 'input') return false; // Input nodes don't need incoming connections
            const incomingEdges = edges.filter(edge => edge.target === node.id);
            return incomingEdges.length === 0;
        });

        if (unconnectedNodes.length > 0) {
            setToast({
                message: 'Some nodes are not connected - please complete the workflow',
                type: 'error'
            });
            return;
        }

        // Set up execution state
        setIsExecuting(true);
        setWorkflowInsights(""); // Clear previous insights

        // Initialize execution state for all nodes
        const initialState = {};
        nodes.forEach(node => {
            initialState[node.id] = {
                status: 'pending', // pending, in-progress, completed, error
                result: null,
                error: null
            };
        });
        setExecutionState(initialState);

        try {
            // Update UI to show we're starting
            setToast({
                message: 'Starting workflow execution...',
                type: 'info'
            });

            // Find the topological order of nodes for execution
            const nodeOrder = getTopologicalOrder(nodes, edges);

            // Execute nodes in topological order
            for (const nodeId of nodeOrder) {
                const node = nodes.find(n => n.id === nodeId);

                if (!node) {
                    throw new Error(`Node with ID ${nodeId} not found`);
                }

                // Update node status to in-progress
                setExecutionState(prev => {
                    const newState = Object.assign({}, prev);
                    if (prev[nodeId]) {
                        newState[nodeId] = Object.assign({}, prev[nodeId], { status: 'in-progress' });
                    } else {
                        newState[nodeId] = { status: 'in-progress', result: null, error: null };
                    }
                    return newState;
                });

                // Get input for this node from previous nodes
                const nodeInputs = await getNodeInputs(nodeId, edges, executionState);

                // Execute this node
                const result = await executeNode(node, nodeInputs);

                // Update execution state with result
                setExecutionState(prev => {
                    const newState = Object.assign({}, prev);
                    newState[nodeId] = { status: 'completed', result, error: null };
                    return newState;
                });

                // If this is an insights node, update the insights panel
                if (node.type === 'insights') {
                    setWorkflowInsights(result);
                }

                // Small delay between nodes for visual effect
                await new Promise(resolve => setTimeout(resolve, 500));
            }

            setToast({
                message: 'Workflow execution completed successfully',
                type: 'success'
            });
        } catch (error) {
            console.error('Error executing workflow:', error);
            setToast({
                message: `Workflow execution failed: ${error.message}`,
                type: 'error'
            });
        } finally {
            setIsExecuting(false);
        }
    };

    // Gets the topological order of nodes for execution
    const getTopologicalOrder = (nodes, edges) => {
        // Create a graph representation
        const graph = {};
        const inDegree = {};

        // Initialize
        nodes.forEach(node => {
            graph[node.id] = [];
            inDegree[node.id] = 0;
        });

        // Build the graph
        edges.forEach(edge => {
            graph[edge.source].push(edge.target);
            inDegree[edge.target] = (inDegree[edge.target] || 0) + 1;
        });

        // Find nodes with no incoming edges (sources)
        const queue = nodes
            .filter(node => inDegree[node.id] === 0)
            .map(node => node.id);

        const result = [];

        // Process the queue
        while (queue.length > 0) {
            const nodeId = queue.shift();
            result.push(nodeId);

            // For each neighbor, decrease in-degree and check if it becomes a source
            graph[nodeId].forEach(neighbor => {
                inDegree[neighbor]--;
                if (inDegree[neighbor] === 0) {
                    queue.push(neighbor);
                }
            });
        }

        // Check if we visited all nodes
        if (result.length !== nodes.length) {
            throw new Error('Workflow contains cycles, cannot determine execution order');
        }

        return result;
    };

    // Get inputs for a node from its incoming edges
    const getNodeInputs = async (nodeId, edges, executionState) => {
        // Find all edges that point to this node
        const incomingEdges = edges.filter(edge => edge.target === nodeId);

        // For each incoming edge, get the output of the source node
        const inputs = {};
        for (const edge of incomingEdges) {
            const sourceId = edge.source;
            const sourceState = executionState[sourceId];

            if (!sourceState || sourceState.status !== 'completed') {
                throw new Error(`Source node ${sourceId} has not completed execution`);
            }

            inputs[sourceId] = sourceState.result;
        }

        return inputs;
    };

    // Execute a single node
    const executeNode = async (node, inputs) => {
        // Based on node type, execute the appropriate logic
        switch (node.type) {
            case 'input':
                // For input nodes, just return the prompt
                return node.data.prompt || "No input provided";

            case 'researcher':
                // Call the research API
                return await executeResearcherNode(node.data.prompt || inputs[Object.keys(inputs)[0]]);

            case 'agent':
                // Execute an agent based on research results
                return await executeAgentNode(node, inputs);

            case 'insights':
                // Process agent outputs to generate insights
                return await generateInsights(inputs);

            case 'notify':
                // Notify functionality (dummy for now)
                console.log("Notification would be sent:", inputs);
                return "Notification sent";

            case 'output':
                // Publishing functionality (dummy for now)
                console.log("Content would be published:", inputs);
                return "Content published";

            default:
                throw new Error(`Unknown node type: ${node.type}`);
        }
    };

    // Execute the researcher node
    const executeResearcherNode = async (topic) => {
        try {
            const token = localStorage.getItem('token');

            // For now, we'll simulate the research by using the same endpoint used for podcast generation
            // In a real implementation, this would be a dedicated research endpoint
            setToast({
                message: 'Researching topic...',
                type: 'info'
            });

            const researchData = {
                topic: topic,
                max_tokens: 1000,
                research_only: true // Hypothetical flag to only do research
            };

            // This is a simplification - in a real implementation, we'd have a dedicated endpoint
            const response = await fetch('http://localhost:8000/generate-podcast', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(researchData)
            });

            if (!response.ok) {
                throw new Error(`Research failed with status: ${response.status}`);
            }

            const result = await response.json();

            // For demo purposes, simulate a research result if the API doesn't provide one
            const researchText = result.research ||
                `## Research on: ${topic}\n\nThis is simulated research content for demonstration purposes. In a real implementation, this would contain actual research data retrieved from various sources about "${topic}".`;

            return researchText;
        } catch (error) {
            console.error("Error in researcher node:", error);

            // For demo purposes, return a fallback response
            return `## Research on: ${topic}\n\nThis is simulated research content for demonstration purposes. In a real implementation, this would contain actual research data retrieved from various sources.`;
        }
    };

    // Execute an agent node
    const executeAgentNode = async (node, inputs) => {
        try {
            const token = localStorage.getItem('token');
            const agentId = node.data.agentId;
            const agentName = node.data.label || "Agent";

            // Get the first input (research result)
            const research = Object.values(inputs)[0];

            setToast({
                message: `Agent "${agentName}" is processing...`,
                type: 'info'
            });

            // In a real implementation, we'd use a dedicated agent endpoint
            // For now, we'll simulate the agent response

            // Wait a bit to simulate processing
            await new Promise(resolve => setTimeout(resolve, 1500));

            // Generate a simulated response based on agent type
            let agentResponse = "";
            if (agentId === 'believer') {
                agentResponse = `## Believer Agent's Perspective\n\nAs a believer in this topic, I think there are several important points to consider:\n\n1. The research shows promising evidence for this concept\n2. There are multiple credible sources supporting this view\n3. The historical patterns suggest this trend will continue\n\nI believe the data clearly demonstrates the validity of this approach.`;
            } else if (agentId === 'skeptic') {
                agentResponse = `## Skeptic Agent's Response\n\nI remain unconvinced by several aspects of this research:\n\n1. There are methodological flaws in some of the cited studies\n2. Alternative explanations haven't been fully explored\n3. The evidence isn't as robust as it initially appears\n\nWe should maintain healthy skepticism until more conclusive data is available.`;
            } else if (agentId === 'researcher') {
                agentResponse = `## Research Agent's Analysis\n\nBased on the collected information, I've identified these key findings:\n\n1. The topic has been studied across multiple disciplines\n2. There are both supporting and contradicting viewpoints\n3. Recent developments suggest new avenues for investigation\n\nFurther research is recommended in the following areas: [list of suggested research directions]`;
            } else {
                agentResponse = `## ${agentName}'s Analysis\n\nI've processed the research and have the following insights to share:\n\n1. This topic presents interesting challenges and opportunities\n2. Several patterns emerge from the available data\n3. We should consider multiple perspectives when evaluating this information\n\nMy conclusion is that this subject deserves more nuanced discussion.`;
            }

            return agentResponse;
        } catch (error) {
            console.error("Error in agent node:", error);

            // For demo purposes, return a fallback response
            return `## Agent Response\n\nThis is a simulated agent response for demonstration purposes. In a real implementation, this would contain the agent's analysis of the research.`;
        }
    };

    // Generate insights from agent outputs
    const generateInsights = async (inputs) => {
        try {
            // Get agent outputs as an array
            const agentOutputs = Object.values(inputs);

            setToast({
                message: 'Generating insights...',
                type: 'info'
            });

            // Wait a bit to simulate processing
            await new Promise(resolve => setTimeout(resolve, 1000));

            // Create a nicely formatted insights summary
            let insightsContent = `# Workflow Insights Summary\n\n`;

            // Add a section for each agent output
            agentOutputs.forEach((output, index) => {
                // Extract the first heading if it exists
                const headingMatch = String(output).match(/##\s+(.*?)(\n|$)/);
                const heading = headingMatch ? headingMatch[1] : `Agent ${index + 1} Insights`;

                insightsContent += `## ${heading}\n\n`;

                // Add the output content, removing the original heading
                const contentWithoutHeading = String(output).replace(/##\s+(.*?)(\n|$)/, '').trim();
                insightsContent += `${contentWithoutHeading}\n\n`;
            });

            // Add a conclusion section
            insightsContent += `## Conclusion\n\nThe workflow has processed inputs through research and agent analysis, producing the insights above. These represent different perspectives and analyses of the topic.`;

            return insightsContent;
        } catch (error) {
            console.error("Error generating insights:", error);

            // For demo purposes, return a fallback response
            return `# Workflow Insights Summary\n\nThis is a simulated insights summary for demonstration purposes. In a real implementation, this would contain a comprehensive analysis of all agent outputs.`;
        }
    };

    const handleAddNode = () => {
        setIsNodePanelOpen(true);
    };

    const handleNodeSelect = ({ type, agentId }) => {
        const nodeCount = nodes.length;
        const newNodeId = `${nodeCount + 1}`;

        // Calculate grid-like position for better layout
        // Start with a decent offset and use a grid pattern for placement
        const columnWidth = 250;
        const rowHeight = 150;
        const columnsPerRow = 3;

        const column = nodeCount % columnsPerRow;
        const row = Math.floor(nodeCount / columnsPerRow);

        const position = {
            x: 50 + (column * columnWidth),
            y: 50 + (row * rowHeight)
        };

        // Configure node based on type
        switch (type) {
            case 'input':
                setNodes((nds) => [...nds, createNode(
                    newNodeId,
                    position,
                    createNodeData('Input Prompt', {
                        description: 'Enter your podcast topic or question'
                    }),
                    'input'
                )]);
                break;
            case 'agent':
                const selectedAgent = agents.find(a => a.id === agentId);

                // Special handling for researcher agent
                if (selectedAgent && selectedAgent.id === 'researcher') {
                    setNodes((nds) => [...nds, createNode(
                        newNodeId,
                        position,
                        createNodeData(
                            'Research Agent',
                            {
                                agentId,
                                description: 'Gathers information and research data'
                            }
                        ),
                        'researcher'
                    )]);
                } else {
                    setNodes((nds) => [...nds, createNode(
                        newNodeId,
                        position,
                        createNodeData(
                            selectedAgent ? `${selectedAgent.name}` : 'AI Agent',
                            {
                                agentId,
                                description: selectedAgent ? `${selectedAgent.status} agent` : 'Processes and enhances content'
                            }
                        ),
                        'agent'
                    )]);
                }
                break;
            case 'insights':
                setNodes((nds) => [...nds, createNode(
                    newNodeId,
                    position,
                    createNodeData('Insights Analysis', {
                        description: 'Extract key findings and trends'
                    }),
                    'insights'
                )]);
                break;
            case 'notify':
                setNodes((nds) => [...nds, createNode(
                    newNodeId,
                    position,
                    createNodeData('Notification', {
                        description: 'Sends alerts when processing completes'
                    }),
                    'notify'
                )]);
                break;
            case 'publish':
                setNodes((nds) => [...nds, createNode(
                    newNodeId,
                    position,
                    createNodeData('YouTube Publication', {
                        description: 'Publish podcast to your channel'
                    }),
                    'output'
                )]);
                break;
            default:
                setNodes((nds) => [...nds, createNode(
                    newNodeId,
                    position,
                    createNodeData(`Node ${newNodeId}`, {
                        description: 'Custom workflow node'
                    })
                )]);
        }
    };

    const handleEditName = () => {
        setTempWorkflowName(workflowName);
        setIsEditingName(true);
    };

    const handleSaveName = () => {
        if (tempWorkflowName.trim()) {
            setWorkflowName(tempWorkflowName.trim());
            setIsEditingName(false);
        }
    };

    const handleCancelNameEdit = () => {
        setTempWorkflowName(workflowName);
        setIsEditingName(false);
    };

    const handleCreateAgents = () => {
        setIsAgentModalOpen(true);
    };

    const handleAgentClick = (agent) => {
        if (!agent.isDefault) {
            setSelectedAgent(agent);
            setIsAgentModalOpen(true);
        }
    };

    // Load custom agents
    const loadCustomAgents = async () => {
        try {
            setIsLoadingAgents(true);
            const token = localStorage.getItem('token');
            if (!token) {
                console.error('No token found');
                return;
            }

            const response = await fetch('http://localhost:8000/agents', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (!response.ok) {
                throw new Error('Failed to load agents');
            }

            const customAgents = await response.json();
            const formattedCustomAgents = customAgents.map(agent => ({
                id: agent.agent_id,
                name: agent.name,
                voice_id: agent.voice_id,
                status: 'Ready',
                isDefault: false
            }));

            // Combine default and custom agents
            setAgents([...DEFAULT_AGENTS, ...formattedCustomAgents]);
        } catch (error) {
            console.error('Error loading agents:', error);
        } finally {
            setIsLoadingAgents(false);
        }
    };

    // Load agents when modal closes
    const handleAgentModalClose = () => {
        setIsAgentModalOpen(false);
        setSelectedAgent(null);
        loadCustomAgents(); // Reload agents after modal closes
    };

    const handleInputSubmit = (nodeId, prompt) => {
        setNodes((nds) =>
            nds.map((node) => {
                if (node.id === nodeId) {
                    return {
                        ...node,
                        data: {
                            ...node.data,
                            prompt: prompt,
                            label: `Input: ${prompt.substring(0, 20)}${prompt.length > 20 ? '...' : ''}`
                        }
                    };
                }
                return node;
            })
        );
    };

    // Load workflow data if editing an existing workflow
    useEffect(() => {
        const loadWorkflow = async () => {
            if (workflowId === '-1') return; // Skip loading for new workflows

            try {
                const token = localStorage.getItem('token');
                const response = await fetch(`http://localhost:8000/api/workflows/${workflowId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('Failed to load workflow');
                }

                const workflow = await response.json();
                setWorkflowName(workflow.name);
                setTempWorkflowName(workflow.name);

                if (workflow.nodes) setNodes(workflow.nodes);

                if (workflow.edges) {
                    // Apply animation and contextual colors to existing edges
                    const nodesMap = workflow.nodes ? workflow.nodes.reduce((acc, node) => {
                        acc[node.id] = node;
                        return acc;
                    }, {}) : {};

                    const animatedEdges = workflow.edges.map(edge => {
                        // Determine source node to get its type
                        const sourceNode = nodesMap[edge.source];

                        // Set color based on source node type
                        let edgeColor = '#6366f1'; // Default color (purple)
                        if (sourceNode) {
                            switch (sourceNode.type) {
                                case 'input':
                                    edgeColor = '#6366F1'; // Input -> purple
                                    break;
                                case 'researcher':
                                    edgeColor = '#4C1D95'; // Researcher -> deep purple
                                    break;
                                case 'agent':
                                    edgeColor = '#10B981'; // Agent -> green
                                    break;
                                case 'insights':
                                    edgeColor = '#F59E0B'; // Insights -> amber
                                    break;
                                default:
                                    edgeColor = '#6366f1'; // Default
                            }
                        }

                        return {
                            ...edge,
                            type: 'custom', // Use our custom edge type
                            animated: true,
                            style: { stroke: edgeColor, strokeWidth: 2 },
                            markerEnd: {
                                type: MarkerType.ArrowClosed,
                                color: edgeColor,
                                width: 20,
                                height: 20,
                            },
                            data: { ...edge.data, sourceType: sourceNode ? sourceNode.type : 'unknown' }
                        };
                    });

                    setEdges(animatedEdges);
                }
            } catch (error) {
                console.error('Error loading workflow:', error);
                alert('Failed to load workflow');
            }
        };

        loadWorkflow();
    }, [workflowId]);

    // Initial load of agents
    useEffect(() => {
        loadCustomAgents();
    }, []);

    // Podcast generation functions
    const handleGeneratePodcast = async () => {
        if (!podcastText.trim()) {
            console.log('Please enter some text');
            return;
        }

        setIsGenerating(true);
        setSuccessMessage('');
        try {
            const response = await fetch('http://localhost:8000/generate-text-podcast', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({
                    text: podcastText,
                    voice_id: selectedVoice,
                    emotion: selectedEmotion,
                    speed: voiceSpeed
                })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.detail || 'Failed to generate podcast');
            }

            const data = await response.json();
            console.log('Podcast generated:', data);

            if (data.audio_url) {
                setAudioUrl(data.audio_url);
                setSuccessMessage('Podcast generated successfully! You can now play it below.');
            }

        } catch (error) {
            console.error('Error generating podcast:', error);
            setSuccessMessage(`Error: ${error.message}`);
        } finally {
            setIsGenerating(false);
        }
    };

    // Audio player functions
    const handlePlayPause = () => {
        if (audioRef.current) {
            if (isPlaying) {
                audioRef.current.pause();
            } else {
                audioRef.current.play();
            }
            setIsPlaying(!isPlaying);
        }
    };

    const formatTime = (time) => {
        const minutes = Math.floor(time / 60);
        const seconds = Math.floor(time % 60);
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    };

    const handleTimeUpdate = () => {
        if (audioRef.current) {
            setCurrentTime(audioRef.current.currentTime);
        }
    };

    const handleLoadedMetadata = () => {
        if (audioRef.current) {
            setDuration(audioRef.current.duration);
        }
    };

    const handleProgressClick = (e) => {
        if (audioRef.current) {
            const progressBar = e.currentTarget;
            const rect = progressBar.getBoundingClientRect();
            const clickPosition = (e.clientX - rect.left) / rect.width;
            const newTime = clickPosition * audioRef.current.duration;
            if (!isNaN(newTime)) {
                audioRef.current.currentTime = newTime;
                setCurrentTime(newTime);
            }
        }
    };

    const handleProgressMouseMove = (e) => {
        if (audioRef.current && e.buttons === 1) { // Check if primary mouse button is pressed
            const progressBar = e.currentTarget;
            const rect = progressBar.getBoundingClientRect();
            const clickPosition = (e.clientX - rect.left) / rect.width;
            const newTime = clickPosition * audioRef.current.duration;
            if (!isNaN(newTime)) {
                audioRef.current.currentTime = newTime;
                setCurrentTime(newTime);
            }
        }
    };

    // Edge class assignment based on source node type
    const getEdgeClassName = useCallback((edge) => {
        const sourceType = edge.data?.sourceType;
        if (sourceType) {
            return `animated source-${sourceType}`;
        }
        return 'animated';
    }, []);

    // Apply classes to existing edges
    useEffect(() => {
        setEdges((eds) =>
            eds.map(edge => {
                // Find source node for this edge
                const sourceNode = nodes.find(n => n.id === edge.source);
                if (sourceNode && sourceNode.type) {
                    // Update edge data with source type if not already set
                    if (!edge.data || !edge.data.sourceType) {
                        return {
                            ...edge,
                            data: {
                                ...(edge.data || {}),
                                sourceType: sourceNode.type
                            }
                        };
                    }
                }
                return edge;
            })
        );
    }, [nodes, setEdges]);

    // Function to attach edge classes to elements in DOM after they're rendered
    useEffect(() => {
        // Apply classes to edge elements based on their source type
        const edgeElements = document.querySelectorAll('.react-flow__edge');
        edgeElements.forEach(el => {
            const edgeId = el.getAttribute('data-testid')?.split('__').pop();
            if (edgeId) {
                const edge = edges.find(e => e.id === edgeId);
                if (edge && edge.data && edge.data.sourceType) {
                    el.classList.add(`source-${edge.data.sourceType}`);
                    el.classList.add('animated');
                }
            }
        });
    }, [edges]);

    // Effect to update nodes with execution state classes
    useEffect(() => {
        if (Object.keys(executionState).length === 0) return;

        setNodes(nds => nds.map(node => {
            if (executionState[node.id]) {
                const status = executionState[node.id].status;
                return {
                    ...node,
                    className: `${node.className || ''} ${status}`.trim()
                };
            }
            return node;
        }));
    }, [executionState, setNodes]);

    // OnInit callback
    const onInit = useCallback((reactFlowInstance) => {
        setRfInstance(reactFlowInstance);

        // Set initial viewport with proper zoom
        reactFlowInstance.setViewport({ x: 0, y: 0, zoom: 0.8 });

        // Center view on nodes if they exist
        if (nodes.length > 0) {
            setTimeout(() => {
                reactFlowInstance.fitView({ padding: 0.2, includeHiddenNodes: false });
            }, 100);
        }
    }, [nodes]);

    return (
        <div className="editor-container">
            <div className="editor-header">
                <h1>Build out a workflow for your podcast generation <TiFlowMerge /></h1>
                <button className="back-button" onClick={() => navigate('/workflows')}>
                    <FaArrowLeft /> Back to Workflows
                </button>
            </div>
            <div className="editor-content">
                <div className="editor-main">
                    <div className="flow-controls">
                        <div className="workflow-name-container">
                            {isEditingName ? (
                                <>
                                    <input
                                        type="text"
                                        value={tempWorkflowName}
                                        onChange={(e) => setTempWorkflowName(e.target.value)}
                                        placeholder="Enter workflow name..."
                                        className="workflow-name-input"
                                    />
                                    <button
                                        className="name-action-button save"
                                        onClick={handleSaveName}
                                        title="Save name"
                                    >
                                        <FaCheck />
                                    </button>
                                    <button
                                        className="name-action-button cancel"
                                        onClick={handleCancelNameEdit}
                                        title="Cancel"
                                    >
                                        <FaTimes />
                                    </button>
                                </>
                            ) : (
                                <>
                                    <div onClick={handleEditName} className="workflow-name-display">
                                        {workflowName || 'Untitled Workflow'}
                                    </div>
                                    <button
                                        className="name-action-button edit"
                                        onClick={handleEditName}
                                        title="Edit name"
                                    >
                                        <FaPencilAlt />
                                    </button>
                                </>
                            )}
                        </div>
                        <button className="flow-button save-workflow" onClick={handleSaveWorkflow}>
                            <FaSave />
                            <span>Save</span>
                        </button>
                        <button className="flow-button clear-workflow" onClick={handleClearWorkflow}>
                            <FaTrash />
                            <span>Clear</span>
                        </button>
                        <button className={`flow-button execute-workflow ${isExecuting ? 'executing' : ''}`} onClick={handleExecuteWorkflow} disabled={isExecuting}>
                            {isExecuting ? (
                                <>
                                    <div className="button-spinner"></div>
                                    <span>Running</span>
                                </>
                            ) : (
                                <>
                                    <FaPlay />
                                    <span>Run</span>
                                </>
                            )}
                        </button>
                        <button className="flow-button add-node" onClick={handleAddNode}>
                            <FaPlus />
                            <span>Add</span>
                        </button>
                    </div>
                    <div className="flow-wrapper">
                        <ReactFlow
                            nodes={nodes}
                            edges={edges}
                            onNodesChange={onNodesChange}
                            onEdgesChange={onEdgesChange}
                            onConnect={onConnect}
                            nodeTypes={customNodeTypes}
                            defaultEdgeOptions={defaultEdgeOptions}
                            edgesFocusable={true}
                            edgesUpdatable={true}
                            elementsSelectable={true}
                            onInit={onInit}
                            defaultViewport={{ x: 0, y: 0, zoom: 0.8 }}
                            attributionPosition="bottom-left"
                            className="workflow-reactflow"
                            deleteKeyCode={['Backspace', 'Delete']}
                            edgeTypes={edgeTypes}
                            maxZoom={2}
                            minZoom={0.2}
                            proOptions={{ hideAttribution: true }}
                            onNodeClick={onNodeClick}
                        >
                            <Controls />
                            <Background variant={BackgroundVariant.Dots} gap={12} size={1} />
                            <MiniMap />
                        </ReactFlow>
                    </div>
                </div>
                <div className="editor-insights">
                    <div
                        className="toggle-insights"
                        onClick={() => setIsInsightsEnabled(!isInsightsEnabled)}
                        style={{ cursor: 'pointer' }}
                        title={isInsightsEnabled ? "Click to disable insights" : "Click to enable insights"}
                    >
                        <h2>{isInsightsEnabled ? "Workflow Insights" : "Text to Podcast"}</h2>
                        {isInsightsEnabled ? <BsToggle2On style={{ marginLeft: '10px' }} /> : <BsToggle2Off style={{ marginLeft: '10px' }} />}
                    </div>

                    <div className="insights-content">
                        {isExecuting ? (
                            <div className="loading-insights">
                                <p>Executing workflow... Please wait.</p>
                                <div className="execution-loader"></div>
                            </div>
                        ) : workflowInsights ? (
                            <div className="insights-result">
                                <pre>{workflowInsights}</pre>
                            </div>
                        ) : isInsightsEnabled ? (
                            <p>
                                Workflow insights are now active. You'll see real-time analytics and insights about your workflow here.
                            </p>
                        ) : (
                            <div className="podcast-generation-form">
                                <div className="voice-controls">
                                    <div className="voice-select-group">
                                        <label>Voice:</label>
                                        <select
                                            value={selectedVoice}
                                            onChange={(e) => setSelectedVoice(e.target.value)}
                                        >
                                            {voices.map(voice => (
                                                <option key={voice.id} value={voice.id}>
                                                    {voice.name}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                    <div className="voice-select-group">
                                        <label>Emotion:</label>
                                        <select
                                            value={selectedEmotion}
                                            onChange={(e) => setSelectedEmotion(e.target.value)}
                                        >
                                            {emotions.map(emotion => (
                                                <option key={emotion.id} value={emotion.id}>
                                                    {emotion.name}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                    <div className="voice-select-group">
                                        <label>Speed: {voiceSpeed}x</label>
                                        <input
                                            type="range"
                                            min="0.5"
                                            max="2.0"
                                            step="0.1"
                                            value={voiceSpeed}
                                            onChange={(e) => setVoiceSpeed(parseFloat(e.target.value))}
                                            className="speed-slider"
                                        />
                                    </div>
                                </div>
                                <textarea
                                    value={podcastText}
                                    onChange={(e) => setPodcastText(e.target.value)}
                                    placeholder="Enter your text here to generate a podcast..."
                                    rows={8}
                                    className="podcast-text-input"
                                />
                                <button
                                    className="generate-button"
                                    onClick={handleGeneratePodcast}
                                    disabled={isGenerating || !podcastText.trim()}
                                >
                                    {isGenerating ? 'Generating...' : 'Generate Podcast'}
                                </button>
                                {successMessage && (
                                    <div className={`generation-message ${successMessage.includes('Error') ? 'error' : 'success'}`}>
                                        {successMessage}
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                </div>
                <div className="editor-sidebar">
                    <div className="sidebar-card agents-view">
                        <h3><RiRobot2Fill /> Create your agents</h3>
                        <div className="agents-list">
                            {isLoadingAgents ? (
                                <div className="loading-agents">Loading agents...</div>
                            ) : (
                                agents.map((agent) => (
                                    <div
                                        key={agent.id}
                                        className={`agent-item ${agent.isDefault ? 'default' : 'custom'}`}
                                        onClick={() => handleAgentClick(agent)}
                                        style={{ cursor: agent.isDefault ? 'default' : 'pointer' }}
                                    >
                                        <span className="agent-name">{agent.name}</span>
                                        <span className="agent-status">{agent.status}</span>
                                    </div>
                                ))
                            )}
                        </div>
                        <button
                            className="create-agents-btn"
                            onClick={() => setIsAgentModalOpen(true)}
                            type="button"
                        >
                            <FaUserCog /> Create your own agents
                        </button>
                        <p>Design and configure AI agents with unique personalities and roles for your podcast</p>
                    </div>
                    <div className="sidebar-card podcast-audio-view">
                        <h3><FaVolumeUp /> Podcast Preview</h3>
                        <div className="audio-player">
                            <audio
                                ref={audioRef}
                                src={audioUrl}
                                onTimeUpdate={handleTimeUpdate}
                                onLoadedMetadata={handleLoadedMetadata}
                                onEnded={() => setIsPlaying(false)}
                                onPause={() => setIsPlaying(false)}
                                onPlay={() => setIsPlaying(true)}
                            />
                            <div className="player-controls">
                                <button
                                    className="play-button"
                                    onClick={handlePlayPause}
                                    disabled={!audioUrl}
                                >
                                    {isPlaying ? <FaPause /> : <FaPlay />}
                                </button>
                                <div
                                    className="progress-bar"
                                    onClick={handleProgressClick}
                                    onMouseMove={handleProgressMouseMove}
                                >
                                    <div
                                        className="progress"
                                        style={{
                                            width: `${duration > 0 ? (currentTime / duration) * 100 : 0}%`
                                        }}
                                    />
                                </div>
                                <div className="time-display">
                                    {formatTime(currentTime)} / {formatTime(duration)}
                                </div>
                            </div>
                        </div>
                        <p>Preview your generated podcast audio</p>
                    </div>
                </div>
            </div>
            <NodeSelectionPanel
                isOpen={isNodePanelOpen}
                onClose={() => setIsNodePanelOpen(false)}
                agents={agents}
                onSelectNode={handleNodeSelect}
            />
            <InputNodeModal
                isOpen={isInputModalOpen}
                onClose={() => setIsInputModalOpen(false)}
                onSubmit={handleInputSubmit}
                nodeId={selectedInputNode}
            />
            <AgentModal
                isOpen={isAgentModalOpen}
                onClose={handleAgentModalClose}
                editAgent={selectedAgent}
            />
            {toast.message && (
                <div className="workflow-toast-container">
                    <WorkflowToast
                        message={toast.message}
                        type={toast.type}
                        onClose={() => setToast(initialToastState)}
                    />
                </div>
            )}
        </div>
    );
};

export default WorkflowEditor;