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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Tutorial-specific JavaScript functionality

let currentTutorial = null;
let currentStep = 0;
let totalSteps = 0;

/**
 * Initialize tutorial functionality
 */
function initializeTutorial(tutorialData) {
    currentTutorial = tutorialData;
    currentStep = tutorialData.currentStep || 0;
    totalSteps = tutorialData.totalSteps;
    
    setupTutorialNavigation();
    setupStepTracking();
    setupKeyboardNavigation();
    updateProgress();
    
    // Show the current step
    showStep(currentStep);
}

/**
 * Setup tutorial navigation
 */
function setupTutorialNavigation() {
    // Step navigation links
    document.querySelectorAll('.step-nav-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const stepIndex = parseInt(this.dataset.step);
            navigateToStep(stepIndex);
        });
    });
    
    // Next/Previous buttons
    document.querySelectorAll('[onclick*="navigateToStep"]').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const match = this.getAttribute('onclick').match(/navigateToStep\((\d+)\)/);
            if (match) {
                navigateToStep(parseInt(match[1]));
            }
        });
    });
}

/**
 * Setup step tracking
 */
function setupStepTracking() {
    // Track time spent on each step
    let stepStartTime = Date.now();
    
    window.addEventListener('beforeunload', () => {
        const timeSpent = Math.floor((Date.now() - stepStartTime) / 1000);
        trackStepTime(currentStep, timeSpent);
    });
    
    // Track step completion
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            const timeSpent = Math.floor((Date.now() - stepStartTime) / 1000);
            trackStepTime(currentStep, timeSpent);
        } else {
            stepStartTime = Date.now();
        }
    });
}

/**
 * Setup keyboard navigation
 */
function setupKeyboardNavigation() {
    document.addEventListener('keydown', function(e) {
        // Only handle keyboard navigation when tutorial content is focused
        if (!document.querySelector('.tutorial-content').contains(document.activeElement)) {
            return;
        }
        
        switch(e.key) {
            case 'ArrowLeft':
                if (currentStep > 0) {
                    e.preventDefault();
                    navigateToStep(currentStep - 1);
                }
                break;
            case 'ArrowRight':
                if (currentStep < totalSteps - 1) {
                    e.preventDefault();
                    navigateToStep(currentStep + 1);
                }
                break;
            case 'Home':
                e.preventDefault();
                navigateToStep(0);
                break;
            case 'End':
                e.preventDefault();
                navigateToStep(totalSteps - 1);
                break;
        }
    });
}

/**
 * Navigate to a specific step
 */
