File size: 28,890 Bytes
52664bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f70079
52664bd
5f70079
 
 
 
11cfd59
52664bd
 
 
b43bb21
52664bd
 
 
 
 
 
b43bb21
 
52664bd
 
1122dc2
c0a49a0
11cfd59
1122dc2
 
 
 
11cfd59
1122dc2
 
 
 
 
 
b43bb21
1122dc2
5f70079
 
1122dc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0a49a0
5f70079
52664bd
 
11cfd59
52664bd
 
 
 
b43bb21
52664bd
 
 
 
b43bb21
 
 
52664bd
b43bb21
 
52664bd
 
 
b43bb21
52664bd
 
 
 
 
 
 
602dee7
b43bb21
602dee7
 
b43bb21
602dee7
 
 
b43bb21
602dee7
 
b43bb21
602dee7
b43bb21
602dee7
b43bb21
602dee7
 
 
 
 
 
11cfd59
 
 
2ace750
 
11cfd59
602dee7
b43bb21
 
 
 
 
602dee7
 
 
b43bb21
602dee7
 
2ace750
602dee7
52664bd
 
 
 
 
 
b43bb21
59defa2
 
 
 
 
 
 
 
 
 
 
 
 
b43bb21
 
59defa2
 
b43bb21
602dee7
 
 
52664bd
b43bb21
 
52664bd
b43bb21
 
3e54b00
5fd934d
 
 
 
 
 
 
 
 
3e54b00
 
 
5fd934d
 
 
 
 
 
 
 
 
3e54b00
 
 
 
 
 
 
b43bb21
 
d38a670
130282f
 
 
3e54b00
 
130282f
 
 
 
 
 
 
66ca194
 
130282f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66ca194
 
130282f
 
d38a670
66ca194
 
130282f
66ca194
130282f
 
 
 
 
 
 
 
 
 
 
b43bb21
 
130282f
 
b43bb21
 
 
130282f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d38a670
 
130282f
66ca194
d38a670
 
66ca194
 
 
b43bb21
 
 
 
 
52664bd
c0a49a0
 
 
 
 
ded15bd
b43bb21
c0a49a0
 
 
b43bb21
9b36dc8
c0a49a0
 
b43bb21
5f70079
 
c0a49a0
5f70079
b43bb21
c0a49a0
 
 
b43bb21
5f70079
c0a49a0
 
b43bb21
 
c0a49a0
 
 
 
 
 
 
ded15bd
b43bb21
 
 
9b36dc8
 
52664bd
b43bb21
 
52664bd
b43bb21
52664bd
2ace750
52664bd
1122dc2
52664bd
 
b43bb21
1122dc2
 
 
 
dc1f1ca
1122dc2
 
dc1f1ca
 
 
 
 
 
 
 
 
b43bb21
dc1f1ca
 
 
1122dc2
b43bb21
1122dc2
b43bb21
 
59defa2
52664bd
 
 
b43bb21
 
52664bd
b43bb21
59defa2
cd1edf4
d446aea
 
 
 
 
 
 
6b5217b
cd1edf4
d446aea
cd1edf4
 
 
 
d446aea
 
 
 
 
 
 
 
 
cd1edf4
 
 
 
 
6b5217b
b43bb21
cd1edf4
 
697e972
 
 
cd1edf4
697e972
 
 
 
 
 
 
cd1edf4
697e972
cd1edf4
697e972
 
 
 
 
 
 
 
 
cd1edf4
 
 
697e972
 
cd1edf4
 
 
 
 
 
 
 
9b5c530
 
 
 
 
 
 
 
 
 
 
d446aea
 
 
9b5c530
 
d446aea
cd1edf4
 
697e972
cd1edf4
697e972
 
 
cd1edf4
697e972
cd1edf4
697e972
 
cd1edf4
 
 
 
 
d446aea
cd1edf4
 
697e972
cd1edf4
 
697e972
d446aea
 
 
 
 
 
 
 
 
 
 
697e972
 
