/**
 * Wally Monitor - Onboarding Wizard
 * First-scan guided experience (inspired by Don't Make Me Think).
 * Shows only once — stores completion in localStorage.
 *
 * @module WallyMonitor.Onboarding
 * @since 1.1.0
 */
(function($) {
    'use strict';

    window.WallyMonitor = window.WallyMonitor || {};
    WallyMonitor.Onboarding = WallyMonitor.Onboarding || {};

    var STORAGE_KEY = 'wally_onboarding_completed';
    var currentStep = 0;

    var steps = [
        {
            title: 'Bem-vindo ao Equallyze! 🎉',
            icon: '🌟',
            content: '<p>O <strong>Equallyze</strong> é o monitor de acessibilidade mais completo para WordPress.</p>' +
                '<p>Ele verifica seu site contra:</p>' +
                '<ul>' +
                '<li>✅ <strong>WCAG 2.2</strong> — Padrão internacional de acessibilidade</li>' +
                '<li>✅ <strong>NBR 17.225</strong> — Norma brasileira (ex-eMAG)</li>' +
                '<li>✅ <strong>48 regras exclusivas</strong> que nenhum outro plugin verifica</li>' +
                '</ul>',
            action: null
        },
        {
            title: 'Escaneie seu site em 1 clique 🔍',
            icon: '🚀',
            content: '<p>Clique em <strong>"Analisar Site Completo Agora"</strong> para iniciar.</p>' +
                '<p>O Equallyze vai:</p>' +
                '<ol>' +
                '<li>Carregar cada página do seu site em segundo plano</li>' +
                '<li>Rodar <strong>208+ regras de acessibilidade</strong> (WCAG 2.2 + NBR 17.225 + regras exclusivas)</li>' +
                '<li>Gerar um score de 0 a 100 com visualização em gauge</li>' +
                '</ol>' +
                '<p class="wally-onboarding-tip">💡 <em>Dica: páginas com muitas imagens podem demorar mais.</em></p>',
            highlight: '#wally-run-full-scan'
        },
        {
            title: 'Entenda os resultados 📊',
            icon: '📋',
            content: '<p>Após o escaneamento, você verá:</p>' +
                '<div class="wally-onboarding-features">' +
                '<div class="wally-onboarding-feature">' +
                '<span class="wally-onboarding-feature-icon">🎯</span>' +
                '<div><strong>Gauge de Score</strong><br>Visualização animada da nota geral (0-100)</div>' +
                '</div>' +
                '<div class="wally-onboarding-feature">' +
                '<span class="wally-onboarding-feature-icon">⚡</span>' +
                '<div><strong>Quick Fix</strong><br>Sugestões de código prontas para copiar e corrigir</div>' +
                '</div>' +
                '<div class="wally-onboarding-feature">' +
                '<span class="wally-onboarding-feature-icon">🔍</span>' +
                '<div><strong>Localizar Elemento</strong><br>Clique em "Localizar" para ver exatamente onde está o problema</div>' +
                '</div>' +
                '<div class="wally-onboarding-feature">' +
                '<span class="wally-onboarding-feature-icon">📥</span>' +
                '<div><strong>Exportar</strong><br>Baixe relatórios em PDF, JSON ou CSV</div>' +
                '</div>' +
                '</div>',
            action: null
        },
        {
            title: 'Pronto para começar? 🎯',
            icon: '✨',
            content: '<p>Você também pode:</p>' +
                '<ul>' +
                '<li>📝 Verificar posts individuais no <strong>Editor do WordPress</strong> (meta box lateral)</li>' +
                '<li>📈 Acompanhar a evolução do site na aba <strong>Histórico</strong></li>' +
                '<li>🔎 Integrar com <strong>Yoast SEO</strong> e <strong>Rank Math</strong> para SEO acessível</li>' +
                '</ul>' +
                '<p style="text-align: center; margin-top: 16px;">' +
                '<strong style="color: #38D39F; font-size: 18px;">Vamos deixar seu site mais acessível!</strong>' +
                '</p>',
            action: null
        }
    ];

    /**
     * Check if onboarding should show.
     */
    WallyMonitor.Onboarding.shouldShow = function() {
        // Only show on main report page
        if (typeof wallyData === 'undefined' || wallyData.hook !== 'toplevel_page_wally-monitor') {
            return false;
        }
        // Check localStorage
        try {
            return !localStorage.getItem(STORAGE_KEY);
        } catch (e) {
            return false;
        }
    };

    /**
     * Mark onboarding as completed.
     */
    WallyMonitor.Onboarding.complete = function() {
        try {
            localStorage.setItem(STORAGE_KEY, '1');
        } catch (e) { /* silent */ }
    };

    /**
     * Reset onboarding (for re-showing).
     */
    WallyMonitor.Onboarding.reset = function() {
        try {
            localStorage.removeItem(STORAGE_KEY);
        } catch (e) { /* silent */ }
    };

    /**
     * Initialize and show onboarding if needed.
     */
    WallyMonitor.Onboarding.init = function() {
        if (!WallyMonitor.Onboarding.shouldShow()) { return; }
        currentStep = 0;
        renderOverlay();
        renderStep(0);
    };

    // ─── Rendering ──────────────────────────────────────────────────────

    function renderOverlay() {
        if ($('#wally-onboarding-overlay').length) { return; }

        var html = '<div id="wally-onboarding-overlay" class="wally-onboarding-overlay">' +
            '<div class="wally-onboarding-modal">' +
            '<button class="wally-onboarding-close" title="Pular introdução">&times;</button>' +
            '<div class="wally-onboarding-progress"></div>' +
            '<div class="wally-onboarding-body"></div>' +
            '<div class="wally-onboarding-footer">' +
            '<button class="button wally-onboarding-skip">Pular</button>' +
            '<div class="wally-onboarding-nav">' +
            '<button class="button wally-onboarding-prev" style="display:none;">← Anterior</button>' +
            '<button class="button button-primary wally-onboarding-next">Próximo →</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        $('body').append(html);

        // Event listeners
        $(document).on('click', '.wally-onboarding-next', function() {
            if (currentStep < steps.length - 1) {
                currentStep++;
                renderStep(currentStep);
            } else {
                closeOnboarding();
            }
        });

        $(document).on('click', '.wally-onboarding-prev', function() {
            if (currentStep > 0) {
                currentStep--;
                renderStep(currentStep);
            }
        });

        $(document).on('click', '.wally-onboarding-skip, .wally-onboarding-close', function() {
            closeOnboarding();
        });

        // Close on Escape
        $(document).on('keydown.wallyOnboarding', function(e) {
            if (e.key === 'Escape') { closeOnboarding(); }
        });
    }

    function renderStep(index) {
        var step = steps[index];
        var $modal = $('.wally-onboarding-modal');

        // Progress dots
        var progressHtml = '';
        for (var i = 0; i < steps.length; i++) {
            progressHtml += '<span class="wally-onboarding-dot' + (i === index ? ' active' : '') +
                (i < index ? ' completed' : '') + '"></span>';
        }
        $modal.find('.wally-onboarding-progress').html(progressHtml);

        // Body
        var bodyHtml = '<div class="wally-onboarding-step-icon">' + step.icon + '</div>' +
            '<h2 class="wally-onboarding-title">' + step.title + '</h2>' +
            '<div class="wally-onboarding-content">' + step.content + '</div>';
        $modal.find('.wally-onboarding-body').html(bodyHtml);

        // Navigation
        $modal.find('.wally-onboarding-prev').toggle(index > 0);
        if (index === steps.length - 1) {
            $modal.find('.wally-onboarding-next').text('Começar! 🚀');
            $modal.find('.wally-onboarding-skip').hide();
        } else {
            $modal.find('.wally-onboarding-next').text('Próximo →');
            $modal.find('.wally-onboarding-skip').show();
        }

        // Highlight target element
        $('.wally-onboarding-highlight').removeClass('wally-onboarding-highlight');
        if (step.highlight) {
            $(step.highlight).addClass('wally-onboarding-highlight');
        }

        // Animate entry
        $modal.find('.wally-onboarding-body').css({ opacity: 0, transform: 'translateY(10px)' })
            .animate({ opacity: 1 }, 300)
            .css('transform', 'translateY(0)');
    }

    function closeOnboarding() {
        WallyMonitor.Onboarding.complete();
        $('.wally-onboarding-highlight').removeClass('wally-onboarding-highlight');
        $('#wally-onboarding-overlay').fadeOut(300, function() {
            $(this).remove();
        });
        $(document).off('keydown.wallyOnboarding');
    }

    // ─── Auto-init on DOM ready ─────────────────────────────────────────
    $(function() {
        // Slight delay to ensure page elements are rendered
        setTimeout(function() {
            WallyMonitor.Onboarding.init();
        }, 500);
    });

})(jQuery);
