/**
 * ================================================================
 * DRIPBOX LINK CHECKER - ADMIN JAVASCRIPT (FINAL v3)
 * Inclui: Scan, Filtros Modernos e Automação
 * ================================================================
 */

(function($) {
    'use strict';
    
    // State
    let scanning = false;
    let allLinks = [];
    let currentIndex = 0;
    let results = [];
    let startTime = 0;
    
    // DOM Elements
    const $startBtn = $('#dbx-start-scan');
    const $clearBtn = $('#dbx-clear-results');
    const $progressContainer = $('#dbx-progress-container');
    const $progressText = $('#dbx-progress-text');
    const $progressCount = $('#dbx-progress-count');
    const $progressFill = $('#dbx-progress-fill');
    const $resultsContainer = $('#dbx-results-container');
    
    // Stats counters
    const $totalLinks = $('#dbx-total-links');
    const $brokenCount = $('#dbx-broken-count');
    const $riskyCount = $('#dbx-risky-count');
    const $okCount = $('#dbx-ok-count');
    
    /**
     * Start Scan
     */
    $startBtn.on('click', function() {
        if (scanning) return;
        
        if (!confirm('This will scan all affiliate links on your site. Continue?')) {
            return;
        }
        
        startScan();
    });
    
    function startScan() {
        scanning = true;
        currentIndex = 0;
        results = [];
        startTime = Date.now();
        
        $startBtn.prop('disabled', true).html('<span class="dashicons dashicons-update"></span> Scanning...');
        $progressContainer.show();
        // Modern Empty State durante o scan
        $resultsContainer.html('<div class="dbx-empty-state-modern"><div class="empty-icon">⏳</div><h2>Scanning in progress...</h2></div>');
        
        $.ajax({
            url: dripboxLinkChecker.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_start_scan',
                nonce: dripboxLinkChecker.nonce
            },
            success: function(response) {
                if (response.success) {
                    allLinks = response.data.links;
                    
                    if (allLinks.length === 0) {
                        alert('No affiliate links found on your site.');
                        resetUI();
                        return;
                    }
                    
                    $progressText.text('Checking links...');
                    $progressCount.text('0 / ' + allLinks.length);
                    checkNextLink();
                } else {
                    alert('Error: ' + (response.data.message || 'Failed to start scan'));
                    resetUI();
                }
            },
            error: function() {
                alert('Connection error. Please try again.');
                resetUI();
            }
        });
    }
    
    function checkNextLink() {
        if (currentIndex >= allLinks.length) {
            finishScan();
            return;
        }
        
        const link = allLinks[currentIndex];
        const progress = Math.round((currentIndex / allLinks.length) * 100);
        $progressFill.css('width', progress + '%');
        $progressCount.text((currentIndex + 1) + ' / ' + allLinks.length);
        
        $.ajax({
            url: dripboxLinkChecker.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_check_link',
                nonce: dripboxLinkChecker.nonce,
                url: link.url,
                post_id: link.post_id,
                post_title: link.post_title,
                post_url: link.post_url
            },
            success: function(response) {
                if (response.success) {
                    results.push(response.data);
                } else {
                    results.push({
                        url: link.url,
                        post_id: link.post_id,
                        post_title: link.post_title,
                        post_url: link.post_url,
                        status: 'broken',
                        label: 'Check failed: ' + (response.data.message || 'Unknown error'),
                        http_code: 0
                    });
                }
                
                currentIndex++;
                setTimeout(checkNextLink, 200);
            },
            error: function() {
                results.push({
                    url: link.url,
                    post_id: link.post_id,
                    post_title: link.post_title,
                    post_url: link.post_url,
                    status: 'broken',
                    label: 'Connection error',
                    http_code: 0
                });
                
                currentIndex++;
                setTimeout(checkNextLink, 200);
            }
        });
    }
    
    function finishScan() {
        const duration = Math.round((Date.now() - startTime) / 1000);
        
        $.ajax({
            url: dripboxLinkChecker.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_save_results',
                nonce: dripboxLinkChecker.nonce,
                results: JSON.stringify(results),
                duration: duration
            },
            success: function() {
                location.reload();
            }
        });
    }
    
    function resetUI() {
        scanning = false;
        $startBtn.prop('disabled', false).html('<span class="dashicons dashicons-update"></span> Scan All Links');
        $progressContainer.hide();
    }
    
    /**
     * Clear Results
     */
    $clearBtn.on('click', function() {
        if (!confirm('This will delete all scan results. Continue?')) {
            return;
        }
        
        $.ajax({
            url: dripboxLinkChecker.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_clear_results',
                nonce: dripboxLinkChecker.nonce
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Error clearing results');
                }
            }
        });
    });
    
    /**
     * Filter tabs (LÓGICA NOVA INTEGRADA)
     */
    $(document).on('click', '.dbx-tab', function() {
        const filter = $(this).data('filter');
        
        // UI das abas
        $('.dbx-tab').removeClass('active');
        $(this).addClass('active');
        
        // Lógica de esconder/mostrar linhas
        if (filter === 'all') {
            $('.dbx-link-row').removeClass('dbx-hidden');
        } else {
            $('.dbx-link-row').each(function() {
                const status = $(this).data('status');
                if (status === filter) {
                    $(this).removeClass('dbx-hidden');
                } else {
                    $(this).addClass('dbx-hidden');
                }
            });
        }
    });

    /**
     * Recheck single link (ATUALIZADO PARA O NOVO HTML)
     */
    $(document).on('click', '.dbx-recheck-link', function() {
        const $btn = $(this);
        const $row = $btn.closest('.dbx-link-row'); 
        const url = $btn.data('url');
        
        // Get OLD status before recheck
        const oldStatus = $row.attr('data-status');
        
        // Busca dados no novo layout (divs e classes)
        const editLink = $row.find('.post-line a[href*="post.php"]').attr('href');
        const postIdMatch = editLink ? editLink.match(/post=(\d+)/) : null;
        const postId = postIdMatch ? postIdMatch[1] : 0;
        
        const postTitle = $row.find('.post-line a:first').text().trim();
        const postUrl = $row.find('.post-line a:first').attr('href');
        
        $btn.prop('disabled', true).text('Checking...');
        
        $.ajax({
            url: dripboxLinkChecker.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_recheck_single',
                nonce: dripboxLinkChecker.nonce,
                url: url,
                post_id: postId,
                post_title: postTitle,
                post_url: postUrl
            },
            success: function(response) {
                if (response.success) {
                    const result = response.data;
                    
                    // Update URL display
                    const displayUrl = truncateUrl(result.url);
                    $row.find('.main-link').attr('href', result.url).text(displayUrl);
                    
                    // Update Status Icon
                    let statusIcon = '';
                    if (result.status === 'ok') {
                        statusIcon = '<div class="status-dot dot-green"></div>';
                    } else if (result.status === 'broken') {
                        statusIcon = '<div class="status-dot dot-red"><span class="dashicons dashicons-no"></span></div>';
                    } else {
                        statusIcon = '<div class="status-dot dot-orange"><span class="dashicons dashicons-warning"></span></div>';
                    }
                    $row.find('.col-status').html(statusIcon);
                    
                    // Update status class
                    $row.removeClass('dbx-row-ok dbx-row-broken dbx-row-risky')
                        .addClass('dbx-row-' + result.status)
                        .attr('data-status', result.status);
                    
                    // Update Label Pill
                    const pillClass = 'pill-' + result.status;
                    $row.find('.col-details').html(
                        '<span class="status-pill ' + pillClass + '">' + result.label + '</span>'
                    );
                    
                    // Update HTTP code
                    $row.find('.http-badge').text(result.http_code);
                    
                    // Update numbers
                    updateCardsAfterRecheck(result.status, oldStatus);
                    
                    let message = 'Link rechecked! Status: ' + result.status;
                    if (result.url_changed) {
                        message += '\n\nURL was updated in the product.';
                    }
                } else {
                    alert('Error: ' + (response.data.message || 'Check failed'));
                }
                $btn.prop('disabled', false).text('Recheck');
            },
            error: function() {
                alert('Connection error');
                $btn.prop('disabled', false).text('Recheck');
            }
        });
    });

    /**
     * === NOVA PARTE: HANDLE AUTOMATION TOGGLES ===
     */
    $('#dbx-toggle-scan, #dbx-toggle-email').on('change', function() {
        const $toggle = $(this);
        const setting = $toggle.attr('id') === 'dbx-toggle-scan' ? 'scan' : 'email';
        const value = $toggle.is(':checked') ? 1 : 0;
        const $parent = $toggle.closest('.dbx-switch');
        
        $parent.addClass('loading');
        
        $.ajax({
            url: dripboxLinkChecker.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_save_automation_settings',
                nonce: dripboxLinkChecker.nonce,
                setting: setting,
                value: value
            },
            success: function(response) {
                $parent.removeClass('loading');
                if (!response.success) {
                    // Reverte se der erro
                    $toggle.prop('checked', !value);
                    alert('Error saving settings.');
                }
            },
            error: function() {
                $parent.removeClass('loading');
                $toggle.prop('checked', !value);
                alert('Connection error.');
            }
        });
    });

    /**
     * Helpers
     */
    function updateCardsAfterRecheck(newStatus, oldStatus) {
        if (newStatus === oldStatus) return;

        let totalLinks = parseInt($totalLinks.text()) || 0;
        let brokenCount = parseInt($brokenCount.text()) || 0;
        let riskyCount = parseInt($riskyCount.text()) || 0;
        let okCount = parseInt($okCount.text()) || 0;
        
        if (oldStatus === 'broken') brokenCount = Math.max(0, brokenCount - 1);
        else if (oldStatus === 'risky') riskyCount = Math.max(0, riskyCount - 1);
        else if (oldStatus === 'ok') okCount = Math.max(0, okCount - 1);
        
        if (newStatus === 'broken') brokenCount++;
        else if (newStatus === 'risky') riskyCount++;
        else if (newStatus === 'ok') okCount++;
        
        $brokenCount.text(brokenCount);
        $riskyCount.text(riskyCount);
        $okCount.text(okCount);
        
        $('.dbx-tab[data-filter="all"] .badge').text(totalLinks);
        $('.dbx-tab[data-filter="broken"] .badge').text(brokenCount);
        $('.dbx-tab[data-filter="risky"] .badge').text(riskyCount);
        $('.dbx-tab[data-filter="ok"] .badge').text(okCount);
    }

    function truncateUrl(url, length) {
        length = length || 60;
        if (url.length <= length) return url;
        return url.substr(0, length) + '...';
    }

})(jQuery);