d446aea
cd1edf4
59defa2
cd1edf4
 
6b5217b
b43bb21
 
602dee7
d446aea
b43bb21
d446aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b43bb21
52664bd
9b5c530
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d446aea
cd1edf4
52664bd
b43bb21
 
52664bd
b43bb21
52664bd
7ce2c5a
 
 
2c9cc82
 
 
7ce2c5a
 
 
2c9cc82
7ce2c5a
2c9cc82
 
7ce2c5a
2c9cc82
 
 
01d5cda
 
 
 
7ce2c5a
 
01d5cda
 
 
 
 
 
 
 
 
 
 
 
 
 
2ace750
7ce2c5a
 
01d5cda
5f70079
01d5cda
 
 
 
 
 
 
 
 
2ace750
7ce2c5a
01d5cda
 
2ace750
01d5cda
 
 
7ce2c5a
01d5cda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ce2c5a
 
01d5cda
7ce2c5a
01d5cda
 
 
 
 
 
 
 
7ce2c5a
 
 
01d5cda
7ce2c5a
 
 
 
 
 
01d5cda
7ce2c5a
 
01d5cda
7ce2c5a
52664bd
7ce2c5a
01d5cda
7ce2c5a
01d5cda
7ce2c5a
4f6e170
52664bd
2c9cc82
 
52664bd
2c9cc82
52664bd
11cfd59
 
52664bd
 
11cfd59
6b5217b
b43bb21
d060704
 
 
 
 
52664bd
 
 
b43bb21
 
 
52664bd
 
 
 
b43bb21
52664bd
 
 
b43bb21
 
52664bd
 
 
b43bb21
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
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
/**
 * Automated Tutorial Video Creator
 * 
 * This script automates browser interactions to create a tutorial video
 * showing how to use CodePractice AI website.
 * 
 * Usage: node scripts/create-tutorial-video.js
 */

const { chromium } = require('playwright');
const path = require('path');
const fs = require('fs');

// Configuration
const CONFIG = {
  // Website URL (local or production)
  websiteUrl: process.env.WEBSITE_URL || 'http://localhost:3000',
  
  // Video output settings
  outputDir: path.join(__dirname, '../tutorial-videos'),
  videoFileName: `tutorial-${new Date().toISOString().split('T')[0]}.mp4`,
  
  // Timing settings (in milliseconds) - 3x faster
  delays: {
    short: 15,       // Quick pause
    medium: 30,      // Normal pause
    long: 60,        // Longer pause
    typing: 3,       // Delay between keystrokes (very fast)
    scroll: 0,       // No scroll animation
  },
  
  // Code to type in the editor
  sampleCode: `def twoSum(nums, target):
    num_map = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in num_map:
            return [num_map[complement], i]
        num_map[num] = i
    return []
`,
};

// Helper function to move hand cursor to target with smooth animation
// Cursor continues from last position to new position
async function moveHandToTarget(page, toX, toY) {
  // Get current cursor position
  const currentPos = await page.evaluate(() => {
    if (window.getPlaywrightCursorPos) {
      return window.getPlaywrightCursorPos();
    }
    return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
  });
  
  const fromX = currentPos.x;
  const fromY = currentPos.y;
  
  // Calculate distance and steps for smooth animation (3x faster)
  const distance = Math.sqrt(Math.pow(toX - fromX, 2) + Math.pow(toY - fromY, 2));
  const steps = Math.max(3, Math.min(15, Math.floor(distance / 30))); // Much fewer steps for very fast movement
  const stepDelay = 3; // 3ms per step for very fast animation
  
  // Animate cursor movement
  for (let i = 0; i <= steps; i++) {
    const progress = i / steps;
    // Use easing function for smooth movement (ease-in-out)
    const eased = progress < 0.5 
      ? 2 * progress * progress 
      : 1 - Math.pow(-2 * progress + 2, 2) / 2;
    
    const currentX = fromX + (toX - fromX) * eased;
    const currentY = fromY + (toY - fromY) * eased;
    
    // Move mouse
    await page.mouse.move(currentX, currentY);
    
    // Update visual cursor indicator
    await page.evaluate(({ x, y }) => {
      if (window.movePlaywrightCursor) {
        window.movePlaywrightCursor(x, y);
      }
    }, { x: currentX, y: currentY });
    
    // Small delay for smooth animation
    await page.waitForTimeout(stepDelay);
  }
  
  // Small pause at target
  await page.waitForTimeout(15);
}

