/**
 * Consolety Diagnostics
 *
 * @package Consolety
 */

/* global jQuery, consoletyDiagnostics */

(function($) {
    'use strict';

    var VP = consoletyDiagnostics;
    var lastDiagData = null;

    function escapeHtml(text) {
        if (!text && text !== 0) return '';
        var div = document.createElement('div');
        div.textContent = String(text);
        return div.innerHTML;
    }

    function badge(status, text) {
        var cls = status === 'ok' ? 'vp-diag-badge-ok' :
                  status === 'warn' ? 'vp-diag-badge-warn' : 'vp-diag-badge-fail';
        return '<span class="vp-diag-badge ' + cls + '">' + escapeHtml(text) + '</span>';
    }

    function row(label, value) {
        return '<tr><td>' + escapeHtml(label) + '</td><td>' + value + '</td></tr>';
    }

    function runDiagnostics() {
        var $container = $('#diagnostics-results');
        $container.html(
            '<div class="vp-loading-state">' +
            '<span class="spinner is-active"></span> ' +
            escapeHtml(VP.i18n.running) +
            '</div>'
        );

        $.post(VP.ajaxUrl, {
            action: 'consolety_run_diagnostics',
            nonce: VP.nonce
        }, function(response) {
            if (!response || !response.success) {
                $container.html('<p style="color:var(--vp-danger);">' + escapeHtml(VP.i18n.failed) + '</p>');
                return;
            }

            var d = response.data;
            lastDiagData = d;
            var html = '<table class="vp-diag-table">';

            // Token
            html += row('Token Present', d.token_present
                ? badge('ok', 'Yes')
                : badge('fail', 'No - Not connected'));

            // Hub reachable
            html += row('Hub Reachable', d.hub_reachable
                ? badge('ok', 'Yes (' + d.hub_latency_ms + 'ms)')
                : badge('fail', 'No' + (d.hub_error ? ' - ' + escapeHtml(d.hub_error) : '')));

            // Last heartbeat
            html += row('Last Heartbeat', escapeHtml(d.last_heartbeat || 'Never'));

            // Tier comparison
            var tierHtml = escapeHtml('Hub: ' + d.hub_tier + ' | Freemius: ' + d.freemius_tier);
            if (d.tier_mismatch) {
                tierHtml += ' ' + badge('warn', 'MISMATCH');
            } else if (d.hub_tier !== 'unknown') {
                tierHtml += ' ' + badge('ok', 'Match');
            }
            html += row('Tier Status', tierHtml);

            // Connection valid
            html += row('Connection Valid', d.connection_invalid
                ? badge('fail', 'Invalid')
                : badge('ok', 'OK'));

            // Credits + Site ID
            html += row('Credits', escapeHtml(d.credits));
            html += row('Site ID', escapeHtml(d.site_id));

            // Versions
            html += row('Plugin Version', escapeHtml(d.plugin_version));
            html += row('WordPress', escapeHtml(d.wp_version));
            html += row('PHP', escapeHtml(d.php_version));

            // Deployment integrity
            html += row('Plugin File Hash', escapeHtml(d.plugin_file_hash || 'N/A'));
            html += row('Freemius SDK', d.freemius_loaded
                ? badge('ok', 'Loaded')
                : badge('warn', 'Not loaded'));
            html += row('Menu Slugs', escapeHtml((d.active_menu_slugs || []).join(', ') || 'None'));

            // Last API error
            if (d.last_api_error) {
                html += row('Last API Error', '<span style="color:var(--vp-warning);">' + escapeHtml(d.last_api_error) + '</span>');
            }

            html += '</table>';
            $container.html(html);

        }).fail(function() {
            $container.html('<p style="color:var(--vp-danger);">' + escapeHtml(VP.i18n.connectionError) + '</p>');
        });
    }

    function actionPost(actionName, btnId, successMsg) {
        var $btn = $(btnId);
        var $status = $('#action-status');
        var originalHtml = $btn.html();

        $btn.prop('disabled', true);
        $status.css('color', 'var(--vp-text-muted)').text(VP.i18n.running);

        $.post(VP.ajaxUrl, {
            action: actionName,
            nonce: VP.nonce
        }, function(response) {
            if (response.success) {
                $status.css('color', 'var(--vp-success, #059669)').text(successMsg);
                runDiagnostics();
            } else {
                var err = (response.data && response.data.message) ? response.data.message : VP.i18n.failed;
                $status.css('color', 'var(--vp-danger, #dc2626)').text(err);
            }
        }).fail(function() {
            $status.css('color', 'var(--vp-danger, #dc2626)').text(VP.i18n.connectionError);
        }).always(function() {
            $btn.prop('disabled', false).html(originalHtml);
            setTimeout(function() { $status.text(''); }, 5000);
        });
    }

    // Button handlers
    $('#btn-force-tier-sync').on('click', function() {
        actionPost('consolety_force_tier_sync', '#btn-force-tier-sync', VP.i18n.tierSynced);
    });

    $('#btn-send-heartbeat').on('click', function() {
        actionPost('consolety_send_heartbeat', '#btn-send-heartbeat', VP.i18n.heartbeatSent);
    });

    $('#btn-clear-caches').on('click', function() {
        actionPost('consolety_clear_caches', '#btn-clear-caches', VP.i18n.cachesCleared);
    });

    $('#btn-rerun-diagnostics').on('click', function() {
        runDiagnostics();
    });

    // Copy diagnostics
    $('#btn-copy-diagnostics').on('click', function() {
        if (!lastDiagData) {
            alert('Run diagnostics first.');
            return;
        }
        var d = lastDiagData;
        var text = 'Consolety Diagnostics\n';
        text += '========================\n';
        text += 'Token: ' + (d.token_present ? 'Yes' : 'No') + '\n';
        text += 'Hub Reachable: ' + (d.hub_reachable ? 'Yes (' + d.hub_latency_ms + 'ms)' : 'No') + '\n';
        text += 'Last Heartbeat: ' + (d.last_heartbeat || 'Never') + '\n';
        text += 'Hub Tier: ' + d.hub_tier + '\n';
        text += 'Freemius Tier: ' + d.freemius_tier + '\n';
        text += 'Tier Mismatch: ' + (d.tier_mismatch ? 'YES' : 'No') + '\n';
        text += 'Credits: ' + d.credits + '\n';
        text += 'Site ID: ' + d.site_id + '\n';
        text += 'Plugin: ' + d.plugin_version + '\n';
        text += 'WordPress: ' + d.wp_version + '\n';
        text += 'PHP: ' + d.php_version + '\n';
        if (d.last_api_error) {
            text += 'Last Error: ' + d.last_api_error + '\n';
        }

        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(function() {
                $('#btn-copy-diagnostics').text('Copied!');
                setTimeout(function() {
                    $('#btn-copy-diagnostics').html('<span class="dashicons dashicons-admin-page"></span> Copy to Clipboard');
                }, 2000);
            });
        }
    });

    // Auto-run on page load
    runDiagnostics();

})(jQuery);
