// Interactive Tutorial System
class Tutorial {
    constructor(steps, userType) {
        this.steps = steps;
        this.userType = userType;
        this.currentStep = 0;
        this.overlay = null;
        this.tooltip = null;
        this.welcome = null;
        this.highlightedElement = null;
    }

    // Initialize tutorial
    init() {
        // Check if user has completed tutorial
        const tutorialCompleted = localStorage.getItem(`tutorial_completed_${this.userType}`);

        if (tutorialCompleted === 'true') {
            return; // Don't show tutorial if already completed
        }

        this.createOverlay();
        this.createWelcome();
        this.showWelcome();
    }

    // Create overlay
    createOverlay() {
        this.overlay = document.createElement('div');
        this.overlay.className = 'tutorial-overlay';
        document.body.appendChild(this.overlay);
    }

    // Create welcome screen
    createWelcome() {
        this.welcome = document.createElement('div');
        this.welcome.className = 'tutorial-welcome';

        const icon = this.userType === 'student' ? '🎓' : (this.userType === 'instructor' ? '👨‍🏫' : '👑');
        const title = this.userType === 'student' ? 'Welcome to CODELAB!' :
                     (this.userType === 'instructor' ? 'Welcome, Instructor!' : 'Welcome, Admin!');
        const description = this.userType === 'student'
            ? 'Let\'s take a quick tour to help you get started with your C++ learning journey! We\'ll show you around the key features.'
            : (this.userType === 'instructor'
                ? 'Let\'s walk through the main features to help you create and manage your courses effectively.'
                : 'Let\'s explore the administrative features to help you manage the system.');

        this.welcome.innerHTML = `
            <div class="tutorial-welcome-icon">${icon}</div>
            <h2>${title}</h2>
            <p>${description}</p>
            <div class="tutorial-welcome-buttons">
                <button class="tutorial-welcome-btn tutorial-welcome-btn-start">
                    Start Tutorial
                </button>
                <button class="tutorial-welcome-btn tutorial-welcome-btn-skip">
                    Skip for Now
                </button>
            </div>
        `;

        document.body.appendChild(this.welcome);

        // Event listeners
        this.welcome.querySelector('.tutorial-welcome-btn-start').addEventListener('click', () => {
            this.hideWelcome();
            this.startTutorial();
        });

        this.welcome.querySelector('.tutorial-welcome-btn-skip').addEventListener('click', () => {
            this.skipTutorial();
        });
    }

    // Show welcome screen
    showWelcome() {
        this.overlay.classList.add('active');
        this.welcome.classList.add('active');
    }

    // Hide welcome screen
    hideWelcome() {
        this.welcome.classList.remove('active');
        setTimeout(() => {
            this.welcome.remove();
        }, 300);
    }

    // Start tutorial
    startTutorial() {
        this.currentStep = 0;
        this.showStep(this.currentStep);
    }