// No scrolling - keep page fixed

async function createTutorialVideo() {
  console.log('🎬 Starting tutorial video creation...');
  
  // Ensure output directory exists
  if (!fs.existsSync(CONFIG.outputDir)) {
    fs.mkdirSync(CONFIG.outputDir, { recursive: true });
  }
  
  const outputPath = path.join(CONFIG.outputDir, CONFIG.videoFileName);
  console.log(`πŸ“Ή Output: ${outputPath}`);
  
  const browser = await chromium.launch({
    headless: false,
    args: ['--start-maximized'],
  });
  
  const context = await browser.newContext({
    viewport: null,
    recordVideo: {
      dir: CONFIG.outputDir,
      size: { width: 1920, height: 1080 },
    },
  });
  
  const page = await context.newPage();
  
  // Inject cursor indicator
  async function injectCursorIndicator() {
    await page.evaluate(() => {
      if (document.getElementById('playwright-cursor-indicator')) return;
      
      const cursorIndicator = document.createElement('div');
      cursorIndicator.id = 'playwright-cursor-indicator';
      cursorIndicator.innerHTML = 'πŸ‘†';
      cursorIndicator.style.cssText = `
        position: fixed;
        z-index: 999999;
        pointer-events: none;
        font-size: 24px;
        transform: translate(-50%, -50%);
        transition: none;
      `;
      document.body.appendChild(cursorIndicator);
      
      let mouseX = window.innerWidth / 2;
      let mouseY = window.innerHeight / 2;
      
      window.movePlaywrightCursor = function(x, y) {
        mouseX = x;
        mouseY = y;
        cursorIndicator.style.left = mouseX + 'px';
        cursorIndicator.style.top = mouseY + 'px';
      };
      
      window.getPlaywrightCursorPos = function() {
        return { x: mouseX, y: mouseY };
      };
      
      document.addEventListener('mousedown', () => {
        cursorIndicator.innerHTML = 'πŸ‘‡';
      });
      
      document.addEventListener('mouseup', () => {
        cursorIndicator.innerHTML = 'πŸ‘†';
      });
    });
  }
  
  try {
    console.log('🌐 Navigating to website...');
    await page.goto(CONFIG.websiteUrl, { waitUntil: 'networkidle' });
    await page.waitForTimeout(CONFIG.delays.long);
    
    // Wait for Next.js to fully hydrate
    console.log('⏳ Waiting for page to fully load...');
    try {
      await page.waitForFunction(() => {
        const body = document.body;
        if (!body) return false;
        const hasButtons = body.querySelectorAll('button').length > 0;
        const hasContent = body.textContent && body.textContent.length > 100;
        const isNotLoading = !body.textContent?.includes('self.__next_f') || 
                            (body.textContent.length > 500 && !body.textContent.startsWith('(self.__next_f'));
        return hasButtons && hasContent && isNotLoading;
      }, { timeout: 15000 });
      console.log('βœ… Page fully loaded');
    } catch (e) {
      console.log('⚠️ Page load timeout, continuing...');
      await page.waitForTimeout(2000);
    }
    
    await page.waitForTimeout(200);
    await injectCursorIndicator();
    console.log('βœ… Cursor indicator injected');
    
    // ============================================
    // TASK 1: Close sign up modal
    // Mouse starts from center, moves to close button
    // ============================================
    console.log('πŸ“‹ Task 1: Closing sign up modal...');
    
    // Wait for modal to appear and check if it exists
    await page.waitForTimeout(2000);
    
    // Clear localStorage to ensure modal shows (if needed)
    await page.evaluate(() => {
      localStorage.removeItem('betaSignupDismissed');
    });
    
    // Wait a bit more for modal to appear after clearing localStorage
    await page.waitForTimeout(500);
    
    // Check if modal is visible
    const modalVisible = await page.evaluate(() => {
      // Check for backdrop with z-50
      const backdrop = document.querySelector('.fixed.inset-0.z-50, .fixed.inset-0[class*="z-"]');
      // Check for modal content
      const modalContent = document.querySelector('[class*="rounded-2xl"][class*="shadow-2xl"]');
      // Check for Maybe Later button
      const maybeLaterBtn = Array.from(document.querySelectorAll('button')).find(btn => 
        btn.textContent?.includes('Maybe Later')
      );
      return !!(backdrop || modalContent || maybeLaterBtn);
    });
    
    if (!modalVisible) {
      console.log('ℹ️ No signup modal found, continuing...');
    } else {
      console.log('βœ… Signup modal detected');
    }
    
    let signupClosed = false;
    
    // Method 1: Try "Maybe Later" button (most reliable for BetaSignupModal)
    try {
      const maybeLaterBtn = page.locator('button:has-text("Maybe Later")').first();
      const isVisible = await maybeLaterBtn.isVisible({ timeout: 3000 }).catch(() => false);
      if (isVisible) {
        const btnBox = await maybeLaterBtn.boundingBox();
        if (btnBox) {
          await moveHandToTarget(page, btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2);
          await maybeLaterBtn.click({ timeout: 2000 });
          await page.waitForTimeout(200);
          signupClosed = true;
          console.log('βœ… Sign up modal closed (via Maybe Later button)');
        }
      }
    } catch (e) {
      // Continue to next method
    }
    
    // Method 2: Try close button with aria-label="Close" (X icon)
    if (!signupClosed) {
      try {
        const closeBtn = page.locator('button[aria-label="Close"]').first();
        if (await closeBtn.isVisible({ timeout: 1000 }).catch(() => false)) {
          const btnBox = await closeBtn.boundingBox();
          if (btnBox) {
            await moveHandToTarget(page, btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2);
            await closeBtn.click({ timeout: 2000 });
            await page.waitForTimeout(200);
            signupClosed = true;
            console.log('βœ… Sign up modal closed (via Close button)');
          }
        }
      } catch (e) {
        // Continue
      }
    }
    
    // Method 3: Try clicking backdrop (closes modal)
    if (!signupClosed) {
      try {
        const backdrop = page.locator('.fixed.inset-0.bg-black\\/50').first();
        if (await backdrop.isVisible({ timeout: 1000 }).catch(() => false)) {
          const backdropBox = await backdrop.boundingBox();
          if (backdropBox) {
            // Click on backdrop (not center, slightly offset)
            await moveHandToTarget(page, backdropBox.x + 100, backdropBox.y + 100);
            await page.mouse.click(backdropBox.x + 100, backdropBox.y + 100);
            await page.waitForTimeout(200);
            signupClosed = true;
            console.log('βœ… Sign up modal closed (via backdrop click)');
          }
        }
      } catch (e) {
        // Continue
      }
    }
    
    // Method 4: Use page.evaluate to find and click close button
    if (!signupClosed) {
      const modalClosed = await page.evaluate(() => {
        // Find button with aria-label="Close"
        const closeBtn = document.querySelector('button[aria-label="Close"]');
        if (closeBtn) {
          closeBtn.click();
          return true;
        }
        // Find "Maybe Later" button
        const buttons = Array.from(document.querySelectorAll('button'));
        const maybeLater = buttons.find(btn => btn.textContent?.includes('Maybe Later'));
        if (maybeLater) {
          maybeLater.click();
          return true;
        }
        // Click backdrop
        const backdrop = document.querySelector('.fixed.inset-0.bg-black\\/50, [class*="backdrop"]');
        if (backdrop) {
          backdrop.click();
          return true;
        }
        return false;
      });
      
      if (modalClosed) {
        await page.waitForTimeout(200);
        signupClosed = true;
        console.log('βœ… Sign up modal closed (via evaluate)');
      }
    }
    
    // Method 5: Try Escape key
    if (!signupClosed) {
      await page.keyboard.press('Escape');
      await page.waitForTimeout(200);
      console.log('⚠️ Used Escape key to close modal');
    }
    
    // Verify modal is closed
    await page.waitForTimeout(200);
    
    // ============================================
    // TASK 2: Skip the tour
    // Mouse continues from previous position (close button or center)
    // ============================================
    console.log('πŸ“‹ Task 2: Skipping tour...');
    
    const skipTourSelectors = [
      'button:has-text("Skip")',
      'button:has-text("Skip Tour")',
      'button[class*="skip"]',
    ];
    
    let tourSkipped = false;
    for (const selector of skipTourSelectors) {
      try {
        const skipBtn = page.locator(selector).first();
        const isVisible = await skipBtn.isVisible({ timeout: 2000 }).catch(() => false);
        if (isVisible) {
          const btnBox = await skipBtn.boundingBox();
          if (btnBox) {
            await moveHandToTarget(page, btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2);
            await skipBtn.click({ timeout: 2000 });
            await page.waitForTimeout(60);
            
            for (let i = 0; i < 3; i++) {
              const overlayGone = await page.evaluate(() => {
                const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\]');
                return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent;
              });
              if (overlayGone) break;
              await page.waitForTimeout(30);
            }
            
            tourSkipped = true;
            console.log('βœ… Tour skipped');
            break;
          }
        }
      } catch (e) {
        // Continue
      }
    }
    
    if (!tourSkipped) {
      await page.keyboard.press('Escape');
      await page.waitForTimeout(30);
    }
    
    // ============================================
    // TASK 3: Click on recommend question button
    // Mouse continues from previous position (Skip button)
    // ============================================
    console.log('πŸ“‹ Task 3: Clicking Start Recommended Problem...');
    
    const startButton = page.locator('#tour-start-recommended-button, button:has-text("Start Recommended Problem"), button:has-text("Start Recommended")').first();
    
    if (await startButton.isVisible({ timeout: 5000 }).catch(() => false)) {
      const startBox = await startButton.boundingBox();
      if (startBox) {
        await moveHandToTarget(page, startBox.x + startBox.width / 2, startBox.y + startBox.height / 2);
        
        const navigationPromise = Promise.race([
          page.waitForNavigation({ waitUntil: 'networkidle', timeout: 15000 }).catch(() => null),
          page.waitForLoadState('networkidle', { timeout: 15000 }).catch(() => null),
          page.waitForURL(url => url.pathname === '/practice', { timeout: 15000 }).catch(() => null),
        ]);
        
        try {
          await startButton.click({ timeout: 2000 });
        } catch (e) {
          await page.evaluate((buttonId) => {
            const btn = document.getElementById(buttonId) || 
                       Array.from(document.querySelectorAll('button')).find(b => 
                         b.textContent?.includes('Start Recommended Problem') || 
                         b.textContent?.includes('Start Recommended')
                       );
            if (btn) btn.click();
          }, 'tour-start-recommended-button');
          await page.waitForTimeout(500);
        }
        
        console.log('⏳ Waiting for navigation...');
        await navigationPromise;
        await page.waitForTimeout(200);
        console.log('βœ… Navigated to practice page');
      }
    }
    
    // ============================================
    // TASK 4: On practice page, skip the tour
    // Mouse continues from previous position (Recommended button)
    // ============================================
    console.log('πŸ“‹ Task 4: Skipping tour on practice page...');
    
    // Wait for practice page to fully load and tour to appear
    await page.waitForTimeout(1500);
    
    // Clear practice tour completion to ensure it shows
    await page.evaluate(() => {
      localStorage.removeItem('practiceTourCompleted');
    });
    await page.waitForTimeout(500);
    
    // Check if tour overlay is present
    let tourPresent = await page.evaluate(() => {
      const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]');
      return !!tourOverlay;
    });
    
    // If not found, wait a bit more and check again
    if (!tourPresent) {
      await page.waitForTimeout(1000);
      tourPresent = await page.evaluate(() => {
        const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]');
        return !!tourOverlay;
      });
    }
    
    if (!tourPresent) {
      console.log('ℹ️ No tour found on practice page, continuing...');
    } else {
      console.log('βœ… Tour detected on practice page');
    }
    
    let practiceTourSkipped = false;
    
    // Method 1: Try to find Skip button using page.evaluate (most reliable)
    // Wait a bit for tour to fully render
    await page.waitForTimeout(500);
    
    const skipFound = await page.evaluate(() => {
      // First, find the tour overlay/modal
      const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]');
      if (!tourOverlay) return false;
      
      // Find Skip button - look for exact text match first
      const buttons = Array.from(tourOverlay.querySelectorAll('button, [role="button"]'));
      let skipBtn = buttons.find(btn => {
        const text = (btn.textContent || '').toLowerCase().trim();
        return text === 'skip';
      });
      
      // If not found, try partial match
      if (!skipBtn) {
        skipBtn = buttons.find(btn => {
          const text = (btn.textContent || '').toLowerCase().trim();
          return text.includes('skip');
        });
      }
      
      if (skipBtn) {
        const rect = skipBtn.getBoundingClientRect();
        if (rect.width > 0 && rect.height > 0) {
          // Scroll into view if needed
          skipBtn.scrollIntoView({ behavior: 'instant', block: 'center' });
          skipBtn.click();
          return true;
        }
      }
      return false;
    });
    
    if (skipFound) {
      await page.waitForTimeout(500);
      // Verify tour is gone - check multiple times
      let tourGone = false;
      for (let i = 0; i < 5; i++) {
        tourGone = await page.evaluate(() => {
          const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]');
          return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent;
        });
        if (tourGone) break;
        await page.waitForTimeout(200);
      }
      if (tourGone) {
        practiceTourSkipped = true;
        console.log('βœ… Practice page tour skipped (via evaluate)');
      } else {
        console.log('⚠️ Tour still present after skip, trying again...');
      }
    }
    
    // Method 2: Try using locators with mouse movement (target Skip button specifically)
    if (!practiceTourSkipped) {
      // Wait for Skip button to be visible
      await page.waitForTimeout(500);
      
      const skipPracticeTourSelectors = [
        'button:has-text("Skip")',  // Exact match first
        '[class*="tour"] button:has-text("Skip")',
        '.fixed.inset-0 button:has-text("Skip")',
        'button[class*="skip"]',
      ];
      
      for (const selector of skipPracticeTourSelectors) {
        try {
          const skipBtn = page.locator(selector).first();
          if (await skipBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
            const btnBox = await skipBtn.boundingBox();
            if (btnBox) {
              // Move mouse to Skip button and click
              await moveHandToTarget(page, btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2);
              await skipBtn.click({ timeout: 2000 });
              await page.waitForTimeout(500);
              
              // Verify tour is gone
              const tourGone = await page.evaluate(() => {
                const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]');
                return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent;
              });
              
              if (tourGone) {
                practiceTourSkipped = true;
                console.log(`βœ… Practice page tour skipped (via selector: ${selector})`);
                break;
              } else {
                console.log(`⚠️ Tour still present after clicking Skip with ${selector}`);
              }
            }
          }
        } catch (e) {
          // Continue
        }
      }
    }
    
    // Method 3: Try Escape key multiple times
    if (!practiceTourSkipped) {
      for (let i = 0; i < 3; i++) {
        await page.keyboard.press('Escape');
        await page.waitForTimeout(200);
        
        // Check if tour is gone
        const tourGone = await page.evaluate(() => {
          const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]');
          return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent;
        });
        
        if (tourGone) {
          practiceTourSkipped = true;
          console.log(`βœ… Practice page tour skipped (via Escape key, attempt ${i + 1})`);
          break;
        }
      }
      
      if (!practiceTourSkipped) {
        console.log('⚠️ Tour may still be visible, but continuing...');
      }
    }
    
    // Final verification and wait to ensure tour is dismissed
    let finalTourGone = false;
    for (let i = 0; i < 10; i++) {
      finalTourGone = await page.evaluate(() => {
        const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]');
        return !tourOverlay || tourOverlay.style.display === 'none' || !tourOverlay.offsetParent;
      });
      if (finalTourGone) {
        console.log(`βœ… Tour confirmed dismissed (check ${i + 1})`);
        break;
      }
      await page.waitForTimeout(200);
    }
    
    if (!finalTourGone) {
      // Force remove tour overlay if still present
      await page.evaluate(() => {
        const tourOverlay = document.querySelector('.fixed.inset-0.z-\\[9999\\], [class*="z-50"], [class*="tour"]');
        if (tourOverlay && tourOverlay.parentNode) {
          tourOverlay.remove();
        }
        // Also mark tour as completed in localStorage
        localStorage.setItem('practiceTourCompleted', 'true');
      });
      console.log('⚠️ Force removed tour overlay');
    }
    
    await page.waitForTimeout(300);
    
    // ============================================
    // TASK 5: Write sample code in the editor
    // Mouse continues from previous position (Skip button)
    // ============================================
    console.log('πŸ“‹ Task 5: Writing code in editor...');
    
    // Wait for editor to be ready
    await page.waitForTimeout(500);
    
    const editorSelector = '#tour-code-editor, .monaco-editor, .cm-editor';
    const editor = page.locator(editorSelector).first();
    
    let editorBox = null;
    if (await editor.isVisible({ timeout: 3000 }).catch(() => false)) {
      editorBox = await editor.boundingBox().catch(() => null);
      if (editorBox) {
        // Move mouse to editor and click to focus
        await moveHandToTarget(page, editorBox.x + editorBox.width / 2, editorBox.y + editorBox.height / 2);
        await page.mouse.click(editorBox.x + editorBox.width / 2, editorBox.y + editorBox.height / 2);
        await page.waitForTimeout(200);
      }
    }
    
    // Set code directly by manipulating the hidden textarea and triggering events
    console.log('⌨️ Setting code in editor...');
    const codeSet = await page.evaluate((sampleCode) => {
      // Try Monaco editor - find the hidden textarea
      const monacoTextarea = document.querySelector('.monaco-editor textarea, .monaco-editor .inputarea');
      if (monacoTextarea) {
        const textarea = monacoTextarea;
        // Set value directly
        textarea.value = sampleCode;
        // Trigger multiple events to ensure Monaco and React both see the change
        textarea.dispatchEvent(new Event('input', { bubbles: true, cancelable: true }));
        textarea.dispatchEvent(new Event('change', { bubbles: true, cancelable: true }));
        textarea.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'a' }));
        textarea.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, cancelable: true, key: 'a' }));
        // Also trigger on the Monaco container
        const monacoContainer = document.querySelector('.monaco-editor');
        if (monacoContainer) {
          monacoContainer.dispatchEvent(new Event('input', { bubbles: true }));
        }
        return { success: true, type: 'monaco-textarea', length: sampleCode.length };
      }
      
      // Try CodeMirror
      const cmEditor = document.querySelector('.cm-editor');
      if (cmEditor) {
        const cmContent = cmEditor.querySelector('.cm-content');
        if (cmContent) {
          // Set text content
          cmContent.textContent = sampleCode;
          // Trigger events
          cmContent.dispatchEvent(new Event('input', { bubbles: true }));
          cmContent.dispatchEvent(new Event('change', { bubbles: true }));
          return { success: true, type: 'codemirror-dom', length: sampleCode.length };
        }
      }
      
      return { success: false, type: 'none', length: 0 };
    }, CONFIG.sampleCode);
    
    if (codeSet.success) {
      console.log(`βœ… Code set in editor (${codeSet.type}, ${codeSet.length} chars)`);
      await page.waitForTimeout(300);
    } else {
      console.log('⚠️ Direct API failed, trying keyboard typing...');
      
      // Fallback: Use keyboard typing
      await page.evaluate(() => {
        const monacoTextarea = document.querySelector('.monaco-editor textarea, .monaco-editor .inputarea');
        if (monacoTextarea) {
          monacoTextarea.focus();
          monacoTextarea.click();
        } else {
          const cmEditor = document.querySelector('.cm-editor, .cm-content');
          if (cmEditor) {
            cmEditor.focus();
            cmEditor.click();
          }
        }
      });
      
      await page.waitForTimeout(200);
      await page.keyboard.press('Control+A');
      await page.waitForTimeout(100);
      await page.keyboard.press('Delete');
      await page.waitForTimeout(100);
      
      // Type code character by character
      for (const char of CONFIG.sampleCode) {
        await page.keyboard.type(char, { delay: CONFIG.delays.typing });
      }
      await page.waitForTimeout(200);
    }
    
    // Verify code was actually written
    const codeTyped = await page.evaluate(() => {
      // Check Monaco view-lines (rendered content) - most reliable
      const monacoLines = document.querySelector('.monaco-editor .view-lines');
      if (monacoLines) {
        const text = monacoLines.textContent || '';
        return { typed: text.length > 10, length: text.length, preview: text.substring(0, 50), type: 'monaco-lines' };
      }
      
      // Check Monaco textarea
      const monacoTextarea = document.querySelector('.monaco-editor textarea, .monaco-editor .inputarea');
      if (monacoTextarea) {
        const value = monacoTextarea.value || '';
        return { typed: value.length > 10, length: value.length, preview: value.substring(0, 50), type: 'monaco-textarea' };
      }
      
      // Check CodeMirror
      const cmEditor = document.querySelector('.cm-editor, .cm-content');
      if (cmEditor) {
        const text = cmEditor.textContent || '';
        return { typed: text.length > 10, length: text.length, preview: text.substring(0, 50), type: 'codemirror' };
      }
      
      return { typed: false, length: 0, preview: '', type: 'none' };
    });
    
    if (codeTyped.typed) {
      console.log(`βœ… Code verified in editor (${codeTyped.type}, ${codeTyped.length} chars): ${codeTyped.preview}...`);
    } else {
      console.log(`⚠️ Code verification failed (${codeTyped.type}, length: ${codeTyped.length})`);
    }
    
    // ============================================
    // TASK 6: Hit the Run button
    // Mouse continues from previous position (editor)
    // ============================================
    console.log('πŸ“‹ Task 6: Clicking Run button...');
    
    const runButton = page.locator('#tour-run-button, button:has-text("Run")').first();
    if (await runButton.isVisible({ timeout: 2000 }).catch(() => false)) {
      const runBox = await runButton.boundingBox();
      if (runBox) {
        await moveHandToTarget(page, runBox.x + runBox.width / 2, runBox.y + runBox.height / 2);
        await runButton.click({ force: true, timeout: 2000 });
        console.log('βœ… Run button clicked');
        
        // Wait for code execution to complete and results to show
        console.log('⏳ Waiting for code execution...');
        await page.waitForTimeout(3000);
        console.log('βœ… Code execution completed');
      }
    }
    
    // All tasks complete
    await page.waitForTimeout(500);
    console.log('βœ… All tasks completed!');
    
  } catch (error) {
    console.error('❌ Error during recording:', error);
  } finally {
    await page.close();
    await context.close();
    await browser.close();
    
    console.log(`πŸ“Ή Video saved: ${outputPath}`);
    console.log(`\nπŸ’‘ Tip: Convert to MP4 using ffmpeg:\n   ffmpeg -i "${outputPath}" -c:v libx264 -c:a aac "${outputPath}"`);
  }
}

createTutorialVideo().catch(console.error);