/**
 * @file wally-stats.js
 * @description Statistics collection for Wally Monitor — collectPageStats,
 *              collectElementStats, aggregateStats.
 * @module WallyMonitor.Stats
 */
window.WallyMonitor = window.WallyMonitor || {};

(function($) {
    'use strict';

    WallyMonitor.Stats = WallyMonitor.Stats || {};

    /**
     * Coleta estatísticas de acessibilidade de uma página
     * @param {Document} doc - Documento da página (iframe)
     * @returns {Object} Estatísticas coletadas
     */
    WallyMonitor.Stats.collectPageStats = function(doc) {
        if (!doc || typeof doc.querySelectorAll !== 'function') {
            console.warn('collectPageStats: documento inválido recebido');
            return {
                totalImages: 0, imagesWithAlt: 0,
                totalLinks: 0, linksWithText: 0,
                totalButtons: 0, buttonsWithLabel: 0,
                totalFormFields: 0, formFieldsWithLabel: 0,
                totalHeadings: 0, headingsCorrect: 0,
                totalTables: 0, tablesAccessible: 0,
                totalVideos: 0, videosWithCaptions: 0
            };
        }

        const stats = {
            totalImages: 0, imagesWithAlt: 0,
            totalLinks: 0, linksWithText: 0,
            totalButtons: 0, buttonsWithLabel: 0,
            totalFormFields: 0, formFieldsWithLabel: 0,
            totalHeadings: 0, headingsCorrect: 0,
            totalTables: 0, tablesAccessible: 0,
            totalVideos: 0, videosWithCaptions: 0
        };

        try {
            // Imagens
            const images = doc.querySelectorAll('img');
            stats.totalImages = images.length;
            images.forEach(img => {
                const alt = img.getAttribute('alt');
                if (alt !== null && alt.trim() !== '') {
                    stats.imagesWithAlt++;
                }
            });

            // Links
            const links = doc.querySelectorAll('a[href]');
            stats.totalLinks = links.length;
            links.forEach(link => {
                const text = link.textContent.trim();
                const ariaLabel = link.getAttribute('aria-label');
                if (text || ariaLabel) {
                    stats.linksWithText++;
                }
            });

            // Botões
            const buttons = doc.querySelectorAll('button, input[type="button"], input[type="submit"], [role="button"]');
            stats.totalButtons = buttons.length;
            buttons.forEach(btn => {
                const text = btn.textContent.trim();
                const ariaLabel = btn.getAttribute('aria-label');
                const value = btn.getAttribute('value');
                if (text || ariaLabel || value) {
                    stats.buttonsWithLabel++;
                }
            });

            // Campos de formulário
            const formFields = doc.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]), textarea, select');
            stats.totalFormFields = formFields.length;
            formFields.forEach(field => {
                const id = field.getAttribute('id');
                const ariaLabel = field.getAttribute('aria-label');
                const ariaLabelledby = field.getAttribute('aria-labelledby');
                const hasLabel = id && doc.querySelector(`label[for="${id}"]`);
                if (hasLabel || ariaLabel || ariaLabelledby) {
                    stats.formFieldsWithLabel++;
                }
            });

            // Headings (verificação simples de ordem)
            const headings = Array.from(doc.querySelectorAll('h1, h2, h3, h4, h5, h6'));
            stats.totalHeadings = headings.length;
            let lastLevel = 0;
            let correctOrder = true;
            headings.forEach(h => {
                const level = parseInt(h.tagName.substring(1));
                if (level > lastLevel + 1) {
                    correctOrder = false;
                }
                lastLevel = level;
            });
            if (correctOrder) {
                stats.headingsCorrect = headings.length;
            }

            // Tabelas
            const tables = doc.querySelectorAll('table');
            stats.totalTables = tables.length;
            tables.forEach(table => {
                const hasHeaders = table.querySelectorAll('th').length > 0;
                const hasCaption = table.querySelector('caption') !== null;
                if (hasHeaders || hasCaption) {
                    stats.tablesAccessible++;
                }
            });

            // Vídeos
            const videos = doc.querySelectorAll('video, iframe[src*="youtube"], iframe[src*="vimeo"]');
            stats.totalVideos = videos.length;
            videos.forEach(video => {
                const hasTrack = video.tagName === 'VIDEO' && video.querySelector('track') !== null;
                const hasTitle = video.getAttribute('title') !== null;
                if (hasTrack || hasTitle) {
                    stats.videosWithCaptions++;
                }
            });

        } catch (error) {
            console.warn('Erro ao coletar estatísticas da página:', error);
        }

        return stats;
    };

    /**
     * Coleta estatísticas de elementos testados e corretos
     * @param {Document} document - Documento a analisar
     * @param {Object} stats - Objeto de estatísticas a preencher
     * @param {Array} violations - Array de violações encontradas
     */
    WallyMonitor.Stats.collectElementStats = function(document, stats, violations) {
        if (!document || typeof document.querySelectorAll !== 'function') {
            return; // Retorna sem fazer nada se document for inválido
        }
        
        // Conta imagens
        const images = document.querySelectorAll('img');
        stats.totalImages = images.length;
        images.forEach(img => {
            const alt = img.getAttribute('alt');
            if (alt !== null && alt.trim() !== '') {
                stats.imagesWithAlt++;
            }
        });

        // Conta links
        const links = document.querySelectorAll('a');
        stats.totalLinks = links.length;
        links.forEach(link => {
            const hasText = link.textContent.trim().length > 0;
            const hasAriaLabel = link.getAttribute('aria-label');
            const hasImage = link.querySelector('img');
            if (hasText || hasAriaLabel || hasImage) {
                stats.linksWithText++;
            }
        });

        // Conta botões
        const buttons = document.querySelectorAll('button, input[type="submit"], input[type="button"], .wp-block-button__link');
        stats.totalButtons = buttons.length;
        buttons.forEach(btn => {
            const hasText = btn.textContent.trim().length > 0;
            const hasAriaLabel = btn.getAttribute('aria-label');
            const hasValue = btn.getAttribute('value');
            if (hasText || hasAriaLabel || hasValue) {
                stats.buttonsWithLabel++;
            }
        });

        // Conta campos de formulário
        const formFields = document.querySelectorAll('input:not([type="submit"]):not([type="button"]):not([type="hidden"]), textarea, select');
        stats.totalFormFields = formFields.length;
        formFields.forEach(field => {
            const id = field.getAttribute('id');
            const hasLabel = id && document.querySelector(`label[for="${id}"]`);
            const inLabel = field.closest('label');
            const hasAriaLabel = field.getAttribute('aria-label') || field.getAttribute('aria-labelledby');
            if (hasLabel || inLabel || hasAriaLabel) {
                stats.formFieldsWithLabel++;
            }
        });

        // Conta headings (verifica hierarquia)
        const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
        stats.totalHeadings = headings.length;
        let previousLevel = 0;
        let headingsCorrectCount = 0;
        headings.forEach(heading => {
            const currentLevel = parseInt(heading.tagName.substring(1));
            if (previousLevel === 0 || currentLevel <= previousLevel + 1) {
                headingsCorrectCount++;
            }
            previousLevel = currentLevel;
        });
        stats.headingsCorrect = headingsCorrectCount;

        // Conta tabelas
        const tables = document.querySelectorAll('table');
        stats.totalTables = tables.length;
        tables.forEach(table => {
            const hasHeaders = table.querySelectorAll('th').length > 0;
            const hasCaption = table.querySelector('caption');
            if (hasHeaders || hasCaption) {
                stats.tablesAccessible++;
            }
        });

        // Conta vídeos
        const videos = document.querySelectorAll('video, .wp-block-video');
        stats.totalVideos = videos.length;
        videos.forEach(video => {
            const videoElement = video.tagName === 'VIDEO' ? video : video.querySelector('video');
            if (videoElement) {
                const hasTrack = videoElement.querySelector('track[kind="captions"], track[kind="subtitles"]');
                if (hasTrack) {
                    stats.videosWithCaptions++;
                }
            }
        });
    };

    /**
     * Agrega estatísticas de múltiplas páginas
     * @param {Object} allStats - Objeto com estatísticas agregadas
     * @param {Object} pageStats - Estatísticas de uma página
     */
    WallyMonitor.Stats.aggregateStats = function(allStats, pageStats) {
        if (!allStats || !pageStats) {
            return;
        }

        allStats.totalImages += pageStats.totalImages || 0;
        allStats.imagesWithAlt += pageStats.imagesWithAlt || 0;
        allStats.totalLinks += pageStats.totalLinks || 0;
        allStats.linksWithText += pageStats.linksWithText || 0;
        allStats.totalButtons += pageStats.totalButtons || 0;
        allStats.buttonsWithLabel += pageStats.buttonsWithLabel || 0;
        allStats.totalFormFields += pageStats.totalFormFields || 0;
        allStats.formFieldsWithLabel += pageStats.formFieldsWithLabel || 0;
        allStats.totalHeadings += pageStats.totalHeadings || 0;
        allStats.headingsCorrect += pageStats.headingsCorrect || 0;
        allStats.totalTables += pageStats.totalTables || 0;
        allStats.tablesAccessible += pageStats.tablesAccessible || 0;
        allStats.totalVideos += pageStats.totalVideos || 0;
        allStats.videosWithCaptions += pageStats.videosWithCaptions || 0;
    };

})(jQuery);
