(function($) {
    'use strict';

    var ps = window.seoFuryPageSpeed || {};

    // Audit titles/savings come from the PageSpeed API (third-party); escape
    // before injecting as HTML.
    function escapeHtml(str) {
        return String(str == null ? '' : str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function getScoreColor(score) {
        if (score >= 90) return '#22C55E';
        if (score >= 50) return '#F59E0B';
        return '#EF4444';
    }

    function getScoreLabel(score) {
        if (score >= 90) return ps.i18n.good || 'Good';
        if (score >= 50) return ps.i18n.needsImprovement || 'Needs Improvement';
        return ps.i18n.poor || 'Poor';
    }

    function getScoreBadgeClass(score) {
        if (score >= 90) return 'sf-score-good';
        if (score >= 50) return 'sf-score-avg';
        return 'sf-score-bad';
    }

    function getMetricColor(score) {
        if (score >= 0.9) return '#22C55E';
        if (score >= 0.5) return '#F59E0B';
        return '#EF4444';
    }

    function animateGauge(circleId, scoreId, labelId, score, circleRadius) {
        var $circle = $(circleId);
        var $score = $(scoreId);
        if (!$circle.length || !$score.length) return;

        var r = circleRadius || 54;
        var circumference = 2 * Math.PI * r;
        var offset = circumference - (score / 100) * circumference;
        var color = getScoreColor(score);

        $circle.css({
            'stroke-dasharray': circumference,
            'stroke-dashoffset': circumference,
            'stroke': color,
            'transition': 'stroke-dashoffset 1s ease-out'
        });

        setTimeout(function() {
            $circle.css('stroke-dashoffset', offset);
        }, 50);

        $({ val: 0 }).animate({ val: score }, {
            duration: 1000,
            step: function() {
                $score.text(Math.round(this.val));
            },
            complete: function() {
                $score.text(score);
            }
        });

        if (labelId) {
            var $label = $(labelId);
            if ($label.length) {
                $label.text(getScoreLabel(score)).css('color', color);
            }
        }
    }

    function renderMetrics(prefix, metrics) {
        var keys = ['fcp', 'lcp', 'tbt', 'cls', 'si', 'tti'];
        keys.forEach(function(key) {
            var m = metrics[key];
            if (!m) return;
            var $card = $(prefix + key);
            if (!$card.length) return;
            var color = getMetricColor(m.score);
            $card.find('.sf-metric-value').text(m.display).css('color', color);
            $card.css('border-left-color', color);
        });
    }

    function renderOpportunities(data) {
        var $wrap = $('#sf-speed-opportunities');
        var $list = $('#sf-speed-opp-list');
        if (!$wrap.length || !$list.length) return;
        $list.empty();

        if (!data.opportunities || data.opportunities.length === 0) {
            $wrap.hide();
            return;
        }

        $wrap.show();
        data.opportunities.forEach(function(opp) {
            var color = getMetricColor(opp.score);
            var html = '<div style="display:flex;align-items:center;gap:10px;padding:10px 0;border-bottom:1px solid #F1F5F9;">';
            html += '<div style="width:4px;height:30px;border-radius:2px;background:' + color + ';"></div>';
            html += '<div style="flex:1;"><strong>' + escapeHtml(opp.title) + '</strong>';
            if (opp.savings) {
                html += ' <span style="color:#94A3B8;font-size:12px;">(' + (ps.i18n.savings || 'save') + ' ' + escapeHtml(opp.savings) + ')</span>';
            }
            html += '</div></div>';
            $list.append(html);
        });
    }

    // Save result persistently
    function saveResult(postId, url, strategy, score, data) {
        // Strip large data to keep post_meta small
        var saveData = {
            score: score,
            strategy: strategy,
            checked_at: data.checked_at || ''
        };
        $.ajax({
            url: ps.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_fury_page_speed_save_result',
                nonce: ps.nonce,
                post_id: postId || 0,
                url: url || '',
                strategy: strategy,
                score: score,
                result: JSON.stringify(saveData)
            }
        });
    }

    // Strategy toggle
    $(document).on('click', '.sf-speed-strategy', function() {
        $('.sf-speed-strategy').removeClass('active').css({ background: '#fff', color: '#334155' });
        $(this).addClass('active').css({ background: '#3B82F6', color: '#fff' });
    });

    // Main check button
    $('#sf-speed-check-btn').on('click', function() {
        var url = $('#sf-speed-url').val();
        var strategy = $('.sf-speed-strategy.active').data('strategy') || 'mobile';

        if (!url) return;

        var $btn = $(this);
        $btn.prop('disabled', true);
        $('#sf-speed-results').hide();
        $('#sf-speed-loading').show();

        $.ajax({
            url: ps.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_fury_page_speed_check',
                nonce: ps.nonce,
                url: url,
                strategy: strategy
            },
            success: function(response) {
                $('#sf-speed-loading').hide();
                if (response.success) {
                    var d = response.data;
                    animateGauge('#sf-speed-circle', '#sf-speed-score', '#sf-speed-label', d.score, 54);
                    renderMetrics('#sf-metric-', d.metrics);
                    renderOpportunities(d);

                    var timeText = d.checked_at;
                    if (d.cached) timeText += ' (' + (ps.i18n.cached || 'cached') + ')';
                    $('#sf-speed-checked-at').text((ps.i18n.lastCheck || 'Last check') + ': ' + timeText);

                    $('#sf-speed-results').show();

                    // Always save result persistently
                    saveResult(0, url, strategy, d.score, d);
                } else {
                    alert(response.data.message);
                }
            },
            error: function() {
                $('#sf-speed-loading').hide();
                alert(ps.i18n.networkError || 'Network error');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // Overview batch check
    $(document).on('click', '.sf-overview-check-btn', function() {
        var $btn = $(this);
        var postId = $btn.data('post-id');
        var $row = $btn.closest('tr');

        $btn.prop('disabled', true).text(ps.i18n.checking || '...');

        var now = new Date();
        var timeStr = now.getFullYear() + '-' +
            String(now.getMonth()+1).padStart(2,'0') + '-' +
            String(now.getDate()).padStart(2,'0') + ' ' +
            String(now.getHours()).padStart(2,'0') + ':' +
            String(now.getMinutes()).padStart(2,'0');

        // Check mobile
        $.ajax({
            url: ps.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_fury_page_speed_batch',
                nonce: ps.nonce,
                post_id: postId,
                strategy: 'mobile'
            },
            success: function(response) {
                if (response.success) {
                    var cls = getScoreBadgeClass(response.data.score);
                    $row.find('.sf-overview-mobile').html('<span class="sf-score-badge ' + cls + '">' + response.data.score + '</span>');
                    // Always save persistently (even if cached from transient)
                    saveResult(postId, '', 'mobile', response.data.score, response.data);
                    // Update last check column
                    $row.find('.sf-overview-last-check').html('<small style="color:#64748B;">' + (response.data.checked_at || timeStr) + '</small>');
                } else {
                    $row.find('.sf-overview-mobile').html('<span class="sf-score-badge sf-score-bad">!</span>');
                }
            }
        });

        // Check desktop
        $.ajax({
            url: ps.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_fury_page_speed_batch',
                nonce: ps.nonce,
                post_id: postId,
                strategy: 'desktop'
            },
            success: function(response) {
                if (response.success) {
                    var cls = getScoreBadgeClass(response.data.score);
                    $row.find('.sf-overview-desktop').html('<span class="sf-score-badge ' + cls + '">' + response.data.score + '</span>');
                    // Always save persistently (even if cached from transient)
                    saveResult(postId, '', 'desktop', response.data.score, response.data);
                    // Update last check column
                    $row.find('.sf-overview-last-check').html('<small style="color:#64748B;">' + (response.data.checked_at || timeStr) + '</small>');
                } else {
                    $row.find('.sf-overview-desktop').html('<span class="sf-score-badge sf-score-bad">!</span>');
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text(ps.i18n.checkBtn || 'Check');
            }
        });
    });

    // Save API Key
    $('#sf-speed-save-key').on('click', function() {
        var $btn = $(this);
        var apiKey = $('#sf-speed-api-key').val();
        $btn.prop('disabled', true);
        $('#sf-speed-key-status').text('...').css('color', '#64748B');

        $.ajax({
            url: ps.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_fury_page_speed_save_key',
                nonce: ps.nonce,
                api_key: apiKey
            },
            success: function(response) {
                if (response.success) {
                    $('#sf-speed-key-status').text('✓').css('color', '#22C55E');
                } else {
                    $('#sf-speed-key-status').text(response.data.message).css('color', '#EF4444');
                }
            },
            error: function() {
                $('#sf-speed-key-status').text(ps.i18n.networkError || 'Network error').css('color', '#EF4444');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // Post meta speed check
    $(document).on('click', '.sf-meta-speed-check', function() {
        var $btn = $(this);
        var strategy = $btn.data('strategy');
        var url = $btn.data('url');

        $('.sf-meta-speed-check').prop('disabled', true);
        $('#sf-meta-speed-results, #sf-meta-speed-error').hide();
        $('#sf-meta-speed-loading').show();

        $.ajax({
            url: ps.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_fury_page_speed_check',
                nonce: ps.nonce,
                url: url,
                strategy: strategy
            },
            success: function(response) {
                $('#sf-meta-speed-loading').hide();
                if (response.success) {
                    var d = response.data;
                    animateGauge('#sf-meta-circle', '#sf-meta-score', null, d.score, 36);

                    $('#sf-meta-fcp').text(d.metrics.fcp.display).css('color', getMetricColor(d.metrics.fcp.score));
                    $('#sf-meta-lcp').text(d.metrics.lcp.display).css('color', getMetricColor(d.metrics.lcp.score));
                    $('#sf-meta-tbt').text(d.metrics.tbt.display).css('color', getMetricColor(d.metrics.tbt.score));
                    $('#sf-meta-cls').text(d.metrics.cls.display).css('color', getMetricColor(d.metrics.cls.score));

                    // Opportunities
                    var $opps = $('#sf-meta-speed-opps');
                    $opps.empty();
                    if (d.opportunities && d.opportunities.length > 0) {
                        var html = '<strong style="font-size:12px;">' + (ps.i18n.opportunities || 'Opportunities') + ':</strong><ul style="margin:4px 0 0;padding-left:16px;">';
                        d.opportunities.slice(0, 5).forEach(function(opp) {
                            html += '<li style="color:' + getMetricColor(opp.score) + ';">' + escapeHtml(opp.title);
                            if (opp.savings) html += ' <span style="color:#94A3B8;">(' + escapeHtml(opp.savings) + ')</span>';
                            html += '</li>';
                        });
                        html += '</ul>';
                        $opps.html(html);
                    }

                    $('#sf-meta-speed-results').show();

                    // Save result for this post and update history
                    if (ps.post_id) {
                        saveResult(ps.post_id, url, strategy, d.score, d);

                        // Prepend row to history table
                        var $historyBody = $('#sf-meta-speed-history tbody');
                        if ($historyBody.length) {
                            var icon = strategy === 'mobile' ? 'smartphone' : 'desktop';
                            var scoreColor = d.score >= 90 ? '#22C55E' : (d.score >= 50 ? '#F59E0B' : '#EF4444');
                            var row = '<tr style="border-bottom:1px solid #F1F5F9;">';
                            row += '<td style="padding:4px 6px;color:#475569;">' + (d.checked_at || new Date().toISOString().slice(0,16).replace('T',' ')) + '</td>';
                            row += '<td style="text-align:center;padding:4px 6px;"><span class="dashicons dashicons-' + icon + '" style="font-size:14px;width:14px;height:14px;color:#64748B;"></span></td>';
                            row += '<td style="text-align:center;padding:4px 6px;"><span style="color:' + scoreColor + ';font-weight:700;">' + d.score + '</span></td>';
                            row += '</tr>';
                            $historyBody.prepend(row);
                            // Keep max 10 rows
                            while ($historyBody.children('tr').length > 10) {
                                $historyBody.children('tr:last').remove();
                            }
                            $('#sf-meta-speed-history').show();
                        } else {
                            // No history table yet — create it
                            var icon = strategy === 'mobile' ? 'smartphone' : 'desktop';
                            var scoreColor = d.score >= 90 ? '#22C55E' : (d.score >= 50 ? '#F59E0B' : '#EF4444');
                            var histHtml = '<div id="sf-meta-speed-history" style="margin-top:16px;border-top:1px solid #E2E8F0;padding-top:12px;">';
                            histHtml += '<h5 style="margin:0 0 8px;font-size:12px;font-weight:600;color:#475569;">' + (ps.i18n.speedHistory || 'Speed History') + '</h5>';
                            histHtml += '<table style="width:100%;font-size:11px;border-collapse:collapse;">';
                            histHtml += '<thead><tr style="border-bottom:1px solid #E2E8F0;"><th style="text-align:left;padding:4px 6px;color:#64748B;font-weight:600;">' + (ps.i18n.date || 'Date') + '</th><th style="text-align:center;padding:4px 6px;color:#64748B;font-weight:600;">' + (ps.i18n.device || 'Device') + '</th><th style="text-align:center;padding:4px 6px;color:#64748B;font-weight:600;">' + (ps.i18n.score || 'Score') + '</th></tr></thead>';
                            histHtml += '<tbody>';
                            histHtml += '<tr style="border-bottom:1px solid #F1F5F9;"><td style="padding:4px 6px;color:#475569;">' + (d.checked_at || 'Just now') + '</td>';
                            histHtml += '<td style="text-align:center;padding:4px 6px;"><span class="dashicons dashicons-' + icon + '" style="font-size:14px;width:14px;height:14px;color:#64748B;"></span></td>';
                            histHtml += '<td style="text-align:center;padding:4px 6px;"><span style="color:' + scoreColor + ';font-weight:700;">' + d.score + '</span></td></tr>';
                            histHtml += '</tbody></table></div>';
                            $('.seo-fury-speed-meta-wrap').append(histHtml);
                        }
                    }
                } else {
                    $('#sf-meta-speed-error').text(response.data.message).show();
                }
            },
            error: function() {
                $('#sf-meta-speed-loading').hide();
                $('#sf-meta-speed-error').text(ps.i18n.networkError || 'Network error').show();
            },
            complete: function() {
                $('.sf-meta-speed-check').prop('disabled', false);
            }
        });
    });

})(jQuery);
