// Schemafy Onboarding Tour System
// Initializes interactive tour for new users

jQuery(document).ready(function($) {
    'use strict';

    // Which editors this build ships — the tour only walks users through
    // tools they actually have.
    var _features = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.features) ? schemafy_ajax.features : {};
    var _hasAi = _features.ai === true;

    // Tour configuration
    var allTourSteps = [
        {
            target: '.schemafy-tab-btn-v2[data-tab="dashboard"]',
            title: SCHEMAFY_TOUR_STRINGS?.dashboard_title || 'Dashboard',
            content: SCHEMAFY_TOUR_STRINGS?.dashboard_content || 'Dashboard help text',
            position: 'right',
            tab: 'dashboard'
        },
        {
            target: '#schemafy-tab-dashboard .schemafy-stats-grid',
            title: SCHEMAFY_TOUR_STRINGS?.stats_title || 'Statistics',
            content: SCHEMAFY_TOUR_STRINGS?.stats_content || 'Stats help text',
            position: 'bottom',
            tab: 'dashboard'
        },
        {
            target: '#schemafy-url-map-container',
            title: SCHEMAFY_TOUR_STRINGS?.map_title || 'Schema Map',
            content: SCHEMAFY_TOUR_STRINGS?.map_content || 'Map help text',
            position: 'top',
            tab: 'dashboard'
        },
        {
            target: '.schemafy-tab-btn-v2[data-tab="builder"]',
            title: SCHEMAFY_TOUR_STRINGS?.builder_title || 'Smart Builder',
            content: SCHEMAFY_TOUR_STRINGS?.builder_content || 'Builder help text',
            position: 'right',
            tab: 'dashboard'
        },
        {
            target: '.schemafy-schema-types-grid',
            title: SCHEMAFY_TOUR_STRINGS?.types_title || 'Schema Types',
            content: SCHEMAFY_TOUR_STRINGS?.types_content || 'Types help text',
            position: 'right',
            tab: 'builder'
        },
        {
            target: '.schemafy-tab-btn-v2[data-tab="manual"]',
            title: SCHEMAFY_TOUR_STRINGS?.manual_title || 'Manual JSON',
            content: SCHEMAFY_TOUR_STRINGS?.manual_content || 'Manual help text',
            position: 'right',
            tab: 'builder',
            noNavigate: true
        },
        {
            target: '#schemafy-manual-form',
            title: SCHEMAFY_TOUR_STRINGS?.editor_title || 'JSON Editor',
            content: SCHEMAFY_TOUR_STRINGS?.editor_content || 'Editor help text',
            position: 'top',
            tab: 'manual',
            requiresFeature: 'manual'
        },
        {
            target: '.schemafy-tab-btn-v2[data-tab="bulk"]',
            title: SCHEMAFY_TOUR_STRINGS?.bulk_title || 'Snippets Manager',
            content: SCHEMAFY_TOUR_STRINGS?.bulk_content || 'Snippets help text',
            position: 'right',
            tab: 'manual',
            noNavigate: false
        },
        {
            target: '#schemafy-bulk-manager-main-card',
            title: SCHEMAFY_TOUR_STRINGS?.library_title || 'Schema Library',
            content: SCHEMAFY_TOUR_STRINGS?.library_content || 'Library help text',
            position: 'top',
            tab: 'bulk'
        },
        {
            target: '.schemafy-tab-btn-v2[data-tab="ai-paste"]',
            title: SCHEMAFY_TOUR_STRINGS?.ai_title || 'AI Generator',
            content: _hasAi
                ? (SCHEMAFY_TOUR_STRINGS?.ai_content || 'AI help text')
                : (SCHEMAFY_TOUR_STRINGS?.ai_locked || 'AI locked text'),
            position: 'right',
            tab: 'bulk',
            noNavigate: true
        }
    ];

    // Filter out steps that require a tier the user doesn't have
    var tourSteps = allTourSteps.filter(function(step) {
        if (step.requiresFeature && _features[step.requiresFeature] !== true) return false;
        return true;
    });

    var currentStep = 0;
    var $overlay = $('#schemafy-tour-overlay');
    var $tooltip = $('#schemafy-tour-tooltip');
    var $welcomeModal = $('#schemafy-welcome-modal');
    var $stepBadge = $tooltip.find('.schemafy-tour-step-badge');
    var $title = $tooltip.find('.schemafy-tour-tooltip-content h4');
    var $content = $tooltip.find('.schemafy-tour-tooltip-content p');
    var $prevBtn = $tooltip.find('.schemafy-tour-prev');
    var $nextBtn = $tooltip.find('.schemafy-tour-next');
    var $skipBtn = $tooltip.find('.schemafy-tour-skip');
    var $closeBtn = $tooltip.find('.schemafy-tour-close');
    var $dontShowTour = $('#schemafy-tour-dont-show');
    var $dontShowWelcome = $('#schemafy-welcome-dont-show');
    var highlightedElement = null;

    function positionTooltip(target, position) {
        var $target = $(target);
        if (!$target.length) return;

        var targetRect = $target[0].getBoundingClientRect();
        var tooltipWidth = $tooltip.outerWidth();
        var tooltipHeight = $tooltip.outerHeight();
        var margin = 16;
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        var top, left;

        switch (position) {
            case 'right':
                top = targetRect.top + (targetRect.height / 2) - (tooltipHeight / 2);
                left = targetRect.right + margin;
                if (left + tooltipWidth > windowWidth - margin) {
                    left = targetRect.left - tooltipWidth - margin;
                    position = 'left';
                }
                break;
            case 'left':
                top = targetRect.top + (targetRect.height / 2) - (tooltipHeight / 2);
                left = targetRect.left - tooltipWidth - margin;
                break;
            case 'bottom':
                top = targetRect.bottom + margin;
                left = targetRect.left + (targetRect.width / 2) - (tooltipWidth / 2);
                if (left < margin) left = margin;
                if (left + tooltipWidth > windowWidth - margin) left = windowWidth - tooltipWidth - margin;
                break;
            case 'top':
                top = targetRect.top - tooltipHeight - margin;
                left = targetRect.left + (targetRect.width / 2) - (tooltipWidth / 2);
                if (left < margin) left = margin;
                if (left + tooltipWidth > windowWidth - margin) left = windowWidth - tooltipWidth - margin;
                if (top < margin) {
                    top = targetRect.bottom + margin;
                    position = 'bottom';
                }
                break;
        }

        if (top < margin) top = margin;
        if (top + tooltipHeight > windowHeight - margin) top = windowHeight - tooltipHeight - margin;

        $tooltip.attr('data-position', position);
        $tooltip.css({
            top: top + 'px',
            left: left + 'px'
        });
    }

    function highlightElement(step) {
        var $target = $(step.target);
        if ($target.length) {
            highlightedElement = $target[0];
            $target.addClass('schemafy-tour-highlight');

            var targetRect = $target[0].getBoundingClientRect();
            if (targetRect.top < 0 || targetRect.bottom > $(window).height()) {
                $target[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
                setTimeout(function() {
                    positionTooltip(step.target, step.position);
                }, 300);
            } else {
                positionTooltip(step.target, step.position);
            }
        }
    }

    function showStep(stepIndex) {
        if (stepIndex < 0 || stepIndex >= tourSteps.length) return;

        currentStep = stepIndex;
        var step = tourSteps[stepIndex];

        if (highlightedElement) {
            $(highlightedElement).removeClass('schemafy-tour-highlight');
        }

        var currentTab = $('.schemafy-tab-btn-v2.active').data('tab');
        if (!step.noNavigate && step.tab && step.tab !== currentTab) {
            $('.schemafy-tab-btn-v2[data-tab="' + step.tab + '"]').trigger('click');
            setTimeout(function() {
                highlightElement(step);
            }, 150);
        } else {
            highlightElement(step);
        }

        $stepBadge.text((stepIndex + 1) + '/' + tourSteps.length);
        $title.text(step.title);
        $content.text(step.content);

        $prevBtn.toggle(stepIndex > 0);
        if (stepIndex === tourSteps.length - 1) {
            $nextBtn.html(SCHEMAFY_TOUR_STRINGS?.finish || 'Finish');
        } else {
            $nextBtn.html(SCHEMAFY_TOUR_STRINGS?.next || 'Next');
        }

        $tooltip.addClass('active');
    }

    function saveDismissPreference() {
        $.post(ajaxurl, {
            action: 'schemafy_dismiss_onboarding',
            nonce: SCHEMAFY_TOUR_STRINGS.dismiss_nonce
        });
    }

    function startTour() {
        $welcomeModal.fadeOut(200);
        $overlay.addClass('active');
        if (!$('.schemafy-tab-btn-v2[data-tab="dashboard"]').hasClass('active')) {
            $('.schemafy-tab-btn-v2[data-tab="dashboard"]').trigger('click');
        }
        setTimeout(function() {
            showStep(0);
        }, 300);
    }

    function endTour(dismiss) {
        $overlay.removeClass('active');
        $tooltip.removeClass('active');
        if (highlightedElement) {
            $(highlightedElement).removeClass('schemafy-tour-highlight');
            highlightedElement = null;
        }
        if (dismiss) {
            saveDismissPreference();
        }
    }

    function closeWelcome(dismiss) {
        $welcomeModal.fadeOut(200);
        if (dismiss) {
            saveDismissPreference();
        }
    }

    $('#schemafy-welcome-start').on('click', function() {
        if ($dontShowWelcome.is(':checked')) {
            $dontShowTour.prop('checked', true);
        }
        startTour();
    });

    $('#schemafy-welcome-skip').on('click', function() {
        closeWelcome($dontShowWelcome.is(':checked'));
    });

    $nextBtn.on('click', function() {
        if (currentStep < tourSteps.length - 1) {
            showStep(currentStep + 1);
        } else {
            endTour(true);
            $('.schemafy-tab-btn-v2[data-tab="builder"]').trigger('click');
        }
    });

    $prevBtn.on('click', function() {
        if (currentStep > 0) {
            showStep(currentStep - 1);
        }
    });

    $skipBtn.on('click', function() {
        endTour($dontShowTour.is(':checked'));
    });

    $closeBtn.on('click', function() {
        endTour($dontShowTour.is(':checked'));
    });

    $overlay.on('click', function(e) {
        if ($(e.target).is($overlay)) {
            endTour($dontShowTour.is(':checked'));
        }
    });

    $(document).on('keydown.tour', function(e) {
        if (e.key === 'Escape') {
            if ($welcomeModal.is(':visible')) {
                closeWelcome($dontShowWelcome.is(':checked'));
            } else if ($tooltip.hasClass('active')) {
                endTour($dontShowTour.is(':checked'));
            }
        }
    });

    $(document).on('keydown.tour', function(e) {
        if (!$tooltip.hasClass('active')) return;
        if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
            e.preventDefault();
            $nextBtn.trigger('click');
        } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
            e.preventDefault();
            if (currentStep > 0) $prevBtn.trigger('click');
        }
    });

    $(window).on('resize.tour', function() {
        if ($tooltip.hasClass('active') && tourSteps[currentStep]) {
            positionTooltip(tourSteps[currentStep].target, tourSteps[currentStep].position);
        }
    });

    // Restart tutorial button
    $('#schemafy-restart-tutorial').on('click', function(e) {
        e.preventDefault();
        $.post(ajaxurl, {
            action: 'schemafy_reset_onboarding',
            nonce: SCHEMAFY_TOUR_STRINGS.reset_nonce
        }).done(function(response) {
            if (response.success) {
                window.location.reload();
            }
        });
    });

    // Move WordPress admin notices above the plugin layout
    (function() {
        var $banner = $('#schemafy-notices-banner');
        var $wrap = $('.schemafy-admin-wrap-v2');
        $wrap.prevAll('.notice, .updated, .update-nag, .error, .warning').each(function() {
            $banner.append($(this));
        });
        $wrap.find('> .notice, > .updated, > .error, > .warning').each(function() {
            $banner.append($(this));
        });
    }());

    // Initialize V2 enhancements
    if (typeof SCHEMAFY !== 'undefined' && typeof SCHEMAFY.initV2Enhancements === 'function') {
        SCHEMAFY.initV2Enhancements();
    }
});
