/**
 * @file wally-ui.js
 * @description UI rendering for Wally Monitor — displayReport (with pagination,
 *              filters, violation cards), highlightElementInEditor, saveReport.
 *              Depends on: WallyMonitor.Utils.
 * @module WallyMonitor.UI
 */
window.WallyMonitor = window.WallyMonitor || {};

(function($) {
    'use strict';

    WallyMonitor.UI = WallyMonitor.UI || {};

    /**
     * Exibe o relatório na interface
     * @param {Object} report - Relatório processado
     * @param {string|null} targetContainer - Seletor do container alvo (null para página principal)
     */
    WallyMonitor.UI.displayReport = function(report, targetContainer) {
        var escapeHtml = WallyMonitor.Utils.escapeHtml;
        var getImpactColor = WallyMonitor.Utils.getImpactColor;

        const $container = targetContainer ? $(targetContainer) : $('#wally-report-container');
        const $summaryContainer = targetContainer ? $container : $('#wally-summary');
        const $resultsContainer = targetContainer ? $container : $('#wally-results');

        if (!targetContainer) {
            $container.show();
            // Limpa containers anteriores
            $summaryContainer.empty();
            $resultsContainer.empty();
            // Remove seção de estatísticas de conformidade de scan anterior
            $('.wally-conformity-stats').remove();
        } else {
            $container.empty(); // Limpa o container do editor
        }

        // Monta o sumário com gauge animado
        const score = report.summary.score;
        const scoreColor = score >= 90 ? 'var(--wally-mint, #38D39F)' : 
                          score >= 70 ? 'var(--wally-moderate, #e5a537)' : 
                          score >= 50 ? 'var(--wally-serious, #e5793a)' : 'var(--wally-critical, #e5484d)';
        const scoreLabel = score >= 90 ? 'Excelente' :
                          score >= 70 ? 'Bom' :
                          score >= 50 ? 'Precisa Melhorar' : 'Crítico';
        
        // SVG gauge arc calculation (270° arc)
        const radius = 80;
        const circumference = 2 * Math.PI * radius;
        const arcLength = circumference * 0.75; // 270°
        const dashOffset = arcLength - (arcLength * score / 100);

        const summaryHtml = `
            <div class="wally-dashboard-header">
                <div class="wally-gauge-container">
                    <svg class="wally-gauge" viewBox="0 0 200 200" width="200" height="200">
                        <circle class="wally-gauge-bg" cx="100" cy="100" r="${radius}" 
                            fill="none" stroke="#e9ecef" stroke-width="16"
                            stroke-dasharray="${arcLength} ${circumference}"
                            stroke-dashoffset="0"
                            transform="rotate(135 100 100)"
                            stroke-linecap="round"/>
                        <circle class="wally-gauge-fill" cx="100" cy="100" r="${radius}" 
                            fill="none" stroke="${scoreColor}" stroke-width="16"
                            stroke-dasharray="${arcLength} ${circumference}"
                            stroke-dashoffset="${dashOffset}"
                            transform="rotate(135 100 100)"
                            stroke-linecap="round"
                            style="transition: stroke-dashoffset 1.5s cubic-bezier(0.4, 0, 0.2, 1);"/>
                    </svg>
                    <div class="wally-gauge-label">
                        <span class="wally-gauge-score" style="color: ${scoreColor};">${score}</span>
                        <span class="wally-gauge-max">/100</span>
                        <span class="wally-gauge-text">${scoreLabel}</span>
                        <span class="wally-gauge-level">${report.summary.conformanceLevel || 'N/A'}</span>
                    </div>
                </div>
                <div class="wally-summary-metrics">
                    <div class="wally-metric-card wally-fade-in wally-stagger-1">
                        <div class="wally-metric-icon"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg></div>
                        <div class="wally-metric-value">${report.summary.totalProblems}</div>
                        <div class="wally-metric-label">Problemas</div>
                    </div>
                    <div class="wally-metric-card wally-fade-in wally-stagger-2">
                        <div class="wally-metric-icon"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg></div>
                        <div class="wally-metric-value">${report.summary.rulesViolated.length}</div>
                        <div class="wally-metric-label">Regras Violadas</div>
                    </div>
                    <div class="wally-metric-card wally-fade-in wally-stagger-3">
                        <div class="wally-metric-icon wally-metric-critical"><svg width="22" height="22" viewBox="0 0 24 24" fill="var(--wally-critical, #e5484d)" stroke="none"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15" stroke="white" stroke-width="2" stroke-linecap="round"/><line x1="9" y1="9" x2="15" y2="15" stroke="white" stroke-width="2" stroke-linecap="round"/></svg></div>
                        <div class="wally-metric-value wally-metric-value--critical">${report.summary.byImpact.critical}</div>
                        <div class="wally-metric-label">Críticos</div>
                    </div>
                    <div class="wally-metric-card wally-fade-in wally-stagger-4">
                        <div class="wally-metric-icon"><svg width="22" height="22" viewBox="0 0 24 24" fill="var(--wally-serious, #e5793a)" stroke="none"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13" stroke="white" stroke-width="2" stroke-linecap="round"/><line x1="12" y1="17" x2="12.01" y2="17" stroke="white" stroke-width="2" stroke-linecap="round"/></svg></div>
                        <div class="wally-metric-value wally-metric-value--serious">${report.summary.byImpact.serious}</div>
                        <div class="wally-metric-label">Sérios</div>
                    </div>
                </div>
            </div>
            <div class="wally-summary-cards-row">
                <div class="wally-summary-card">
                    <p>Distribuição WCAG</p>
                    <div style="display: flex; gap: 15px; margin-top: 5px;">
                        <span><strong>A:</strong> ${report.summary.wcagLevels?.A || 0}</span>
                        <span><strong>AA:</strong> ${report.summary.wcagLevels?.AA || 0}</span>
                        <span><strong>AAA:</strong> ${report.summary.wcagLevels?.AAA || 0}</span>
                    </div>
                </div>
                ${report.summary.wpBlocks && (report.summary.wpBlocks.images > 0 || report.summary.wpBlocks.buttons > 0 || report.summary.wpBlocks.headings > 0 || report.summary.wpBlocks.links > 0 || report.summary.wpBlocks.other > 0) ? `
                <div class="wally-summary-card">
                    <p>Blocos WordPress</p>
                    <div style="display: flex; gap: 12px; margin-top: 5px; flex-wrap: wrap;">
                        ${report.summary.wpBlocks.images > 0 ? `<span class="wally-block-tag"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg> ${report.summary.wpBlocks.images}</span>` : ''}
                        ${report.summary.wpBlocks.buttons > 0 ? `<span class="wally-block-tag"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="8" width="18" height="8" rx="2" ry="2"/><line x1="8" y1="12" x2="16" y2="12"/></svg> ${report.summary.wpBlocks.buttons}</span>` : ''}
                        ${report.summary.wpBlocks.links > 0 ? `<span class="wally-block-tag"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg> ${report.summary.wpBlocks.links}</span>` : ''}
                        ${report.summary.wpBlocks.headings > 0 ? `<span class="wally-block-tag"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/></svg> ${report.summary.wpBlocks.headings}</span>` : ''}
                        ${report.summary.wpBlocks.other > 0 ? `<span class="wally-block-tag"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg> ${report.summary.wpBlocks.other}</span>` : ''}
                    </div>
                </div>
                ` : ''}
            </div>
        `;
        $summaryContainer.html(summaryHtml);

        // Animação do gauge: inicia de 0 e anima até o valor
        setTimeout(function() {
            var gaugeFill = document.querySelector('.wally-gauge-fill');
            if (gaugeFill) {
                gaugeFill.style.strokeDashoffset = dashOffset;
            }
        }, 100);

        // Helper: safe percentage (avoids division by zero → NaN/Infinity)
        const pct = (part, total) => total > 0 ? Math.round((part / total) * 100) : 0;

        // Adiciona estatísticas de conformidade em seção separada se houver dados
        if (report.summary.elementsStats && (report.summary.elementsStats.totalImages > 0 || report.summary.elementsStats.totalLinks > 0)) {
            const statsHtml = `
                <div class="wally-conformity-stats wally-fade-in">
                    <h3 class="wally-conformity-title">
                        <span class="wally-conformity-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg></span>
                        Estatísticas de Conformidade
                    </h3>
                    <div class="wally-stats-grid">
                        ${report.summary.elementsStats.totalImages > 0 ? `
                        <div class="wally-stat-card wally-fade-in wally-stagger-1">
                            <div class="wally-stat-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></div>
                            <div class="wally-stat-content">
                                <div class="wally-stat-label">Imagens</div>
                                <div class="wally-stat-value">${report.summary.elementsStats.imagesWithAlt}/${report.summary.elementsStats.totalImages} <span class="wally-stat-suffix">com alt</span></div>
                                <div class="wally-stat-bar">
                                    <div class="wally-stat-bar-fill" style="width: ${pct(report.summary.elementsStats.imagesWithAlt, report.summary.elementsStats.totalImages)}%"></div>
                                </div>
                                <div class="wally-stat-percent">${pct(report.summary.elementsStats.imagesWithAlt, report.summary.elementsStats.totalImages)}%</div>
                            </div>
                        </div>
                        ` : ''}
                        ${report.summary.elementsStats.totalFormFields > 0 ? `
                        <div class="wally-stat-card">
                            <div class="wally-stat-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></div>
                            <div class="wally-stat-content">
                                <div class="wally-stat-label">Formulários</div>
                                <div class="wally-stat-value">${report.summary.elementsStats.formFieldsWithLabel}/${report.summary.elementsStats.totalFormFields} <span class="wally-stat-suffix">com label</span></div>
                                <div class="wally-stat-bar">
                                    <div class="wally-stat-bar-fill" style="width: ${pct(report.summary.elementsStats.formFieldsWithLabel, report.summary.elementsStats.totalFormFields)}%"></div>
                                </div>
                                <div class="wally-stat-percent">${pct(report.summary.elementsStats.formFieldsWithLabel, report.summary.elementsStats.totalFormFields)}%</div>
                            </div>
                        </div>
                        ` : ''}
                        ${report.summary.elementsStats.totalLinks > 0 ? `
                        <div class="wally-stat-card">
                            <div class="wally-stat-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></div>
                            <div class="wally-stat-content">
                                <div class="wally-stat-label">Links</div>
                                <div class="wally-stat-value">${report.summary.elementsStats.linksWithText}/${report.summary.elementsStats.totalLinks} <span class="wally-stat-suffix">descritivos</span></div>
                                <div class="wally-stat-bar">
                                    <div class="wally-stat-bar-fill" style="width: ${pct(report.summary.elementsStats.linksWithText, report.summary.elementsStats.totalLinks)}%"></div>
                                </div>
                                <div class="wally-stat-percent">${pct(report.summary.elementsStats.linksWithText, report.summary.elementsStats.totalLinks)}%</div>
                            </div>
                        </div>
                        ` : ''}
                        ${report.summary.elementsStats.totalButtons > 0 ? `
                        <div class="wally-stat-card">
                            <div class="wally-stat-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="8" width="18" height="8" rx="2" ry="2"/><line x1="8" y1="12" x2="16" y2="12"/></svg></div>
                            <div class="wally-stat-content">
                                <div class="wally-stat-label">Botões</div>
                                <div class="wally-stat-value">${report.summary.elementsStats.buttonsWithLabel}/${report.summary.elementsStats.totalButtons} <span class="wally-stat-suffix">com label</span></div>
                                <div class="wally-stat-bar">
                                    <div class="wally-stat-bar-fill" style="width: ${pct(report.summary.elementsStats.buttonsWithLabel, report.summary.elementsStats.totalButtons)}%"></div>
                                </div>
                                <div class="wally-stat-percent">${pct(report.summary.elementsStats.buttonsWithLabel, report.summary.elementsStats.totalButtons)}%</div>
                            </div>
                        </div>
                        ` : ''}
                        ${report.summary.elementsStats.totalHeadings > 0 ? `
                        <div class="wally-stat-card">
                            <div class="wally-stat-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/></svg></div>
                            <div class="wally-stat-content">
                                <div class="wally-stat-label">Headings</div>
                                <div class="wally-stat-value">${report.summary.elementsStats.headingsCorrect}/${report.summary.elementsStats.totalHeadings} <span class="wally-stat-suffix">corretos</span></div>
                                <div class="wally-stat-bar">
                                    <div class="wally-stat-bar-fill" style="width: ${pct(report.summary.elementsStats.headingsCorrect, report.summary.elementsStats.totalHeadings)}%"></div>
                                </div>
                                <div class="wally-stat-percent">${pct(report.summary.elementsStats.headingsCorrect, report.summary.elementsStats.totalHeadings)}%</div>
                            </div>
                        </div>
                        ` : ''}
                        ${report.summary.elementsStats.totalTables > 0 ? `
                        <div class="wally-stat-card">
                            <div class="wally-stat-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/></svg></div>
                            <div class="wally-stat-content">
                                <div class="wally-stat-label">Tabelas</div>
                                <div class="wally-stat-value">${report.summary.elementsStats.tablesAccessible}/${report.summary.elementsStats.totalTables} <span class="wally-stat-suffix">acessíveis</span></div>
                                <div class="wally-stat-bar">
                                    <div class="wally-stat-bar-fill" style="width: ${pct(report.summary.elementsStats.tablesAccessible, report.summary.elementsStats.totalTables)}%"></div>
                                </div>
                                <div class="wally-stat-percent">${pct(report.summary.elementsStats.tablesAccessible, report.summary.elementsStats.totalTables)}%</div>
                            </div>
                        </div>
                        ` : ''}
                        ${report.summary.elementsStats.totalVideos > 0 ? `
                        <div class="wally-stat-card">
                            <div class="wally-stat-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg></div>
                            <div class="wally-stat-content">
                                <div class="wally-stat-label">Vídeos</div>
                                <div class="wally-stat-value">${report.summary.elementsStats.videosWithCaptions}/${report.summary.elementsStats.totalVideos} <span class="wally-stat-suffix">com legendas</span></div>
                                <div class="wally-stat-bar">
                                    <div class="wally-stat-bar-fill" style="width: ${pct(report.summary.elementsStats.videosWithCaptions, report.summary.elementsStats.totalVideos)}%"></div>
                                </div>
                                <div class="wally-stat-percent">${pct(report.summary.elementsStats.videosWithCaptions, report.summary.elementsStats.totalVideos)}%</div>
                            </div>
                        </div>
                        ` : ''}
                    </div>
                </div>
            `;
            $summaryContainer.after(statsHtml);
        }

        // Configuração de paginação
        const ITEMS_PER_PAGE = 10;
        let currentPage = 1;
        let currentFilter = null; // null = todos, ou 'critical', 'serious', etc.
        let currentEngine = null; // null = todos, ou 'wcag', 'wally-nbr', etc.
        let currentGroupBy = 'priority'; // 'priority' | 'page' | 'rule'
        let currentSort = 'impact';      // 'impact' | 'count' | 'quickfix'
        
        // ── Prioritized Action Plan sort ────────────────────────────
        const IMPACT_ORDER = { critical: 0, serious: 1, moderate: 2, minor: 3 };

        const sortViolations = function(violations, sortKey) {
            return violations.slice().sort(function(a, b) {
                if (sortKey === 'impact') {
                    var impactDiff = (IMPACT_ORDER[a.impact] || 9) - (IMPACT_ORDER[b.impact] || 9);
                    if (impactDiff !== 0) { return impactDiff; }
                    return b.nodes.length - a.nodes.length; // secondary: more elements first
                }
                if (sortKey === 'count') {
                    return b.nodes.length - a.nodes.length;
                }
                if (sortKey === 'quickfix') {
                    var aQF = WallyMonitor.QuickFix && WallyMonitor.QuickFix.hasQuickFix(a.id) ? 0 : 1;
                    var bQF = WallyMonitor.QuickFix && WallyMonitor.QuickFix.hasQuickFix(b.id) ? 0 : 1;
                    if (aQF !== bQF) { return aQF - bQF; }
                    return (IMPACT_ORDER[a.impact] || 9) - (IMPACT_ORDER[b.impact] || 9);
                }
                return 0;
            });
        };

        // ── Group by page helper ────────────────────────────────────
        const groupByPage = function(violations) {
            var groups = {};
            violations.forEach(function(v) {
                var pages = {};
                v.nodes.forEach(function(n) {
                    var url = n.pageUrl || window.location.href;
                    if (!pages[url]) { pages[url] = []; }
                    pages[url].push(n);
                });
                Object.keys(pages).forEach(function(url) {
                    if (!groups[url]) { groups[url] = []; }
                    groups[url].push({ violation: v, nodes: pages[url] });
                });
            });
            return groups;
        };

        // ── Collect unique engines for filter ───────────────────────
        var availableEngines = {};
        report.violations.forEach(function(v) {
            var engine = v._source || 'wcag';
            availableEngines[engine] = (availableEngines[engine] || 0) + 1;
        });
        var engineLabels = {
            'wcag': 'WCAG 2.2',
            'wally-custom': 'WordPress',
            'wally-nbr': 'NBR 17225',
            'wally-ifthen': 'IF-THEN'
        };

        // ── Check if multi-page scan ────────────────────────────────
        var hasMultiplePages = false;
        (function() {
            var pageSet = {};
            report.violations.forEach(function(v) {
                v.nodes.forEach(function(n) {
                    if (n.pageUrl) { pageSet[n.pageUrl] = true; }
                });
            });
            hasMultiplePages = Object.keys(pageSet).length > 1;
        })();

        // Função para renderizar página específica
        const renderPage = (page, filter) => {
            filter = typeof filter !== 'undefined' ? filter : null;
            currentPage = page;
            currentFilter = filter;
            
            // Filtra violações
            let filteredViolations = report.violations;
            if (filter) {
                filteredViolations = filteredViolations.filter(v => v.impact === filter);
            }
            if (currentEngine) {
                filteredViolations = filteredViolations.filter(v => (v._source || 'wcag') === currentEngine);
            }

            // Sort by action plan priority
            filteredViolations = sortViolations(filteredViolations, currentSort);

            const totalPages = Math.ceil(filteredViolations.length / ITEMS_PER_PAGE);
            const startIndex = (page - 1) * ITEMS_PER_PAGE;
            const endIndex = startIndex + ITEMS_PER_PAGE;
            
            // ── Build Advanced Filters Bar (main page only) ─────────
            let filtersHtml = '';
            if (!targetContainer) {
                // Engine filter options
                var engineOptions = '<option value="">Todos Engines</option>';
                Object.keys(availableEngines).forEach(function(eng) {
                    var sel = (currentEngine === eng) ? ' selected' : '';
                    engineOptions += '<option value="' + escapeHtml(eng) + '"' + sel + '>' + escapeHtml(engineLabels[eng] || eng) + ' (' + availableEngines[eng] + ')</option>';
                });

                // Sort options
                var sortOptions = [
                    { val: 'impact', label: '▼ Impacto (Plano de Ação)' },
                    { val: 'count', label: '# Nº de Elementos' },
                    { val: 'quickfix', label: '⚡ Quick Fix Primeiro' }
                ];
                var sortOptionsHtml = sortOptions.map(function(o) {
                    return '<option value="' + o.val + '"' + (currentSort === o.val ? ' selected' : '') + '>' + o.label + '</option>';
                }).join('');

                // Group by options
                var groupOptions = '<option value="priority"' + (currentGroupBy === 'priority' ? ' selected' : '') + '>Prioridade</option>';
                if (hasMultiplePages) {
                    groupOptions += '<option value="page"' + (currentGroupBy === 'page' ? ' selected' : '') + '>Página</option>';
                }

                filtersHtml = `
                    <div class="wally-filters wally-pill-bar">
                        <button class="wally-pill ${!filter ? 'active' : ''}" data-filter="all" aria-pressed="${!filter ? 'true' : 'false'}">
                            Todos (${report.violations.length})
                        </button>
                        <button class="wally-pill critical ${filter === 'critical' ? 'active' : ''}" data-filter="critical" aria-pressed="${filter === 'critical' ? 'true' : 'false'}">
                            Crítico (${report.summary.byImpact.critical})
                        </button>
                        <button class="wally-pill serious ${filter === 'serious' ? 'active' : ''}" data-filter="serious" aria-pressed="${filter === 'serious' ? 'true' : 'false'}">
                            Sério (${report.summary.byImpact.serious})
                        </button>
                        <button class="wally-pill moderate ${filter === 'moderate' ? 'active' : ''}" data-filter="moderate" aria-pressed="${filter === 'moderate' ? 'true' : 'false'}">
                            Moderado (${report.summary.byImpact.moderate})
                        </button>
                        <button class="wally-pill minor ${filter === 'minor' ? 'active' : ''}" data-filter="minor" aria-pressed="${filter === 'minor' ? 'true' : 'false'}">
                            Leve (${report.summary.byImpact.minor})
                        </button>
                    </div>
                    <div class="wally-advanced-filters">
                        <div class="wally-filter-group">
                            <label for="wally-engine-filter" class="wally-filter-label">Engine:</label>
                            <select id="wally-engine-filter" class="wally-filter-select">${engineOptions}</select>
                        </div>
                        <div class="wally-filter-group">
                            <label for="wally-sort-select" class="wally-filter-label">Ordenar:</label>
                            <select id="wally-sort-select" class="wally-filter-select">${sortOptionsHtml}</select>
                        </div>
                        ${hasMultiplePages ? `
                        <div class="wally-filter-group">
                            <label for="wally-group-select" class="wally-filter-label">Agrupar:</label>
                            <select id="wally-group-select" class="wally-filter-select">${groupOptions}</select>
                        </div>
                        ` : ''}
                    </div>
                `;
            }
            
            let violationsHtml = filtersHtml;

            // ── Build Action Plan Summary ───────────────────────────
            if (!targetContainer && filteredViolations.length > 0) {
                var quickFixCount = 0;
                filteredViolations.forEach(function(v) {
                    if (WallyMonitor.QuickFix && WallyMonitor.QuickFix.hasQuickFix(v.id)) { quickFixCount++; }
                });

                var topActions = filteredViolations.slice(0, 3);
                var actionStepsHtml = topActions.map(function(v, idx) {
                    var hasQF = WallyMonitor.QuickFix && WallyMonitor.QuickFix.hasQuickFix(v.id);
                    var impactIcon = v.impact === 'critical' ? '🔴' : v.impact === 'serious' ? '🟠' : v.impact === 'moderate' ? '🟡' : '🔵';
                    return '<li class="wally-action-step">' +
                        '<span class="wally-action-number">' + (idx + 1) + '</span>' +
                        '<span class="wally-action-text">' + impactIcon + ' ' + escapeHtml(v.help) +
                        ' <span class="wally-action-meta">(' + v.nodes.length + ' elem' + (v.nodes.length > 1 ? 's' : '') + ')' +
                        (hasQF ? ' ⚡' : '') + '</span></span></li>';
                }).join('');

                violationsHtml += `
                    <div class="wally-action-plan">
                        <div class="wally-action-plan-header">
                            <h3 class="wally-action-plan-title"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -2px; margin-right: 6px;"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/></svg>Plano de Ação Priorizado</h3>
                            <div class="wally-action-plan-stats">
                                <span class="wally-action-stat">${filteredViolations.length} regras</span>
                                <span class="wally-action-stat">${quickFixCount} ⚡ Quick Fix</span>
                            </div>
                        </div>
                        <ol class="wally-action-steps">${actionStepsHtml}</ol>
                        <p class="wally-action-hint">Resolva os itens na ordem acima para o maior impacto na acessibilidade.</p>
                    </div>
                `;
            }

            // ── Render violations (grouped or flat) ─────────────────
            if (currentGroupBy === 'page' && hasMultiplePages && !targetContainer) {
                // Group by page mode
                var pageGroups = groupByPage(filteredViolations);
                var pageUrls = Object.keys(pageGroups).sort();

                pageUrls.forEach(function(pageUrl) {
                    var pageItems = pageGroups[pageUrl];
                    var pageName = pageUrl.replace(/^https?:\/\/[^/]+/, '') || '/';
                    var totalNodesOnPage = 0;
                    pageItems.forEach(function(item) { totalNodesOnPage += item.nodes.length; });

                    violationsHtml += '<div class="wally-page-group">';
                    violationsHtml += '<div class="wally-page-group-header">';
                    violationsHtml += '<h3 class="wally-page-group-title">🌐 ' + escapeHtml(pageName) + '</h3>';
                    violationsHtml += '<span class="wally-page-group-count">' + pageItems.length + ' regras · ' + totalNodesOnPage + ' elementos</span>';
                    violationsHtml += '</div>';

                    pageItems.forEach(function(item) {
                        violationsHtml += renderViolationCard(item.violation, item.nodes, escapeHtml, getImpactColor);
                    });

                    violationsHtml += '</div>';
                });
            } else {
                // Flat / priority mode (paginated)
                var pageViolations = filteredViolations.slice(startIndex, endIndex);

                if (pageViolations.length === 0) {
                    violationsHtml += '<p class="wally-no-results">Nenhum problema encontrado neste filtro.</p>';
                } else {
                    violationsHtml += `
                        <div class="wally-pagination-info">
                            Exibindo ${startIndex + 1}-${Math.min(endIndex, filteredViolations.length)} de ${filteredViolations.length} problemas
                        </div>
                    `;

                    pageViolations.forEach(function(v) {
                        violationsHtml += renderViolationCard(v, v.nodes, escapeHtml, getImpactColor);
                    });

                    // Pagination controls
                    if (totalPages > 1) {
                        violationsHtml += renderPagination(page, totalPages);
                    }
                }
            }

            // Usa innerHTML nativo para evitar que jQuery interprete tags HTML
            // escapadas (ex: &lt;script&gt;) via buildFragment/appendChild
            $resultsContainer.empty()[0].innerHTML = violationsHtml;
            
            // ── Event listeners ─────────────────────────────────────
            // Pagination
            $('.wally-page-btn').on('click', function() {
                if (!$(this).prop('disabled')) {
                    var newPage = parseInt($(this).data('page'));
                    renderPage(newPage, currentFilter);
                    $resultsContainer[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            });
            
            // Impact filter pills (atualiza aria-pressed ao clicar)
            $('.wally-filters .wally-pill').on('click', function() {
                var f = $(this).data('filter');
                $('.wally-filters .wally-pill').attr('aria-pressed', 'false');
                $(this).attr('aria-pressed', 'true');
                renderPage(1, f === 'all' ? null : f);
            });

            // Engine filter
            $('#wally-engine-filter').on('change', function() {
                currentEngine = $(this).val() || null;
                renderPage(1, currentFilter);
            });

            // Sort
            $('#wally-sort-select').on('change', function() {
                currentSort = $(this).val();
                renderPage(1, currentFilter);
            });

            // Group by
            $('#wally-group-select').on('change', function() {
                currentGroupBy = $(this).val();
                renderPage(1, currentFilter);
            });
            
            // Highlight/localizar
            $('.wally-highlight-btn').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var target = $(this).data('target');
                var pageUrl = $(this).data('page-url');
                if (!pageUrl || pageUrl === window.location.href) {
                    WallyMonitor.UI.highlightElementInEditor(target);
                } else {
                    if (confirm('Este elemento está em outra página (' + pageUrl + ').\nDeseja abrir essa página em nova aba?')) {
                        window.open(pageUrl, '_blank');
                    }
                }
            });

            // Copy Quick Fix
            $('.wally-copy-fix').on('click', function(e) {
                e.preventDefault();
                var code = $(this).attr('data-code');
                if (!code) { return; }
                var tmp = document.createElement('textarea');
                tmp.innerHTML = code;
                code = tmp.value;
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(code).then(function() {
                        WallyMonitor.Utils.showNotification('📋 Código copiado para a área de transferência!', 'success');
                    });
                } else {
                    tmp.value = code;
                    tmp.style.position = 'fixed';
                    tmp.style.left = '-9999px';
                    document.body.appendChild(tmp);
                    tmp.select();
                    document.execCommand('copy');
                    document.body.removeChild(tmp);
                    WallyMonitor.Utils.showNotification('📋 Código copiado!', 'success');
                }
            });
        };

        // ── Violation card renderer (shared by flat & grouped) ──────
        const renderViolationCard = function(v, nodes, escape, getColor) {
            var hasQF = WallyMonitor.QuickFix && WallyMonitor.QuickFix.hasQuickFix(v.id);
            var priorityBadge = '';
            var quickFixBadge = '';
            var engineBadge = v._source ? '<span class="wally-engine-badge">' + escape(engineLabels[v._source] || v._source) + '</span>' : '';

            if (v.impact === 'critical' && v.nodes.length > 5) {
                priorityBadge = '<span class="priority-badge urgent" title="Alta prioridade: impacto crítico em múltiplos elementos">🔥 URGENTE</span>';
            }
            if (hasQF) {
                quickFixBadge = '<span class="priority-badge quick-fix" title="Correção rápida disponível">⚡ Quick Fix</span>';
            }

            var quickFixHtml = '';
            if (hasQF) {
                var qf = WallyMonitor.QuickFix.getSuggestion(v, 0);
                if (qf) {
                    quickFixHtml =
                        '<div class="wally-quickfix-panel">' +
                            '<div class="wally-quickfix-header">' +
                                '<span class="wally-quickfix-icon">' + escape(qf.icon) + '</span>' +
                                '<strong>' + escape(qf.label) + '</strong>' +
                            '</div>' +
                            '<p class="wally-quickfix-desc">' + escape(qf.description) + '</p>' +
                            '<pre class="wally-quickfix-code"><code>' + escape(qf.code) + '</code></pre>' +
                            '<button class="button button-small wally-copy-fix" data-code="' + escape(qf.code) + '" title="Copiar código">' +
                                '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px;"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg> Copiar Correção' +
                            '</button>' +
                        '</div>';
                }
            }

            var displayNodes = nodes || v.nodes;

            return '<div class="wally-violation" data-impact="' + escape(v.impact) + '" data-violation-id="' + escape(v.id) + '">' +
                '<div class="wally-violation-header">' +
                    '<h3>' + escape(v.help) + '</h3>' +
                    '<div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">' +
                        priorityBadge + quickFixBadge + engineBadge +
                        '<span class="impact-badge" style="background-color: ' + getColor(v.impact) + '">' + escape(v.impact) + '</span>' +
                    '</div>' +
                '</div>' +
                '<div class="wally-violation-body">' +
                    '<p>' + escape(v.description) + '</p>' +
                    '<p><a href="' + escape(v.helpUrl) + '" target="_blank" rel="noopener">Saiba mais</a></p>' +
                    '<strong>Encontrado em ' + escape(String(displayNodes.length)) + ' elemento(s):</strong>' +
                    '<ul>' +
                        displayNodes.slice(0, 5).map(function(node) {
                            return '<li>' +
                                '<code>' + escape(node.target[0]) + '</code> ' +
                                (node.pageUrl ? 'em <a href="' + escape(node.pageUrl) + '" target="_blank" rel="noopener">' + escape(node.pageUrl.split('/').pop() || '/') + '</a>' : '') +
                                '<button class="button button-small wally-highlight-btn" ' +
                                    'data-target="' + escape(node.target[0]) + '" ' +
                                    'data-page-url="' + escape(node.pageUrl || '') + '" ' +
                                    'style="margin-left: 8px; font-size: 11px; padding: 2px 8px;">' +
                                    '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg> Localizar' +
                                '</button>' +
                            '</li>';
                        }).join('') +
                        (displayNodes.length > 5 ? '<li><em>... e mais ' + (displayNodes.length - 5) + ' elemento(s)</em></li>' : '') +
                    '</ul>' +
                    quickFixHtml +
                '</div>' +
            '</div>';
        };

        // ── Pagination renderer ─────────────────────────────────────
        const renderPagination = function(page, totalPages) {
            var html = '<div class="wally-pagination">';

            if (page > 1) {
                html += '<button class="button wally-page-btn" data-page="' + (page - 1) + '">« Anterior</button>';
            } else {
                html += '<button class="button wally-page-btn" disabled>« Anterior</button>';
            }

            var maxButtons = 7;
            var startP = Math.max(1, page - Math.floor(maxButtons / 2));
            var endP = Math.min(totalPages, startP + maxButtons - 1);
            if (endP - startP < maxButtons - 1) { startP = Math.max(1, endP - maxButtons + 1); }

            if (startP > 1) {
                html += '<button class="button wally-page-btn" data-page="1">1</button>';
                if (startP > 2) { html += '<span class="wally-page-ellipsis">...</span>'; }
            }

            for (var i = startP; i <= endP; i++) {
                html += '<button class="button wally-page-btn ' + (i === page ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
            }

            if (endP < totalPages) {
                if (endP < totalPages - 1) { html += '<span class="wally-page-ellipsis">...</span>'; }
                html += '<button class="button wally-page-btn" data-page="' + totalPages + '">' + totalPages + '</button>';
            }

            if (page < totalPages) {
                html += '<button class="button wally-page-btn" data-page="' + (page + 1) + '">Próximo »</button>';
            } else {
                html += '<button class="button wally-page-btn" disabled>Próximo »</button>';
            }

            html += '</div>';
            return html;
        };

        // Renderiza primeira página
        renderPage(1);
    };

    /**
     * Destaca e rola até elemento problemático no editor
     * @param {string} selector - Seletor CSS do elemento
     */
    WallyMonitor.UI.highlightElementInEditor = function(selector) {
        try {
            // Tenta encontrar no iframe do editor (Gutenberg)
            const editorIframe = document.querySelector('iframe[name="editor-canvas"]');
            let targetDoc = document;
            let targetElement = null;
            
            if (editorIframe && editorIframe.contentDocument) {
                targetDoc = editorIframe.contentDocument;
                targetElement = targetDoc.querySelector(selector);
            }
            
            // Se não encontrou no iframe, procura no documento principal
            if (!targetElement) {
                targetElement = document.querySelector(selector);
            }
            
            if (targetElement) {
                // Remove highlights anteriores
                targetDoc.querySelectorAll('.wally-highlighted').forEach(el => {
                    el.classList.remove('wally-highlighted');
                });
                
                // Adiciona highlight ao elemento
                targetElement.classList.add('wally-highlighted');
                
                // Scroll suave até o elemento
                targetElement.scrollIntoView({ 
                    behavior: 'smooth', 
                    block: 'center',
                    inline: 'nearest'
                });
                
                // Remove highlight após 5 segundos
                setTimeout(() => {
                    targetElement.classList.remove('wally-highlighted');
                }, 5000);
                
                // Adiciona estilo inline temporário se a classe CSS não estiver carregada
                const originalBorder = targetElement.style.border;
                const originalBoxShadow = targetElement.style.boxShadow;
                const originalOutline = targetElement.style.outline;
                
                targetElement.style.border = '3px solid #ff6b6b';
                targetElement.style.boxShadow = '0 0 20px rgba(255, 107, 107, 0.6)';
                targetElement.style.outline = '3px solid rgba(255, 107, 107, 0.3)';
                targetElement.style.outlineOffset = '3px';
                
                setTimeout(() => {
                    targetElement.style.border = originalBorder;
                    targetElement.style.boxShadow = originalBoxShadow;
                    targetElement.style.outline = originalOutline;
                    targetElement.style.outlineOffset = '';
                }, 5000);
                
                // Feedback visual
                WallyMonitor.Utils.showNotification('✓ Elemento localizado e destacado', 'success');
            } else {
                WallyMonitor.Utils.showNotification('⚠ Elemento não encontrado na página atual', 'warning');
            }
        } catch (error) {
            console.error('Erro ao destacar elemento:', error);
            WallyMonitor.Utils.showNotification('✗ Erro ao localizar elemento', 'error');
        }
    };

    /**
     * Salva o relatório no backend para exportação
     * @param {Object} report - Relatório processado
     */
    WallyMonitor.UI.saveReport = function(report) {
        $.post(wallyData.ajax_url, {
            action: 'wally_save_full_report',
            nonce: wallyData.nonce,
            report: JSON.stringify(report)
        });
    };

})(jQuery);