    // Show specific step
    showStep(stepIndex) {
        if (stepIndex >= this.steps.length) {
            this.completeTutorial();
            return;
        }

        const step = this.steps[stepIndex];

        // Remove previous highlight
        if (this.highlightedElement) {
            this.highlightedElement.classList.remove('tutorial-highlight');
        }

        // Find and highlight target element
        const targetElement = document.querySelector(step.target);
        if (targetElement) {
            this.highlightedElement = targetElement;
            this.highlightedElement.classList.add('tutorial-highlight');

            // Scroll element into view
            this.highlightedElement.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });
        }

        // Create or update tooltip
        if (!this.tooltip) {
            this.createTooltip();
        }

        this.updateTooltip(step, stepIndex);
        this.positionTooltip(targetElement, step.position || 'bottom');
    }

    // Create tooltip
    createTooltip() {
        this.tooltip = document.createElement('div');
        this.tooltip.className = 'tutorial-tooltip';
        document.body.appendChild(this.tooltip);
    }

    // Update tooltip content
    updateTooltip(step, stepIndex) {
        const isLastStep = stepIndex === this.steps.length - 1;

        this.tooltip.innerHTML = `
            <div class="tutorial-tooltip-header">
                <span class="tutorial-tooltip-icon">${step.icon}</span>
                <h3 class="tutorial-tooltip-title">${step.title}</h3>
            </div>
            <div class="tutorial-tooltip-content">
                ${step.content}
            </div>
            <div class="tutorial-tooltip-footer">
                <span class="tutorial-progress">Step ${stepIndex + 1} of ${this.steps.length}</span>
                <div class="tutorial-buttons">
                    <button class="tutorial-btn tutorial-btn-skip">Skip Tutorial</button>
                    <button class="tutorial-btn tutorial-btn-next">
                        ${isLastStep ? 'Got it!' : 'Next'}
                    </button>
                </div>
            </div>
        `;

        this.tooltip.classList.add('active');

        // Event listeners
        this.tooltip.querySelector('.tutorial-btn-next').addEventListener('click', () => {
            this.nextStep();
        });

        this.tooltip.querySelector('.tutorial-btn-skip').addEventListener('click', () => {
            this.skipTutorial();
        });
    }

    // Position tooltip relative to target
    positionTooltip(targetElement, position) {
        if (!targetElement) {
            // Center tooltip if no target
            this.tooltip.style.top = '50%';
            this.tooltip.style.left = '50%';
            this.tooltip.style.transform = 'translate(-50%, -50%)';
            return;
        }

        const rect = targetElement.getBoundingClientRect();
        const tooltipRect = this.tooltip.getBoundingClientRect();

        // Remove previous arrow classes
        this.tooltip.classList.remove('arrow-top', 'arrow-bottom', 'arrow-left', 'arrow-right');

        let top, left;

        switch (position) {
            case 'top':
                top = rect.top - tooltipRect.height - 20;
                left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
                this.tooltip.classList.add('arrow-bottom');
                break;
            case 'bottom':
                top = rect.bottom + 20;
                left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
                this.tooltip.classList.add('arrow-top');
                break;
            case 'left':
                top = rect.top + (rect.height / 2) - (tooltipRect.height / 2);
                left = rect.left - tooltipRect.width - 20;
                this.tooltip.classList.add('arrow-right');
                break;
            case 'right':
                top = rect.top + (rect.height / 2) - (tooltipRect.height / 2);
                left = rect.right + 20;
                this.tooltip.classList.add('arrow-left');
                break;
            default:
                top = rect.bottom + 20;
                left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
                this.tooltip.classList.add('arrow-top');
        }

        // Ensure tooltip stays within viewport
        const padding = 20;
        if (left < padding) left = padding;
        if (left + tooltipRect.width > window.innerWidth - padding) {
            left = window.innerWidth - tooltipRect.width - padding;
        }
        if (top < padding) top = padding;
        if (top + tooltipRect.height > window.innerHeight - padding) {
            top = window.innerHeight - tooltipRect.height - padding;
        }

        this.tooltip.style.top = top + 'px';
        this.tooltip.style.left = left + 'px';
        this.tooltip.style.transform = 'none';
    }

    // Move to next step
    nextStep() {
        this.currentStep++;
        this.showStep(this.currentStep);
    }

    // Skip tutorial
    skipTutorial() {
        if (confirm('Are you sure you want to skip the tutorial? You can restart it anytime from your profile settings.')) {
            this.cleanup();
            localStorage.setItem(`tutorial_completed_${this.userType}`, 'true');
        }
    }

    // Complete tutorial
    completeTutorial() {
        // Show completion message
        if (this.tooltip) {
            this.tooltip.innerHTML = `
                <div class="tutorial-tooltip-header">
                    <span class="tutorial-tooltip-icon">🎉</span>
                    <h3 class="tutorial-tooltip-title">Tutorial Complete!</h3>
                </div>
                <div class="tutorial-tooltip-content">
                    You're all set! Feel free to explore the platform. If you need help, you can always restart the tutorial from your profile settings.
                </div>
                <div class="tutorial-tooltip-footer">
                    <div class="tutorial-buttons" style="margin-left: auto;">
                        <button class="tutorial-btn tutorial-btn-next">Got it!</button>
                    </div>
                </div>
            `;

            this.tooltip.querySelector('.tutorial-btn-next').addEventListener('click', () => {
                this.cleanup();
                localStorage.setItem(`tutorial_completed_${this.userType}`, 'true');
            });
        }
    }

    // Clean up tutorial elements
    cleanup() {
        if (this.highlightedElement) {
            this.highlightedElement.classList.remove('tutorial-highlight');
        }
        if (this.tooltip) {
            this.tooltip.classList.remove('active');
            setTimeout(() => this.tooltip.remove(), 300);
        }
        if (this.overlay) {
            this.overlay.classList.remove('active');
            setTimeout(() => this.overlay.remove(), 300);
        }
        if (this.welcome) {
            this.welcome.classList.remove('active');
            setTimeout(() => this.welcome.remove(), 300);
        }
    }

    // Restart tutorial (can be called from settings)
    static restart(userType) {
        localStorage.removeItem(`tutorial_completed_${userType}`);
        location.reload();
    }
}

// Export for use in other files
if (typeof module !== 'undefined' && module.exports) {
    module.exports = Tutorial;
}
