File size: 36,612 Bytes
d0a6b4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>SVM 3D Simulator</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Babel for JSX (Standalone) -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Outfit:wght@400;500;700&display=swap" rel="stylesheet">

    <!-- Import Map to resolve dependencies -->
    <script type="importmap">

    {

        "imports": {

            "react": "https://esm.sh/react@18.2.0",

            "react-dom/client": "https://esm.sh/react-dom@18.2.0/client",

            "react-dom": "https://esm.sh/react-dom@18.2.0",

            "three": "https://esm.sh/three@0.161.0",

            "@react-three/fiber": "https://esm.sh/@react-three/fiber@8.15.16?external=react,react-dom,three",

            "@react-three/drei": "https://esm.sh/@react-three/drei@9.102.0?external=react,react-dom,three,@react-three/fiber"

        }

    }

    </script>
     {% raw %} 

    <style>

        :root {

            --font-sans: 'Inter', sans-serif;

            --font-display: 'Outfit', sans-serif;

        }

        body {

            font-family: var(--font-sans);

            background-color: #020817;

            color: #f8fafc;

            margin: 0;

            overflow: hidden;

            touch-action: none; /* Prevent scrolling on mobile while interacting with canvas */

        }

        .font-display { font-family: var(--font-display); }

        

        /* Glassmorphism */

        .glass-panel {

            background: rgba(15, 23, 42, 0.75);

            backdrop-filter: blur(12px);

            border: 1px solid rgba(255, 255, 255, 0.1);

            border-radius: 0.75rem;

            box-shadow: 0 4px 30px rgba(0, 0, 0, 0.2);

        }



        /* Animations */

        @keyframes slideUp {

            from { opacity: 0; transform: translateY(20px); }

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

        }

        .animate-slide-up {

            animation: slideUp 0.6s ease-out forwards;

        }

        

        @keyframes pulseGlow {

            0%, 100% { box-shadow: 0 0 5px #ffd60a; }

            50% { box-shadow: 0 0 15px #ffd60a; }

        }

        .animate-pulse-glow {

            animation: pulseGlow 2s infinite;

        }



        /* Neon Text Effects */

        .neon-text-primary { text-shadow: 0 0 10px rgba(56, 189, 248, 0.5); }

        .neon-text-accent { text-shadow: 0 0 10px rgba(255, 214, 10, 0.5); }



        /* Custom Scrollbar */

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

        ::-webkit-scrollbar-track { background: transparent; }

        ::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.2); border-radius: 3px; }

        ::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.3); }

        

        /* Hide scrollbar for clean mobile UI but allow scroll */

        .no-scrollbar::-webkit-scrollbar { display: none; }

        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }



        /* Button Glows */

        .glow-primary { box-shadow: 0 0 15px rgba(56, 189, 248, 0.3); }

        .glow-accent { box-shadow: 0 0 15px rgba(255, 214, 10, 0.3); }

        

        .bg-classA { background-color: #00d4ff; }

        .bg-classB { background-color: #ff006e; }

        .bg-supportVector { background-color: #ffd60a; }

        .bg-hyperplane { background-color: #44ff44; }

        .bg-marginLineSVM { background-color: #ef4444; }

    </style>
</head>
<body>
    <div id="root"></div>

    <script type="text/babel" data-type="module">

        import React, { useState, useEffect, useCallback, useMemo, useRef, Suspense, createContext, useContext } from 'react';

        import { createRoot } from 'react-dom/client';

        import * as THREE from 'three';

        import { Canvas, useFrame } from '@react-three/fiber';

        import { OrbitControls, Stars, Grid } from '@react-three/drei';



        // --- Utils: Icons ---

        const PlayIcon = ({ className }) => (

            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><polygon points="5 3 19 12 5 21 5 3"/></svg>

        );

        const RotateCcwIcon = ({ className }) => (

            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74-2.74L3 12"/><path d="M3 3v9h9"/></svg>

        );

        const EyeIcon = ({ className }) => (

            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>

        );

        const EyeOffIcon = ({ className }) => (

            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/></svg>

        );

        const LayersIcon = ({ className }) => (

            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/><path d="m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65"/><path d="m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65"/></svg>

        );

        const ChevronLeftIcon = ({ className }) => (

            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="m15 18-6-6 6-6"/></svg>

        );

        const ChevronRightIcon = ({ className }) => (

            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><path d="m9 18 6-6-6-6"/></svg>

        );



        // --- Utils: SVM Logic ---

        const generateSVMData = () => {

            const points = [];

            const w1 = 0.5, w2 = -0.3, b = 0.5;

            

            for(let i=0; i<40; i++) {

                const x = (Math.random() - 0.5) * 8;

                const z = (Math.random() - 0.5) * 8;

                const boundaryY = -(w1 * x + w2 * z + b);

                const isClassA = Math.random() > 0.5;

                const gap = 0.8 + Math.random() * 2;

                const y = isClassA ? boundaryY + gap : boundaryY - gap;

                points.push({ position: [x, y, z], classLabel: isClassA ? 1 : -1 });

            }

            return points;

        };



        const computeHyperplane = (dataPoints) => ({ w1: 0.5, w2: -0.3, b: 0.5 });



        const findSupportVectors = (dataPoints, params, margin) => {

            const indices = [];

            const { w1, w2, b } = params;

            dataPoints.forEach((point, index) => {

                const [x, y, z] = point.position;

                const predictedY = -(w1 * x + w2 * z + b);

                const distance = Math.abs(y - predictedY);

                if (distance < margin + 0.5) indices.push(index);

            });

            return indices;

        };



        // --- UI Components ---

        const Button = ({ children, variant = 'default', size = 'default', className = '', ...props }) => {

            const baseStyles = "inline-flex items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 touch-manipulation";

            const variants = {

                default: "bg-slate-100 text-slate-900 hover:bg-slate-100/90 shadow",

                outline: "border border-slate-700 bg-slate-900/50 hover:bg-slate-800 text-slate-100",

                ghost: "hover:bg-slate-800 text-slate-100"

            };

            const sizes = {

                default: "h-8 md:h-9 px-3 md:px-4 py-1 md:py-2 text-xs md:text-sm",

                sm: "h-7 md:h-8 rounded-md px-2 md:px-3 text-[10px] md:text-xs",

                icon: "h-8 w-8 md:h-9 md:w-9"

            };

            return (

                <button className={`${baseStyles} ${variants[variant]} ${sizes[size]} ${className}`} {...props}>

                    {children}

                </button>

            );

        };



        // Toast System

        const ToastContext = createContext(null);

        const ToastProvider = ({ children }) => {

            const [toasts, setToasts] = useState([]);

            

            const addToast = useCallback((message, type = 'info') => {

                const id = Date.now();

                setToasts(prev => [...prev, { id, message, type }]);

                setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);

            }, []);



            return (

                <ToastContext.Provider value={addToast}>

                    {children}

                    <div className="fixed bottom-20 left-4 right-4 md:bottom-4 md:right-4 md:left-auto md:w-auto z-[60] flex flex-col gap-2 pointer-events-none">

                        {toasts.map(t => (

                            <div key={t.id} className={`p-4 rounded-lg shadow-lg text-sm font-medium animate-slide-up mx-auto md:mx-0 w-full md:w-72 text-center md:text-left ${

                                t.type === 'success' ? 'bg-green-600/90 text-white backdrop-blur' : 'bg-slate-800/90 text-white border border-slate-700 backdrop-blur'

                            }`}>{t.message}</div>

                        ))}

                    </div>

                </ToastContext.Provider>

            );

        };

        const useToast = () => {

            const context = useContext(ToastContext);

            if (!context) throw new Error("useToast must be used within ToastProvider");

            return { info: (msg) => context(msg, 'info'), success: (msg) => context(msg, 'success') };

        };





        // --- 3D Components ---

        const DataPoint = ({ position, classLabel, isSupportVector }) => {

            const meshRef = useRef(null);

            const glowRef = useRef(null);

            useFrame((state) => {

                if (meshRef.current) {

                    meshRef.current.position.y = position[1] + Math.sin(state.clock.elapsedTime * 2 + position[0]) * 0.03;

                    if (isSupportVector) meshRef.current.scale.setScalar(1 + Math.sin(state.clock.elapsedTime * 3) * 0.15);

                }

                if (glowRef.current && isSupportVector) glowRef.current.rotation.z = state.clock.elapsedTime * 0.5;

            });

            const color = classLabel === 1 ? "#00d4ff" : "#ff006e";

            const size = isSupportVector ? 0.28 : 0.22;

            return (

                <group position={position}>

                    <mesh ref={meshRef}>

                        <sphereGeometry args={[size, 32, 32]} />

                        <meshPhongMaterial color={color} emissive={color} emissiveIntensity={isSupportVector ? 1 : 0.6} shininess={100} />

                    </mesh>

                    <mesh>

                        <sphereGeometry args={[size * 0.6, 16, 16]} />

                        <meshBasicMaterial color={color} transparent opacity={0.9} />

                    </mesh>

                    <mesh>

                        <sphereGeometry args={[size * 1.4, 16, 16]} />

                        <meshBasicMaterial color={color} transparent opacity={0.15} />

                    </mesh>

                    {isSupportVector && (

                        <mesh ref={glowRef} rotation={[Math.PI / 2, 0, 0]}>

                            <torusGeometry args={[0.4, 0.03, 16, 32]} />

                            <meshBasicMaterial color="#ffd60a" transparent opacity={0.8} />

                        </mesh>

                    )}

                </group>

            );

        };



        const Hyperplane = ({ params }) => {

            const meshRef = useRef(null);

            useFrame((state) => {

                if (meshRef.current) meshRef.current.material.emissiveIntensity = 0.3 + Math.sin(state.clock.elapsedTime * 2) * 0.1;

            });

            const geometry = useMemo(() => {

                const { w1, w2, b } = params;

                const size = 7;

                const segments = 30;

                const positions = [], colors = [], indices = [];

                for (let i = 0; i <= segments; i++) {

                    for (let j = 0; j <= segments; j++) {

                        const x = (i / segments - 0.5) * size * 2;

                        const z = (j / segments - 0.5) * size * 2;

                        const y = -(w1 * x + w2 * z + b);

                        const clampedY = Math.max(-4, Math.min(4, y));

                        positions.push(x, clampedY, z);

                        const normalizedY = (clampedY + 4) / 8;

                        const normalizedX = i / segments;

                        colors.push(0.2 + normalizedX * 0.8, 0.8 - normalizedY * 0.6, 0.4);

                    }

                }

                for (let i = 0; i < segments; i++) {

                    for (let j = 0; j < segments; j++) {

                        const a = i * (segments + 1) + j;

                        const b_idx = a + 1;

                        const c = a + segments + 1;

                        const d = c + 1;

                        indices.push(a, b_idx, c);

                        indices.push(b_idx, d, c);

                    }

                }

                const geo = new THREE.BufferGeometry();

                geo.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));

                geo.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));

                geo.setIndex(indices);

                geo.computeVertexNormals();

                return geo;

            }, [params]);

            const wireframeGeometry = useMemo(() => new THREE.WireframeGeometry(geometry), [geometry]);

            return (

                <group>

                    <mesh ref={meshRef} geometry={geometry}>

                        <meshPhongMaterial vertexColors transparent opacity={0.6} side={THREE.DoubleSide} emissive="#44ff44" emissiveIntensity={0.2} shininess={100} />

                    </mesh>

                    <lineSegments geometry={wireframeGeometry}>

                        <lineBasicMaterial color="#00ffff" transparent opacity={0.3} />

                    </lineSegments>

                </group>

            );

        };



        const MarginPlanes = ({ params, margin }) => {

            const createPlaneGeometry = (offset) => {

                const { w1, w2, b } = params;

                const size = 6;

                const segments = 20;

                const positions = [], indices = [];

                for (let i = 0; i <= segments; i++) {

                    for (let j = 0; j <= segments; j++) {

                        const x = (i / segments - 0.5) * size * 2;

                        const z = (j / segments - 0.5) * size * 2;

                        const y = -(w1 * x + w2 * z + b) + offset;

                        positions.push(x, Math.max(-3, Math.min(3, y)), z);

                    }

                }

                for (let i = 0; i < segments; i++) {

                    for (let j = 0; j < segments; j++) {

                        const a = i * (segments + 1) + j;

                        const b_idx = a + 1;

                        const c = a + segments + 1;

                        const d = c + 1;

                        indices.push(a, b_idx, c);

                        indices.push(b_idx, d, c);

                    }

                }

                const geo = new THREE.BufferGeometry();

                geo.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));

                geo.setIndex(indices);

                geo.computeVertexNormals();

                return geo;

            };

            const upperGeometry = useMemo(() => createPlaneGeometry(margin), [params, margin]);

            const lowerGeometry = useMemo(() => createPlaneGeometry(-margin), [params, margin]);

            const color = '#ef4444';

            return (

                <>

                    <mesh geometry={upperGeometry}><meshStandardMaterial color={color} transparent opacity={0.4} side={THREE.DoubleSide} emissive={color} emissiveIntensity={0.2} /></mesh>

                    <mesh geometry={lowerGeometry}><meshStandardMaterial color={color} transparent opacity={0.4} side={THREE.DoubleSide} emissive={color} emissiveIntensity={0.2} /></mesh>

                </>

            );

        };



        const GridFloor = () => (

            <Grid position={[0, -3, 0]} args={[20, 20]} cellSize={1} cellThickness={0.5} cellColor="#1a3a4a" sectionSize={5} sectionThickness={1} sectionColor="#2a5a6a" fadeDistance={25} fadeStrength={1} infiniteGrid={true} />

        );



        const Scene3D = ({ dataPoints, supportVectorIndices, showHyperplane, showMargins, hyperplaneParams, margin, sceneRotation }) => (

            <Canvas camera={{ position: [8, 6, 8], fov: 50 }}>

                <Suspense fallback={null}>

                    <group rotation={[0, sceneRotation, 0]}>

                        <ambientLight intensity={0.4} />

                        <pointLight position={[10, 10, 10]} intensity={1.5} color="#00d4ff" />

                        <pointLight position={[-10, 10, -10]} intensity={1} color="#ff006e" />

                        <pointLight position={[0, -10, 0]} intensity={0.5} color="#ffd60a" />

                        <directionalLight position={[5, 5, 5]} intensity={0.8} />

                        <spotLight position={[0, 15, 0]} intensity={1} angle={0.5} penumbra={0.5} color="#ffffff" />

                        <Stars radius={100} depth={50} count={3000} factor={4} saturation={0} fade speed={1} />

                        <GridFloor />

                        {dataPoints.map((point, index) => (

                            <DataPoint key={index} position={point.position} classLabel={point.classLabel} isSupportVector={supportVectorIndices.includes(index)} />

                        ))}

                        {showHyperplane && <Hyperplane params={hyperplaneParams} />}

                        {showMargins && showHyperplane && <MarginPlanes params={hyperplaneParams} margin={margin} />}

                    </group>

                    <OrbitControls enablePan={true} enableZoom={true} enableRotate={true} minDistance={5} maxDistance={30} autoRotateSpeed={0.5} />

                </Suspense>

            </Canvas>

        );



        // --- Panel Components ---

        const ControlPanel = ({ 

            showHyperplane, onToggleHyperplane, 

            showMargins, onToggleMargins, 

            onRegenerateData, onRunAlgorithm, 

            isRunning, margin, onMarginChange,

            isResultView, onResetView

        }) => {

            // NEW: Result View Logic for Mobile Optimization

            if (isResultView) {

                return (

                    <div className="glass-panel p-3 md:p-4 animate-slide-up w-full text-center">

                        <div className="bg-green-500/20 border border-green-500/50 rounded-lg p-2 mb-3">

                            <p className="text-green-400 text-sm font-semibold flex items-center justify-center gap-2">

                                <span className="relative flex h-3 w-3">

                                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>

                                  <span className="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>

                                </span>

                                Separation Complete

                            </p>

                        </div>

                        <Button onClick={onResetView} className="w-full bg-slate-700 hover:bg-slate-600 text-white shadow-lg h-10 font-bold border border-slate-600">

                            <RotateCcwIcon className="w-4 h-4 mr-2" />

                            Continue Editing

                        </Button>

                    </div>

                );

            }



            // Default View

            return (

                <div className="glass-panel p-3 md:p-4 space-y-2 md:space-y-4 animate-slide-up w-full">

                    <h2 className="font-display text-lg font-bold text-white neon-text-primary hidden md:block">Controls</h2>

                    <div className="space-y-2">

                        <Button onClick={onRunAlgorithm} disabled={isRunning} className="w-full bg-green-500 hover:bg-green-600 text-white glow-primary font-semibold shadow-lg">

                            <PlayIcon className="w-4 h-4 mr-2" />

                            {isRunning ? "Running..." : "Find Hyperplane"}

                        </Button>

                        <Button onClick={onRegenerateData} variant="outline" className="w-full shadow-lg">

                            <RotateCcwIcon className="w-4 h-4 mr-2" />

                            New Data Points

                        </Button>

                    </div>

                    <div className="space-y-2">

                        <label className="text-sm text-slate-400 hidden md:block">Visibility</label>

                        <div className="flex gap-2">

                            <Button variant={showHyperplane ? "default" : "outline"} size="sm" onClick={onToggleHyperplane} className="flex-1">

                                {showHyperplane ? <EyeIcon className="w-4 h-4" /> : <EyeOffIcon className="w-4 h-4" />}

                                <span className="ml-2">Plane</span>

                            </Button>

                            <Button variant={showMargins ? "default" : "outline"} size="sm" onClick={onToggleMargins} className="flex-1">

                                <LayersIcon className="w-4 h-4" />

                                <span className="ml-2">Margins</span>

                            </Button>

                        </div>

                    </div>

                    <div className="space-y-2 hidden md:block">

                        <label className="text-sm text-slate-400">Margin Width: {margin.toFixed(2)}</label>

                        <input type="range" min="0.3" max="2" step="0.1" value={margin} onChange={(e) => onMarginChange(parseFloat(e.target.value))} className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-cyan-500" />

                    </div>

                </div>

            );

        };



        const LegendPanel = () => (

            <div className="glass-panel p-3 md:p-4 space-y-2 md:space-y-3 animate-slide-up w-full">

                <h2 className="font-display text-lg font-bold hidden md:block">Legend</h2>

                <div className="space-y-2 text-xs md:text-sm">

                    <div className="flex items-center gap-3"><div className="w-4 h-4 rounded-full bg-classA glow-primary flex-shrink-0" /><span className="text-slate-200">Class A (Positive)</span></div>

                    <div className="flex items-center gap-3"><div className="w-4 h-4 rounded-full bg-classB shadow-[0_0_10px_#ff006e] flex-shrink-0" /><span className="text-slate-200">Class B (Negative)</span></div>

                    <div className="flex items-center gap-3"><div className="w-4 h-4 rounded-full bg-supportVector glow-accent animate-pulse-glow flex-shrink-0" /><span className="text-slate-200">Support Vectors</span></div>

                    <div className="flex items-center gap-3"><div className="w-4 h-2 rounded bg-hyperplane opacity-60 flex-shrink-0" /><span className="text-slate-200">Decision Boundary</span></div>

                    <div className="flex items-center gap-3"><div className="w-4 h-2 rounded opacity-80 bg-marginLineSVM flex-shrink-0" /><span className="text-slate-200">Margin Boundaries (Red)</span></div>

                </div>

            </div>

        );



        const TutorialPanel = () => {

            const [currentStep, setCurrentStep] = useState(0);

            const svmSteps = [

                { title: "What is SVM?", content: "Support Vector Machine (SVM) finds the best boundary (hyperplane) to separate two classes." },

                { title: "Data Points", content: "Cyan points are Class A, Magenta are Class B. The goal is to separate them cleanly." },

                { title: "The Hyperplane", content: "The green transparent surface is the decision boundary. One side is A, the other B." },

                { title: "Support Vectors", content: "YELLOW glowing points are Support Vectors! They define where the boundary sits." },

                { title: "The Margin (Red)", content: "RED planes show the MARGIN. SVM maximizes this street width. Points should be OUTSIDE." },

                { title: "Max Margin", content: "A wider margin means the model is more confident and generalizes better." },

            ];

            const steps = svmSteps;

            const nextStep = () => setCurrentStep(prev => Math.min(prev + 1, steps.length - 1));

            const prevStep = () => setCurrentStep(prev => Math.max(prev - 1, 0));

            return (

                <div className="glass-panel p-3 md:p-4 space-y-2 md:space-y-4 animate-slide-up w-full">

                    <div className="flex items-center justify-between">

                        <h2 className="font-display text-md md:text-lg font-bold neon-text-accent">Learn SVM</h2>

                        <span className="text-xs text-slate-400">{currentStep + 1} / {steps.length}</span>

                    </div>

                    <div className="min-h-[60px] md:min-h-[100px]">

                        <h3 className="font-display text-sm md:text-md text-cyan-400 mb-1 md:mb-2 font-semibold">{steps[currentStep].title}</h3>

                        <p className="text-xs md:text-sm text-slate-300 leading-relaxed">{steps[currentStep].content}</p>

                    </div>

                    <div className="flex items-center justify-between gap-2">

                        <Button variant="outline" size="sm" onClick={prevStep} disabled={currentStep === 0}><ChevronLeftIcon className="w-4 h-4" /></Button>

                        <div className="flex gap-1">

                            {steps.map((_, i) => (

                                <div key={i} className={`w-1.5 h-1.5 rounded-full transition-all ${i === currentStep ? "bg-yellow-400 scale-125" : i < currentStep ? "bg-cyan-500/50" : "bg-slate-700"}`} />

                            ))}

                        </div>

                        <Button variant="outline" size="sm" onClick={nextStep} disabled={currentStep === steps.length - 1}><ChevronRightIcon className="w-4 h-4" /></Button>

                    </div>

                </div>

            );

        };



        // --- Main App Component ---

        const App = () => {

            const toast = useToast();

            const [dataPoints, setDataPoints] = useState([]);

            const [supportVectorIndices, setSupportVectorIndices] = useState([]);

            const [hyperplaneParams, setHyperplaneParams] = useState({ w1: 0.3, w2: 0.1, b: 0 });

            const [margin, setMargin] = useState(0.8);

            const [showHyperplane, setShowHyperplane] = useState(false);

            const [showMargins, setShowMargins] = useState(false);

            const [isRunning, setIsRunning] = useState(false);

            const [sceneRotation, setSceneRotation] = useState(0);

            

            // New state for mobile toggle

            const [isResultView, setIsResultView] = useState(false);



            const regenerateData = useCallback(() => {

                const newData = generateSVMData();

                setDataPoints(newData);

                setSupportVectorIndices([]);

                setShowHyperplane(false);

                setShowMargins(false);

                setIsResultView(false); // Reset view on new data

                if(dataPoints.length > 0) toast.success(`Generated ${newData.length} new data points!`);

            }, [toast, dataPoints.length]);



            useEffect(() => { 

                regenerateData(); 

            }, []); 



            const runAlgorithm = async () => {

                setIsRunning(true);

                toast.info("Finding optimal hyperplane...");

                await new Promise(r => setTimeout(r, 800));

                

                const params = computeHyperplane(dataPoints);

                setHyperplaneParams(params);

                setShowHyperplane(true);

                

                await new Promise(r => setTimeout(r, 500));

                

                const svIndices = findSupportVectors(dataPoints, params, margin);

                setSupportVectorIndices(svIndices);

                setShowMargins(true);

                

                setIsRunning(false);

                setIsResultView(true); // Switch to result view

                toast.success(`Found ${svIndices.length} support vectors!`);

            };



            return (

                <div className="h-[100dvh] w-full bg-slate-950 overflow-hidden relative font-sans text-slate-100">

                    {/* Header */}

                    <header className="absolute top-0 left-0 right-0 z-40 p-3 md:p-6 pointer-events-none bg-gradient-to-b from-slate-950/80 to-transparent">

                        <div className="flex flex-col md:flex-row items-center md:items-start justify-between gap-2 md:gap-4 pointer-events-auto">

                            <div className="text-center md:text-left">

                                <h1 className="font-display text-xl md:text-3xl font-bold text-white neon-text-primary">SVM 3D Simulator</h1>

                                <p className="text-xs md:text-sm text-slate-400 mt-1 hidden md:block">Interactive Machine Learning Visualization</p>

                            </div>

                            <div className="hidden md:flex items-center gap-2 text-sm text-slate-500 backdrop-blur-sm bg-slate-900/30 p-2 rounded-full border border-slate-800">

                                <span>🖱️ Drag to rotate</span>

                                <span></span>

                                <span>🔍 Scroll to zoom</span>

                            </div>

                        </div>

                    </header>



                    {/* 3D Scene */}

                    <div className="absolute inset-0 z-0">

                        <Scene3D 

                            dataPoints={dataPoints} 

                            supportVectorIndices={supportVectorIndices} 

                            showHyperplane={showHyperplane} 

                            showMargins={showMargins} 

                            hyperplaneParams={hyperplaneParams} 

                            margin={margin}

                            sceneRotation={sceneRotation}

                        />

                    </div>



                    {/* Controls Container: Mobile Top, Desktop Left */}

                    <div className="absolute left-4 right-4 md:right-auto top-[4.5rem] md:top-28 md:w-64 space-y-3 md:space-y-4 z-30 max-h-[45vh] overflow-y-auto md:max-h-none md:overflow-visible no-scrollbar">

                        <ControlPanel 

                            showHyperplane={showHyperplane} 

                            onToggleHyperplane={() => setShowHyperplane(!showHyperplane)}

                            showMargins={showMargins}

                            onToggleMargins={() => setShowMargins(!showMargins)}

                            onRegenerateData={regenerateData}

                            onRunAlgorithm={runAlgorithm}

                            isRunning={isRunning}

                            margin={margin}

                            onMarginChange={setMargin}

                            isResultView={isResultView}

                            onResetView={() => setIsResultView(false)}

                        />

                        {/* Hide legend in result view on mobile to save space if needed, though instruction said only buttons invisible */}

                        <LegendPanel />

                    </div>



                    {/* Tutorial Container: Mobile Bottom, Desktop Right */}

                    <div className="absolute left-4 right-4 md:left-auto md:right-4 bottom-20 md:bottom-auto md:top-28 md:w-72 z-20">

                        <TutorialPanel />

                    </div>



                    {/* Rotation Slider: Hidden on Mobile */}

                    <div className="hidden md:flex absolute right-6 top-1/2 -translate-y-1/2 z-20 items-center justify-center bg-slate-900/80 p-3 rounded-xl border border-slate-700 backdrop-blur-md">

                        <div className="flex flex-col items-center gap-2 h-64 w-8 relative">

                            <span className="text-xs font-medium text-slate-300 absolute -top-6">Rot</span>

                            <input 

                                type="range" 

                                min={0} 

                                max={Math.PI * 2} 

                                step={0.01} 

                                value={sceneRotation} 

                                onChange={(e) => setSceneRotation(parseFloat(e.target.value))} 

                                className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-56 h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-cyan-500 -rotate-90 origin-center" 

                            />

                        </div>

                    </div>



                    {/* Footer */}

                    <footer className="absolute bottom-4 left-0 right-0 z-10 text-center pointer-events-none">

                         <div className="absolute left-1/2 -translate-x-1/2 bottom-0 w-full flex flex-col items-center gap-2 pointer-events-auto pb-4 md:pb-0">

                            <p className="hidden md:block text-xs text-slate-500 backdrop-blur-sm px-3 py-1 rounded-full mb-2">

                                Click "Find Hyperplane" to see the algorithm in action!

                            </p>

                            

                            <a href="/svm" onClick={() => {}} className="inline-flex items-center justify-center text-center leading-none bg-blue-600 hover:bg-blue-500 text-white font-bold py-3 px-8 md:py-2 md:px-6 rounded-xl text-sm transition-all duration-150 shadow-[0_4px_0_rgb(29,78,216)] active:shadow-none active:translate-y-[4px] uppercase tracking-wider">

                                Back to Core

                            </a>

                        </div>

                    </footer>

                </div>

            );

        };



        const Root = () => (<ToastProvider><App /></ToastProvider>);

        const root = createRoot(document.getElementById('root'));

        root.render(<Root />);

    </script>
   {% endraw %}
</body>
</html>