// Tutorial System - Client-side implementation
window.setTutorialManagerRef = function(dotNetRef) {
    window.tutorialManagerRef = dotNetRef;
};

window.invokeTutorialManagerMethod = function(methodName, ...args) {
    if (window.tutorialManagerRef) {
        return window.tutorialManagerRef.invokeMethodAsync(methodName, ...args);
    }

    console.warn(`Tutorial manager reference not available for method '${methodName}'.`);
    return Promise.resolve();
};

window.tutorialSystem = {
    currentTour: null,
    activeHints: new Map(),
    activeCallouts: new Map(),

    // Initialize the tutorial system
    initialize: function() {
        this.createStyles();
        this.bindEvents();
        console.log('Tutorial system initialized');
    },

    // Start a guided tour
    startGuidedTour: function(tutorial) {
        if (this.currentTour) {
            this.endTour();
        }

        this.currentTour = {
            tutorial: tutorial,
            currentStep: 0,
            overlay: null
        };

        this.showTourStep(0);
    },

    // Show a specific tour step
    showTourStep: function(stepIndex) {
        if (!this.currentTour || stepIndex >= this.currentTour.tutorial.steps.length) {
            return;
        }

        const step = this.currentTour.tutorial.steps[stepIndex];
        const element = step.element ? document.querySelector(step.element) : null;

        // Create overlay
        this.createTourOverlay();

        // Highlight target element
        if (element) {
            this.highlightElement(element);
            this.scrollToElement(element);
        }

        // Show step content
        this.showStepPopover(step, element, stepIndex);
        this.currentTour.currentStep = stepIndex;
    },

    // Create tour overlay
    createTourOverlay: function() {
        if (this.currentTour.overlay) {
            this.currentTour.overlay.remove();
        }

        const overlay = document.createElement('div');
        overlay.className = 'tutorial-overlay';
        overlay.innerHTML = `
            <div class="tutorial-backdrop"></div>
        `;
        
        document.body.appendChild(overlay);
        this.currentTour.overlay = overlay;
    },

    // Highlight target element
    highlightElement: function(element) {
        // Remove previous highlights
        document.querySelectorAll('.tutorial-highlight').forEach(el => {
            el.classList.remove('tutorial-highlight');
        });

        if (element) {
            element.classList.add('tutorial-highlight');
            
            // Create spotlight effect
            const rect = element.getBoundingClientRect();
            const spotlight = document.createElement('div');
            spotlight.className = 'tutorial-spotlight';
            spotlight.style.cssText = `
                position: fixed;
                top: ${rect.top - 8}px;
                left: ${rect.left - 8}px;
                width: ${rect.width + 16}px;
                height: ${rect.height + 16}px;
                pointer-events: none;
                z-index: 10001;
            `;
            
            this.currentTour.overlay.appendChild(spotlight);
        }
    },

    // Show step popover
    showStepPopover: function(step, targetElement, stepIndex) {
        const popover = document.createElement('div');
        popover.className = 'tutorial-popover';
        
        const isLastStep = stepIndex === this.currentTour.tutorial.steps.length - 1;
        const isFirstStep = stepIndex === 0;
        
        popover.innerHTML = `
            <div class="tutorial-popover-content">
                <div class="tutorial-popover-header">
                    <h3>${step.title}</h3>
                    <button class="tutorial-close" onclick="tutorialSystem.endTour()">×</button>
                </div>
                <div class="tutorial-popover-body">
                    <p>${step.content}</p>
                </div>
                <div class="tutorial-popover-footer">
                    <div class="tutorial-step-indicator">
                        ${stepIndex + 1} of ${this.currentTour.tutorial.steps.length}
                    </div>
                    <div class="tutorial-buttons">
                        ${step.showSkip ? '<button class="tutorial-btn tutorial-btn-skip" onclick="tutorialSystem.skipTour()">Skip Tour</button>' : ''}
                        ${!isFirstStep && step.showPrev ? '<button class="tutorial-btn tutorial-btn-prev" onclick="tutorialSystem.prevStep()">Previous</button>' : ''}
                        ${!isLastStep && step.showNext ? '<button class="tutorial-btn tutorial-btn-next" onclick="tutorialSystem.nextStep()">Next</button>' : ''}
                        ${isLastStep ? '<button class="tutorial-btn tutorial-btn-finish" onclick="tutorialSystem.completeTour()">Finish</button>' : ''}
                    </div>
                </div>
            </div>
        `;

        // Position popover
        this.positionPopover(popover, targetElement, step.placement);
        this.currentTour.overlay.appendChild(popover);
    },

    // Position popover relative to target element
    positionPopover: function(popover, targetElement, placement = 'bottom') {
        document.body.appendChild(popover);
        
        if (targetElement) {
            const rect = targetElement.getBoundingClientRect();
            const popoverRect = popover.getBoundingClientRect();
            
            let top, left;
            
            switch (placement) {
                case 'top':
                    top = rect.top - popoverRect.height - 10;
                    left = rect.left + (rect.width - popoverRect.width) / 2;
                    break;
                case 'bottom':
                    top = rect.bottom + 10;
                    left = rect.left + (rect.width - popoverRect.width) / 2;
                    break;
                case 'left':
                    top = rect.top + (rect.height - popoverRect.height) / 2;
                    left = rect.left - popoverRect.width - 10;
                    break;
                case 'right':
                    top = rect.top + (rect.height - popoverRect.height) / 2;
                    left = rect.right + 10;
                    break;
                default:
                    top = rect.bottom + 10;
                    left = rect.left + (rect.width - popoverRect.width) / 2;
            }
            
            // Ensure popover stays within viewport
            top = Math.max(10, Math.min(top, window.innerHeight - popoverRect.height - 10));
            left = Math.max(10, Math.min(left, window.innerWidth - popoverRect.width - 10));
            
            popover.style.cssText += `
                position: fixed;
                top: ${top}px;
                left: ${left}px;
                z-index: 10002;
            `;
        } else {
            // Center on screen if no target element
            popover.style.cssText += `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: 10002;
            `;
        }
    },

    // Scroll to element smoothly
    scrollToElement: function(element) {
        if (element) {
            element.scrollIntoView({
                behavior: 'smooth',
                block: 'center',
                inline: 'center'
            });
        }
    },

    // Navigation methods
    nextStep: function() {
        if (this.currentTour) {
            this.showTourStep(this.currentTour.currentStep + 1);
        }
    },

    prevStep: function() {
        if (this.currentTour && this.currentTour.currentStep > 0) {
            this.showTourStep(this.currentTour.currentStep - 1);
        }
    },

    skipTour: function() {
        if (this.currentTour) {
            window.invokeTutorialManagerMethod('SkipTutorial', this.currentTour.tutorial.id);
            this.endTour();
        }
    },

    completeTour: function() {
        if (this.currentTour) {
            window.invokeTutorialManagerMethod('CompleteTutorial', this.currentTour.tutorial.id);
            this.endTour();
        }
    },

    endTour: function() {
        if (this.currentTour) {
            // Remove overlay and highlights
            if (this.currentTour.overlay) {
                this.currentTour.overlay.remove();
            }
            
            document.querySelectorAll('.tutorial-highlight').forEach(el => {
                el.classList.remove('tutorial-highlight');
            });
            
            this.currentTour = null;
        }
    },

    // Show contextual hint
    showHint: function(hintId, elementSelector, title, content) {
        const element = document.querySelector(elementSelector);
        if (!element || this.activeHints.has(hintId)) {
            return;
        }

        const hint = document.createElement('div');
        hint.className = 'tutorial-hint';
        hint.innerHTML = `
            <div class="tutorial-hint-content">
                <div class="tutorial-hint-header">
                    <strong>${title}</strong>
                    <button class="tutorial-hint-close" onclick="tutorialSystem.dismissHint('${hintId}')">×</button>
                </div>
                <div class="tutorial-hint-body">
                    ${content}
                </div>
                <div class="tutorial-hint-actions">
                    <button class="tutorial-btn tutorial-btn-small" onclick="tutorialSystem.dismissHint('${hintId}')">Got it</button>
                </div>
            </div>
        `;

        this.positionPopover(hint, element, 'top');
        this.activeHints.set(hintId, hint);

        // Auto-dismiss after 10 seconds
        setTimeout(() => this.dismissHint(hintId), 10000);
    },

    // Show feature callout
    showCallout: function(calloutId, title, content, badgeText = null) {
        if (this.activeCallouts.has(calloutId)) {
            return;
        }

        const callout = document.createElement('div');
        callout.className = 'tutorial-callout';
        callout.innerHTML = `
            <div class="tutorial-callout-content">
                ${badgeText ? `<div class="tutorial-callout-badge">${badgeText}</div>` : ''}
                <div class="tutorial-callout-header">
                    <strong>${title}</strong>
                    <button class="tutorial-callout-close" onclick="tutorialSystem.dismissCallout('${calloutId}')">×</button>
                </div>
                <div class="tutorial-callout-body">
                    ${content}
                </div>
                <div class="tutorial-callout-actions">
                    <button class="tutorial-btn tutorial-btn-small" onclick="tutorialSystem.dismissCallout('${calloutId}')">Dismiss</button>
                </div>
            </div>
        `;

        // Position in top-right corner
        callout.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 10000;
        `;

        document.body.appendChild(callout);
        this.activeCallouts.set(calloutId, callout);

        // Auto-dismiss after 15 seconds
        setTimeout(() => this.dismissCallout(calloutId), 15000);
    },

    // Dismiss hint
    dismissHint: function(hintId) {
        const hint = this.activeHints.get(hintId);
        if (hint) {
            hint.remove();
            this.activeHints.delete(hintId);
            window.invokeTutorialManagerMethod('CompleteTutorial', hintId);
        }
    },

    // Dismiss callout
    dismissCallout: function(calloutId) {
        const callout = this.activeCallouts.get(calloutId);
        if (callout) {
            callout.remove();
            this.activeCallouts.delete(calloutId);
            window.invokeTutorialManagerMethod('CompleteTutorial', calloutId);
        }
    },

    // Show modal tutorial
    showModal: function(tutorial) {
        const modal = document.createElement('div');
        modal.className = 'tutorial-modal';
        modal.innerHTML = `
            <div class="tutorial-modal-backdrop" onclick="tutorialSystem.dismissModal('${tutorial.id}')"></div>
            <div class="tutorial-modal-content">
                <div class="tutorial-modal-header">
                    <h2>${tutorial.name}</h2>
                    <button class="tutorial-modal-close" onclick="tutorialSystem.dismissModal('${tutorial.id}')">×</button>
                </div>
                <div class="tutorial-modal-body">
                    <p>${tutorial.description}</p>
                </div>
                <div class="tutorial-modal-footer">
                    <button class="tutorial-btn tutorial-btn-outline" onclick="tutorialSystem.dismissModal('${tutorial.id}')">Skip</button>
                    <button class="tutorial-btn tutorial-btn-primary" onclick="tutorialSystem.startModalTutorial('${tutorial.id}')">Start Tutorial</button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);
    },

    dismissModal: function(tutorialId) {
        const modal = document.querySelector('.tutorial-modal');
        if (modal) {
            modal.remove();
            window.invokeTutorialManagerMethod('SkipTutorial', tutorialId);
        }
    },

    startModalTutorial: function(tutorialId) {
        this.dismissModal(tutorialId);
        window.invokeTutorialManagerMethod('StartTutorial', tutorialId);
    },

    // Bind keyboard events
    bindEvents: function() {
        document.addEventListener('keydown', (e) => {
            if (this.currentTour) {
                switch (e.key) {
                    case 'Escape':
                        this.endTour();
                        break;
                    case 'ArrowRight':
                    case ' ':
                        e.preventDefault();
                        this.nextStep();
                        break;
                    case 'ArrowLeft':
                        e.preventDefault();
                        this.prevStep();
                        break;
                }
            }
        });
    },

    // Create CSS styles
    createStyles: function() {
        if (document.getElementById('tutorial-styles')) return;

        const styles = document.createElement('style');
        styles.id = 'tutorial-styles';
        styles.textContent = `
            .tutorial-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 10000;
                pointer-events: none;
            }

            .tutorial-backdrop {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                pointer-events: auto;
            }

            .tutorial-spotlight {
                background: transparent;
                border: 2px solid #3b82f6;
                border-radius: 8px;
                box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5);
                animation: tutorial-pulse 2s infinite;
            }

            @keyframes tutorial-pulse {
                0%, 100% { box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5), 0 0 0 0 rgba(59, 130, 246, 0.7); }
                50% { box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5), 0 0 0 10px rgba(59, 130, 246, 0); }
            }

            .tutorial-highlight {
                position: relative;
                z-index: 10001 !important;
            }

            .tutorial-popover {
                background: white;
                border-radius: 12px;
                box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
                max-width: 400px;
                min-width: 300px;
                pointer-events: auto;
                animation: tutorial-fadeIn 0.3s ease-out;
            }

            .tutorial-popover-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16px 20px 0;
            }

            .tutorial-popover-header h3 {
                margin: 0;
                font-size: 18px;
                font-weight: 600;
                color: #1f2937;
            }

            .tutorial-close {
                background: none;
                border: none;
                font-size: 24px;
                cursor: pointer;
                color: #6b7280;
                padding: 0;
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .tutorial-popover-body {
                padding: 12px 20px;
            }

            .tutorial-popover-body p {
                margin: 0;
                color: #4b5563;
                line-height: 1.5;
            }

            .tutorial-popover-footer {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 0 20px 16px;
                border-top: 1px solid #f3f4f6;
                margin-top: 16px;
                padding-top: 16px;
            }

            .tutorial-step-indicator {
                font-size: 14px;
                color: #6b7280;
            }

            .tutorial-buttons {
                display: flex;
                gap: 8px;
            }

            .tutorial-btn {
                padding: 8px 16px;
                border-radius: 6px;
                border: none;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: all 0.2s;
            }

            .tutorial-btn-skip {
                background: #f3f4f6;
                color: #6b7280;
            }

            .tutorial-btn-skip:hover {
                background: #e5e7eb;
            }

            .tutorial-btn-prev {
                background: #f3f4f6;
                color: #374151;
            }

            .tutorial-btn-prev:hover {
                background: #e5e7eb;
            }

            .tutorial-btn-next, .tutorial-btn-finish {
                background: #3b82f6;
                color: white;
            }

            .tutorial-btn-next:hover, .tutorial-btn-finish:hover {
                background: #2563eb;
            }

            .tutorial-hint, .tutorial-callout {
                background: white;
                border-radius: 8px;
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
                max-width: 320px;
                animation: tutorial-slideIn 0.3s ease-out;
            }

            .tutorial-hint-content, .tutorial-callout-content {
                padding: 16px;
            }

            .tutorial-hint-header, .tutorial-callout-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 8px;
            }

            .tutorial-callout-badge {
                position: absolute;
                top: -8px;
                right: -8px;
                background: #ef4444;
                color: white;
                font-size: 12px;
                font-weight: 600;
                padding: 4px 8px;
                border-radius: 12px;
            }

            .tutorial-btn-small {
                padding: 6px 12px;
                font-size: 12px;
            }

            .tutorial-modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 10000;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .tutorial-modal-backdrop {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
            }

            .tutorial-modal-content {
                background: white;
                border-radius: 12px;
                max-width: 500px;
                width: 90%;
                position: relative;
                animation: tutorial-scaleIn 0.3s ease-out;
            }

            .tutorial-modal-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 24px 24px 0;
            }

            .tutorial-modal-body {
                padding: 16px 24px;
            }

            .tutorial-modal-footer {
                display: flex;
                justify-content: flex-end;
                gap: 12px;
                padding: 0 24px 24px;
            }

            .tutorial-btn-outline {
                background: transparent;
                border: 1px solid #d1d5db;
                color: #374151;
            }

            .tutorial-btn-primary {
                background: #3b82f6;
                color: white;
            }

            @keyframes tutorial-fadeIn {
                from { opacity: 0; transform: translateY(-10px); }
                to { opacity: 1; transform: translateY(0); }
            }

            @keyframes tutorial-slideIn {
                from { opacity: 0; transform: translateX(20px); }
                to { opacity: 1; transform: translateX(0); }
            }

            @keyframes tutorial-scaleIn {
                from { opacity: 0; transform: scale(0.9); }
                to { opacity: 1; transform: scale(1); }
            }

            @media (max-width: 640px) {
                .tutorial-popover {
                    max-width: calc(100vw - 40px);
                    min-width: calc(100vw - 40px);
                }
                
                .tutorial-hint, .tutorial-callout {
                    max-width: calc(100vw - 40px);
                }
            }
        `;

        document.head.appendChild(styles);
    }
};

// Initialize when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => tutorialSystem.initialize());
} else {
    tutorialSystem.initialize();
}
