File size: 22,314 Bytes
c2ea5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
import React, { useMemo } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { useAgentGraph } from "@/context/AgentGraphContext";
import { Network, BarChart3, Target, Activity } from "lucide-react";

interface ConnectedComponent {
  id: number;
  nodeIds: string[];
  size: number;
  density: number;
  maxDegree: number;
  avgDegree: number;
}

interface DegreeDistribution {
  [degree: number]: {
    count: number;
    percentage: number;
    entityTypes: string[];
  };
}

interface StructuralPattern {
  type: "star" | "chain" | "cluster" | "hub" | "isolated";
  description: string;
  nodeIds: string[];
  centralNodeId?: string;
  score: number;
}

interface StructuralData {
  totalNodes: number;
  totalEdges: number;
  networkDensity: number;
  avgDegree: number;
  maxDegree: number;
  connectedComponents: ConnectedComponent[];
  degreeDistribution: DegreeDistribution;
  structuralPatterns: StructuralPattern[];
  networkHealth: number;
  isolatedNodes: string[];
}

export function StructuralConnectivityAnalysis() {
  const { state } = useAgentGraph();

  const structuralData = useMemo<StructuralData>(() => {
    const nodeMap = new Map<
      string,
      { id: string; type: string; name: string }
    >();
    const adjacencyList = new Map<string, Set<string>>();
    const edgeSet = new Set<string>();

    // Process all traces and their knowledge graphs
    state.traces.forEach((trace) => {
      trace.knowledge_graphs?.forEach((kg: any) => {
        if (kg.graph_data) {
          try {
            const graphData =
              typeof kg.graph_data === "string"
                ? JSON.parse(kg.graph_data)
                : kg.graph_data;

            // Build node map
            if (graphData.entities && Array.isArray(graphData.entities)) {
              graphData.entities.forEach((entity: any) => {
                nodeMap.set(entity.id, {
                  id: entity.id,
                  type: entity.type || "Unknown",
                  name: entity.name || entity.id,
                });
                adjacencyList.set(entity.id, new Set());
              });
            }

            // Build adjacency list and count edges
            if (graphData.relations && Array.isArray(graphData.relations)) {
              graphData.relations.forEach((relation: any) => {
                const sourceId = relation.source;
                const targetId = relation.target;
                const edgeKey = [sourceId, targetId].sort().join("-");

                if (
                  nodeMap.has(sourceId) &&
                  nodeMap.has(targetId) &&
                  !edgeSet.has(edgeKey)
                ) {
                  adjacencyList.get(sourceId)?.add(targetId);
                  adjacencyList.get(targetId)?.add(sourceId);
                  edgeSet.add(edgeKey);
                }
              });
            }
          } catch (error) {
            console.warn("Error parsing graph_data:", error);
          }
        }
      });
    });

    const totalNodes = nodeMap.size;
    const totalEdges = edgeSet.size;

    // Calculate basic metrics
    const networkDensity =
      totalNodes > 1 ? (2 * totalEdges) / (totalNodes * (totalNodes - 1)) : 0;

    const degrees = Array.from(adjacencyList.values()).map(
      (neighbors) => neighbors.size
    );
    const avgDegree =
      degrees.length > 0
        ? Math.round(
            (degrees.reduce((sum, d) => sum + d, 0) / degrees.length) * 10
          ) / 10
        : 0;
    const maxDegree = Math.max(...degrees, 0);

    // Find connected components using DFS
    const visited = new Set<string>();
    const connectedComponents: ConnectedComponent[] = [];

    const dfs = (nodeId: string, component: string[]): void => {
      if (visited.has(nodeId)) return;
      visited.add(nodeId);
      component.push(nodeId);

      const neighbors = adjacencyList.get(nodeId) || new Set();
      neighbors.forEach((neighborId) => {
        if (!visited.has(neighborId)) {
          dfs(neighborId, component);
        }
      });
    };

    let componentId = 0;
    nodeMap.forEach((_, nodeId) => {
      if (!visited.has(nodeId)) {
        const component: string[] = [];
        dfs(nodeId, component);

        if (component.length > 0) {
          const componentEdges =
            component.reduce((count, nodeId) => {
              const neighbors = adjacencyList.get(nodeId) || new Set();
              const internalNeighbors = Array.from(neighbors).filter((n) =>
                component.includes(n)
              );
              return count + internalNeighbors.length;
            }, 0) / 2; // Divide by 2 since each edge is counted twice

          const componentDensity =
            component.length > 1
              ? (2 * componentEdges) /
                (component.length * (component.length - 1))
              : 0;

          const componentDegrees = component.map(
            (nodeId) => (adjacencyList.get(nodeId) || new Set()).size
          );

          connectedComponents.push({
            id: componentId++,
            nodeIds: component,
            size: component.length,
            density: Math.round(componentDensity * 1000) / 1000,
            maxDegree: Math.max(...componentDegrees, 0),
            avgDegree:
              componentDegrees.length > 0
                ? Math.round(
                    (componentDegrees.reduce((sum, d) => sum + d, 0) /
                      componentDegrees.length) *
                      10
                  ) / 10
                : 0,
          });
        }
      }
    });

    // Calculate degree distribution
    const degreeDistribution: DegreeDistribution = {};
    Array.from(nodeMap.entries()).forEach(([nodeId, node]) => {
      const degree = (adjacencyList.get(nodeId) || new Set()).size;
      if (!degreeDistribution[degree]) {
        degreeDistribution[degree] = {
          count: 0,
          percentage: 0,
          entityTypes: [],
        };
      }
      degreeDistribution[degree].count++;
      if (!degreeDistribution[degree].entityTypes.includes(node.type)) {
        degreeDistribution[degree].entityTypes.push(node.type);
      }
    });

    // Calculate percentages
    Object.values(degreeDistribution).forEach((dist) => {
      dist.percentage =
        totalNodes > 0 ? Math.round((dist.count / totalNodes) * 100) : 0;
    });

    // Identify structural patterns
    const structuralPatterns: StructuralPattern[] = [];

    // Find star patterns (one central node with many connections, others mostly connected to center)
    Array.from(nodeMap.keys()).forEach((nodeId) => {
      const neighbors = adjacencyList.get(nodeId) || new Set();
      if (neighbors.size >= 3) {
        // Check if this is a potential star center
        const neighborDegrees = Array.from(neighbors).map(
          (nId) => (adjacencyList.get(nId) || new Set()).size
        );
        const avgNeighborDegree =
          neighborDegrees.reduce((sum, d) => sum + d, 0) /
          neighborDegrees.length;

        if (neighbors.size >= avgNeighborDegree * 1.5) {
          structuralPatterns.push({
            type: "star",
            description: `Star pattern centered on ${
              nodeMap.get(nodeId)?.name
            }`,
            nodeIds: [nodeId, ...Array.from(neighbors)],
            centralNodeId: nodeId,
            score: neighbors.size,
          });
        }
      }
    });

    // Find hub patterns (nodes with significantly higher degree than average)
    const degreeThreshold = avgDegree * 2;
    Array.from(nodeMap.keys()).forEach((nodeId) => {
      const degree = (adjacencyList.get(nodeId) || new Set()).size;
      if (degree >= degreeThreshold && degree >= 4) {
        structuralPatterns.push({
          type: "hub",
          description: `High-degree hub: ${nodeMap.get(nodeId)?.name}`,
          nodeIds: [nodeId],
          centralNodeId: nodeId,
          score: degree,
        });
      }
    });

    // Find chain patterns (nodes with degree 2 in sequence)
    const visited_chains = new Set<string>();
    Array.from(nodeMap.keys()).forEach((nodeId) => {
      if (visited_chains.has(nodeId)) return;

      const neighbors = adjacencyList.get(nodeId) || new Set();
      if (neighbors.size === 2) {
        // Start building a chain
        const chain = [nodeId];
        visited_chains.add(nodeId);

        let current: string = nodeId;
        let prev: string | null = null;

        // Follow the chain
        let maxChainLength = 50; // Prevent infinite loops
        while (maxChainLength-- > 0) {
          const currentNeighbors = Array.from(
            adjacencyList.get(current) || new Set<string>()
          );
          const next = currentNeighbors.find((n: string) => n !== prev);

          if (!next || visited_chains.has(next)) break;

          const nextNeighbors = adjacencyList.get(next) || new Set();
          if (nextNeighbors.size > 2) break; // End of chain

          chain.push(next);
          visited_chains.add(next);
          prev = current;
          current = next;

          if (nextNeighbors.size === 1) break; // End node
        }

        if (chain.length >= 3) {
          structuralPatterns.push({
            type: "chain",
            description: `Chain of ${chain.length} nodes`,
            nodeIds: chain,
            score: chain.length,
          });
        }
      }
    });

    // Find isolated nodes
    const isolatedNodes = Array.from(nodeMap.keys()).filter(
      (nodeId) => (adjacencyList.get(nodeId) || new Set()).size === 0
    );

    // Calculate network health (0-100)
    const healthFactors = {
      connectivity:
        connectedComponents.length === 1
          ? 100
          : Math.max(0, 100 - connectedComponents.length * 10),
      isolation:
        isolatedNodes.length === 0
          ? 100
          : Math.max(0, 100 - isolatedNodes.length * 20),
      density: Math.min(100, networkDensity * 200), // Scale density to 0-100
      distribution:
        avgDegree > 0
          ? Math.min(100, (1 - (maxDegree - avgDegree) / maxDegree) * 100)
          : 100,
    };

    const networkHealth = Math.round(
      healthFactors.connectivity * 0.3 +
        healthFactors.isolation * 0.3 +
        healthFactors.density * 0.2 +
        healthFactors.distribution * 0.2
    );

    // Sort patterns by score
    structuralPatterns.sort((a, b) => b.score - a.score);

    return {
      totalNodes,
      totalEdges,
      networkDensity: Math.round(networkDensity * 1000) / 1000,
      avgDegree,
      maxDegree,
      connectedComponents: connectedComponents.sort((a, b) => b.size - a.size),
      degreeDistribution,
      structuralPatterns: structuralPatterns.slice(0, 6),
      networkHealth,
      isolatedNodes,
    };
  }, [state.traces]);

  const getHealthColor = (health: number) => {
    if (health >= 80) return "text-green-600";
    if (health >= 60) return "text-yellow-600";
    if (health >= 40) return "text-orange-600";
    return "text-red-600";
  };

  const getPatternColor = (type: string) => {
    const colorMap: { [key: string]: string } = {
      star: "bg-yellow-100 text-yellow-800 border-yellow-200",
      hub: "bg-red-100 text-red-800 border-red-200",
      chain: "bg-blue-100 text-blue-800 border-blue-200",
      cluster: "bg-green-100 text-green-800 border-green-200",
      isolated: "bg-gray-100 text-gray-800 border-gray-200",
    };
    return colorMap[type] || "bg-gray-100 text-gray-800 border-gray-200";
  };

  const getTypeColor = (index: number) => {
    const colors = [
      "bg-blue-500",
      "bg-green-500",
      "bg-yellow-500",
      "bg-purple-500",
      "bg-pink-500",
      "bg-indigo-500",
    ];
    return colors[index % colors.length];
  };

  if (structuralData.totalNodes === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Network className="h-5 w-5" />
            Structural Connectivity Analysis
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8 text-muted-foreground">
            <Network className="h-12 w-12 mx-auto mb-4 opacity-50" />
            <p>No structural data available</p>
            <p className="text-sm">
              Generate some knowledge graphs to see connectivity analysis
            </p>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* Summary Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-blue-100">
                <Network className="h-4 w-4 text-blue-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Network Density</p>
                <p className="text-2xl font-bold">
                  {structuralData.networkDensity}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-green-100">
                <Target className="h-4 w-4 text-green-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Components</p>
                <p className="text-2xl font-bold">
                  {structuralData.connectedComponents.length}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-purple-100">
                <BarChart3 className="h-4 w-4 text-purple-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Avg Degree</p>
                <p className="text-2xl font-bold">{structuralData.avgDegree}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-orange-100">
                <Activity className="h-4 w-4 text-orange-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Network Health</p>
                <p
                  className={`text-2xl font-bold ${getHealthColor(
                    structuralData.networkHealth
                  )}`}
                >
                  {structuralData.networkHealth}%
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Connected Components */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Target className="h-5 w-5" />
              Connected Components
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {structuralData.connectedComponents
                .slice(0, 6)
                .map((component, index) => (
                  <div
                    key={component.id}
                    className="flex items-center justify-between p-3 rounded-lg border"
                  >
                    <div className="flex items-center gap-3">
                      <div
                        className={`w-2 h-2 rounded-full ${getTypeColor(
                          index
                        )}`}
                      />
                      <div>
                        <p className="font-medium">
                          Component {component.id + 1}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {component.size} nodes • Density: {component.density}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <Badge variant="outline">
                        Max: {component.maxDegree}
                      </Badge>
                      <Badge variant="outline">
                        Avg: {component.avgDegree}
                      </Badge>
                    </div>
                  </div>
                ))}
              {structuralData.isolatedNodes.length > 0 && (
                <div className="flex items-center justify-between p-3 rounded-lg border border-dashed border-gray-300">
                  <div className="flex items-center gap-3">
                    <div className="w-2 h-2 rounded-full bg-gray-400" />
                    <div>
                      <p className="font-medium text-gray-600">
                        Isolated Nodes
                      </p>
                      <p className="text-sm text-muted-foreground">
                        {structuralData.isolatedNodes.length} disconnected nodes
                      </p>
                    </div>
                  </div>
                  <Badge className="bg-gray-100 text-gray-800 border-gray-200">
                    Isolated
                  </Badge>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Structural Patterns */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <BarChart3 className="h-5 w-5" />
              Structural Patterns
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {structuralData.structuralPatterns.length > 0 ? (
                structuralData.structuralPatterns.map((pattern, index) => (
                  <div
                    key={index}
                    className="flex items-center justify-between p-3 rounded-lg border"
                  >
                    <div className="flex items-center gap-3">
                      <div
                        className={`w-2 h-2 rounded-full ${getTypeColor(
                          index
                        )}`}
                      />
                      <div>
                        <p className="font-medium capitalize">
                          {pattern.type} Pattern
                        </p>
                        <p
                          className="text-sm text-muted-foreground truncate"
                          title={pattern.description}
                        >
                          {pattern.description}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <Badge className={getPatternColor(pattern.type)}>
                        {pattern.type.toUpperCase()}
                      </Badge>
                      <Badge variant="outline">
                        {Math.round(pattern.score)}
                      </Badge>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-center py-4 text-muted-foreground">
                  <p className="text-sm">No significant patterns detected</p>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Degree Distribution */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Activity className="h-5 w-5" />
            Degree Distribution
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {Object.entries(structuralData.degreeDistribution)
              .sort(([a], [b]) => parseInt(a) - parseInt(b))
              .slice(0, 8)
              .map(([degree, stats], index) => (
                <div key={degree} className="p-4 rounded-lg border">
                  <div className="flex items-center gap-2 mb-2">
                    <div
                      className={`w-3 h-3 rounded-full ${getTypeColor(index)}`}
                    />
                    <h4 className="font-medium">Degree {degree}</h4>
                  </div>
                  <div className="space-y-1 text-sm">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">Nodes:</span>
                      <span>{stats.count}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">Percentage:</span>
                      <span>{stats.percentage}%</span>
                    </div>
                    <div className="mt-2">
                      <p className="text-muted-foreground text-xs mb-1">
                        Entity Types:
                      </p>
                      <div className="flex flex-wrap gap-1">
                        {stats.entityTypes
                          .slice(0, 3)
                          .map((type: string, _typeIndex: number) => (
                            <Badge
                              key={type}
                              variant="outline"
                              className="text-xs"
                            >
                              {type}
                            </Badge>
                          ))}
                        {stats.entityTypes.length > 3 && (
                          <Badge variant="outline" className="text-xs">
                            +{stats.entityTypes.length - 3}
                          </Badge>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}