function navigateToStep(stepIndex) {
    if (stepIndex < 0 || stepIndex >= totalSteps) {
        return;
    }
    
    // Hide current step
    const currentStepElement = document.querySelector(`#step-${currentStep}`);
    if (currentStepElement) {
        currentStepElement.classList.remove('active');
    }
    
    // Update step navigation
    document.querySelectorAll('.step-nav-link').forEach(link => {
        link.classList.remove('active');
    });
    
    // Show new step
    currentStep = stepIndex;
    showStep(currentStep);
    
    // Update navigation
    const newNavLink = document.querySelector(`[data-step="${currentStep}"]`);
    if (newNavLink) {
        newNavLink.classList.add('active');
    }
    
    // Update progress
    updateProgress();
    
    // Save progress
    saveProgress();
    
    // Track step view
    window.DifyLearning?.trackEvent('tutorial_step_viewed', {
        tutorial_id: currentTutorial.id,
        step: currentStep + 1,
        step_title: document.querySelector(`#step-${currentStep} .step-title`)?.textContent
    });
    
    // Scroll to top of content
    const tutorialContent = document.querySelector('.tutorial-content');
    if (tutorialContent) {
        tutorialContent.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
}

/**
 * Show a specific step
 */
function showStep(stepIndex) {
    // Hide all steps
    document.querySelectorAll('.tutorial-step').forEach(step => {
        step.classList.remove('active');
    });
    
    // Show target step
    const targetStep = document.querySelector(`#step-${stepIndex}`);
    if (targetStep) {
        targetStep.classList.add('active');
        
        // Initialize any interactive elements in this step
        initializeStepElements(targetStep);
        
        // Add fade-in animation
        targetStep.classList.add('fade-in');
        
        // Update step counter
        updateStepCounter(stepIndex + 1);
    }
}

/**
 * Initialize interactive elements in a step
 */
function initializeStepElements(stepElement) {
    // Initialize code examples with syntax highlighting
    const codeBlocks = stepElement.querySelectorAll('pre code');
    codeBlocks.forEach(block => {
        // Add copy button
        addCopyButton(block);
        
        // Add line numbers if needed
        if (block.textContent.split('\n').length > 5) {
            addLineNumbers(block);
        }
    });
    
    // Initialize interactive demos
    const demos = stepElement.querySelectorAll('.interactive-demo');
    demos.forEach(demo => {
        initializeDemo(demo);
    });
    
    // Initialize tooltips for this step
    const tooltips = stepElement.querySelectorAll('[data-bs-toggle="tooltip"]');
    tooltips.forEach(tooltip => {
        new bootstrap.Tooltip(tooltip);
    });
}

/**
 * Add copy button to code blocks
 */
function addCopyButton(codeBlock) {
    if (codeBlock.querySelector('.copy-button')) {
        return; // Already has copy button
    }
    
    const copyButton = document.createElement('button');
    copyButton.className = 'btn btn-sm btn-outline-secondary copy-button position-absolute top-0 end-0 m-2';
    copyButton.innerHTML = '<i data-feather="copy"></i>';
    copyButton.title = 'Copy code';
    
    copyButton.addEventListener('click', async () => {
        try {
            await navigator.clipboard.writeText(codeBlock.textContent);
            copyButton.innerHTML = '<i data-feather="check"></i>';
            copyButton.classList.add('btn-success');
            copyButton.classList.remove('btn-outline-secondary');
            
            setTimeout(() => {
                copyButton.innerHTML = '<i data-feather="copy"></i>';
                copyButton.classList.remove('btn-success');
                copyButton.classList.add('btn-outline-secondary');
                feather.replace();
            }, 2000);
            
            window.DifyLearning?.showToast('Code copied to clipboard!', 'success');
        } catch (err) {
            window.DifyLearning?.showToast('Failed to copy code', 'danger');
        }
    });
    
    // Make parent relative positioned
    const pre = codeBlock.closest('pre');
    if (pre) {
        pre.style.position = 'relative';
        pre.appendChild(copyButton);
        feather.replace();
    }
}

/**
 * Add line numbers to code blocks
 */
function addLineNumbers(codeBlock) {
    const lines = codeBlock.textContent.split('\n');
    const lineNumbers = lines.map((_, index) => index + 1).join('\n');
    
    const lineNumbersElement = document.createElement('pre');
    lineNumbersElement.className = 'line-numbers';
    lineNumbersElement.textContent = lineNumbers;
    lineNumbersElement.style.cssText = `
        position: absolute;
        left: 0;
        top: 0;
        padding: 1rem 0.5rem;
        background: #f1f3f4;
        color: #666;
        font-size: 0.8rem;
        border-right: 1px solid #ddd;
        user-select: none;
        width: 3rem;
        text-align: right;
    `;
    
    const pre = codeBlock.closest('pre');
    if (pre) {
        pre.style.position = 'relative';
        pre.style.paddingLeft = '4rem';
        pre.appendChild(lineNumbersElement);
    }
}

/**
 * Initialize interactive demos
 */
function initializeDemo(demoElement) {
    const demoType = demoElement.dataset.demoType;
    
    switch(demoType) {
        case 'workflow-builder':
            initializeWorkflowDemo(demoElement);
            break;
        case 'chatbot-preview':
            initializeChatbotDemo(demoElement);
            break;
        case 'agent-configuration':
            initializeAgentDemo(demoElement);
            break;
        default:
            // Generic demo initialization
            demoElement.innerHTML = `
                <div class="demo-placeholder">
                    <i data-feather="play-circle" class="large-icon text-primary mb-2"></i>
                    <p>Interactive Demo</p>
                    <button class="btn btn-primary btn-sm">Try It</button>
                </div>
            `;
            feather.replace();
    }
}

/**
 * Initialize workflow builder demo
 */
function initializeWorkflowDemo(element) {
    element.innerHTML = `
        <div class="workflow-demo">
            <div class="workflow-canvas">
                <div class="workflow-node start-node">
                    <i data-feather="play"></i>
                    <span>Start</span>
                </div>
                <div class="workflow-arrow">→</div>
                <div class="workflow-node llm-node">
                    <i data-feather="cpu"></i>
                    <span>LLM</span>
                </div>
                <div class="workflow-arrow">→</div>
                <div class="workflow-node end-node">
                    <i data-feather="message-circle"></i>
                    <span>Response</span>
                </div>
            </div>
            <div class="workflow-controls mt-3">
                <button class="btn btn-sm btn-primary" onclick="addWorkflowNode(this)">
                    <i data-feather="plus"></i> Add Node
                </button>
            </div>
        </div>
    `;
    feather.replace();
}

/**
 * Initialize chatbot demo
 */
function initializeChatbotDemo(element) {
    element.innerHTML = `
        <div class="chatbot-demo">
            <div class="chat-window">
                <div class="chat-messages" id="demo-chat-messages">
                    <div class="message bot-message">
                        <div class="message-content">
                            Hello! I'm your Dify AI assistant. How can I help you today?
                        </div>
                    </div>
                </div>
                <div class="chat-input">
                    <input type="text" class="form-control" placeholder="Type your message..." 
                           onkeypress="handleDemoChatInput(event)">
                    <button class="btn btn-primary" onclick="sendDemoMessage()">
                        <i data-feather="send"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
    feather.replace();
}

/**
 * Handle demo chat input
 */
function handleDemoChatInput(event) {
    if (event.key === 'Enter') {
        sendDemoMessage();
    }
}

/**
 * Send demo message
 */
function sendDemoMessage() {
    const input = event.target.closest('.chat-input').querySelector('input');
    const message = input.value.trim();
    
    if (!message) return;
    
    const messagesContainer = document.getElementById('demo-chat-messages');
    
    // Add user message
    const userMessage = document.createElement('div');
    userMessage.className = 'message user-message';
    userMessage.innerHTML = `<div class="message-content">${message}</div>`;
    messagesContainer.appendChild(userMessage);
    
    // Clear input
    input.value = '';
    
    // Simulate bot response
    setTimeout(() => {
        const botMessage = document.createElement('div');
        botMessage.className = 'message bot-message';
        botMessage.innerHTML = `
            <div class="message-content">
                That's a great question about Dify! This is a demo response showing how your chatbot would interact with users.
            </div>
        `;
        messagesContainer.appendChild(botMessage);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }, 1000);
    
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

/**
 * Update progress display
 */
function updateProgress() {
    // Update progress bar
    const progressBar = document.getElementById('tutorial-progress-bar');
    if (progressBar) {
        const percentage = ((currentStep + 1) / totalSteps) * 100;
        window.DifyLearning?.animateProgressBar(progressBar, percentage);
    }
    
    // Update step counter
    updateStepCounter(currentStep + 1);
    
    // Update sidebar navigation
    updateSidebarNavigation();
}

/**
 * Update step counter
 */
function updateStepCounter(stepNumber) {
    const counter = document.getElementById('current-step');
    if (counter) {
        counter.textContent = stepNumber;
    }
}

/**
 * Update sidebar navigation
 */
function updateSidebarNavigation() {
    document.querySelectorAll('.step-nav-link').forEach((link, index) => {
        link.classList.remove('active');
        
        if (index === currentStep) {
            link.classList.add('active');
        }
        
        // Remove completed indicators (checkmarks disabled)
        const existingCheck = link.querySelector('i[data-feather="check"]');
        if (existingCheck) {
            existingCheck.remove();
        }
    });
}

/**
 * Save progress to server
 */
async function saveProgress() {
    if (!currentTutorial) return;
    
    try {
        const response = await fetch('/api/progress/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                tutorial_id: currentTutorial.id,
                current_step: currentStep,
                completed: false
            })
        });
        
        if (!response.ok) {
            throw new Error('Failed to save progress');
        }
        
    } catch (error) {
        console.error('Error saving progress:', error);
        // Show error message to user
        window.DifyLearning?.showToast('Failed to save progress', 'warning');
    }
}

/**
 * Complete tutorial
 */
async function completeTutorial() {
    if (!currentTutorial) return;
    
    try {
        const response = await fetch('/api/progress/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                tutorial_id: currentTutorial.id,
                current_step: totalSteps - 1,
                completed: true
            })
        });
        
        if (response.ok) {
            // Track completion
            window.DifyLearning?.trackEvent('tutorial_completed', {
                tutorial_id: currentTutorial.id,
                total_steps: totalSteps,
                completion_time: new Date().toISOString()
            });
            
            // Show completion modal
            const modal = new bootstrap.Modal(document.getElementById('completionModal'));
            modal.show();
            
            // Update UI to show completion
            document.querySelectorAll('.progress-circle').forEach(circle => {
                circle.className = 'progress-circle completed';
                circle.innerHTML = '<i data-feather="check"></i>';
            });
            feather.replace();
            
        } else {
            throw new Error('Failed to complete tutorial');
        }
        
    } catch (error) {
        console.error('Error completing tutorial:', error);
        window.DifyLearning?.showToast('Failed to save completion status', 'warning');
    }
}

/**
 * Track time spent on step
 */
function trackStepTime(stepIndex, seconds) {
    if (seconds < 5) return; // Ignore very short durations
    
    const stepData = {
        tutorial_id: currentTutorial?.id,
        step: stepIndex + 1,
        time_spent: seconds
    };
    
    // Store locally for analytics
    const stepTimes = JSON.parse(localStorage.getItem('dify_step_times') || '[]');
    stepTimes.push({
        ...stepData,
        timestamp: new Date().toISOString()
    });
    localStorage.setItem('dify_step_times', JSON.stringify(stepTimes.slice(-1000)));
}

/**
 * Add workflow node (demo function)
 */
function addWorkflowNode(button) {
    const canvas = button.closest('.workflow-demo').querySelector('.workflow-canvas');
    const newNode = document.createElement('div');
    newNode.className = 'workflow-node';
    newNode.innerHTML = `
        <i data-feather="settings"></i>
        <span>New Node</span>
    `;
    
    // Add arrow before new node
    const arrow = document.createElement('div');
    arrow.className = 'workflow-arrow';
    arrow.textContent = '→';
    
    // Insert before end node
    const endNode = canvas.querySelector('.end-node');
    canvas.insertBefore(arrow, endNode);
    canvas.insertBefore(newNode, endNode);
    
    feather.replace();
    
    // Show success message
    window.DifyLearning?.showToast('Node added to workflow!', 'success');
}

// Make functions available globally
window.navigateToStep = navigateToStep;
window.completeTutorial = completeTutorial;
window.handleDemoChatInput = handleDemoChatInput;
window.sendDemoMessage = sendDemoMessage;
window.addWorkflowNode = addWorkflowNode;