/**
 * SiteStaffr Diagnostics Page JavaScript
 *
 * Handles token analysis UI interactions for developer diagnostics.
 *
 * @since 0.11.56
 * @package SiteStaffr
 */

jQuery(document).ready(function($) {
    'use strict';

    /**
     * Analyze Tokens button click handler
     */
    $('#analyze-tokens').on('click', function() {
        var callRef = $('#token-callsid').val().trim();

        // Validate Call Reference
        if (!callRef) {
            alert('Please enter a Call Reference');
            return;
        }

        // Accept legacy Call SID (CA...), WebRTC session id (sess_...), or numeric internal call_id.
        var isLegacyCallSid = /^CA[a-f0-9]{32}$/i.test(callRef);
        var isWebrtcSession = /^sess_[A-Za-z0-9]+$/.test(callRef);
        var isNumericCallId = /^\d+$/.test(callRef);
        if (!isLegacyCallSid && !isWebrtcSession && !isNumericCallId) {
            alert('Invalid format. Use legacy Call SID (CA...), WebRTC Session ID (sess_...), or numeric Call ID.');
            return;
        }

        // Hide previous results/errors
        $('#token-metrics-display').hide();
        $('#token-error-display').hide();

        // Show loading indicator
        $('#token-loading').show();

        // Make AJAX request
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sitestaffr_analyze_tokens',
                call_ref: callRef,
                nonce: sitestaffrDiagnostics.nonce
            },
            success: function(response) {
                // Hide loading indicator
                $('#token-loading').hide();

                if (response.success) {
                    displayTokenMetrics(response.data);
                } else {
                    displayError(response.data.message || 'Unknown error occurred');
                }
            },
            error: function(xhr, status, error) {
                // Hide loading indicator
                $('#token-loading').hide();

                console.error('AJAX error:', status, error);
                displayError('AJAX request failed: ' + error);
            }
        });
    });

    /**
     * Display token metrics in the UI
     *
     * @param {Object} data Token metrics data from server
     */
    function displayTokenMetrics(data) {
        // Populate call information
        $('#display-callsid').text(data.session_id || 'N/A');
        $('#display-from-number').text(data.from_number || 'N/A');
        $('#display-duration').text((data.duration || 0) + 's');
        $('#display-started-at').text(data.started_at || 'N/A');
        $('#display-model').text(data.model || 'N/A');

        // Populate operations table
        var tbody = $('#token-operations-body');
        tbody.empty();

        if (data.operations && data.operations.length > 0) {
            $.each(data.operations, function(i, op) {
                var row = '<tr>' +
                    '<td><strong>' + escapeHtml(op.operation_type) + '</strong></td>' +
                    '<td>' + numberFormat(op.prompt_tokens) + '</td>' +
                    '<td>' + numberFormat(op.completion_tokens) + '</td>' +
                    '<td>' + numberFormat(op.cached_tokens || 0) + '</td>' +
                    '<td>' + numberFormat(op.total_tokens) + '</td>' +
                    '<td><code>' + escapeHtml(op.model_used) + '</code></td>' +
                    '<td>' + (op.api_response_time_ms || 0) + 'ms</td>' +
                    '<td><small>' + escapeHtml(op.created_at) + '</small></td>' +
                '</tr>';
                tbody.append(row);
            });
        } else {
            tbody.append('<tr><td colspan="8" style="text-align: center; color: #888;"><em>No token data found for this call</em></td></tr>');
        }

        // Populate totals
        var totals = data.totals || {};

        $('#token-conversation').text(numberFormat(totals.conversation_tokens || 0));
        $('#token-recap').text(numberFormat(totals.recap_tokens || 0));
        $('#token-other').text(numberFormat(totals.other_tokens || 0));

        $('#op-count-conversation').text(totals.operation_count ? totals.operation_count.conversation || 0 : 0);
        $('#op-count-recap').text(totals.operation_count ? totals.operation_count.recap || 0 : 0);
        $('#op-count-other').text(totals.operation_count ? totals.operation_count.other || 0 : 0);

        $('#token-input').text(numberFormat(totals.total_input_tokens || 0));
        $('#token-output').text(numberFormat(totals.total_output_tokens || 0));
        $('#token-cached').text(numberFormat(totals.total_cached_tokens || 0));

        // COST-001: use conversation-only pricing from server response.
        var conversationTokens = totals.conversation_tokens || 0;
        var conversationInputTokens = totals.conversation_input_tokens || 0;
        var conversationOutputTokens = totals.conversation_output_tokens || 0;
        var conversationCachedTokens = totals.conversation_cached_tokens || 0;
        var inputCost = 0;
        var outputCost = 0;
        var cachedCost = 0;
        var totalCost = totals.estimated_conversation_cost || totals.estimated_cost || 0;

        // Derive conversation-only component costs for display.
        if (conversationTokens > 0) {
            var uncachedConversationInput = Math.max(0, conversationInputTokens - conversationCachedTokens);
            inputCost = (uncachedConversationInput / 1000000) * 0.60;
            outputCost = (conversationOutputTokens / 1000000) * 2.40;
            cachedCost = (conversationCachedTokens / 1000000) * 0.06;
        }

        $('#cost-input').text(inputCost.toFixed(6));
        $('#cost-output').text(outputCost.toFixed(6));
        $('#cost-cached').text(cachedCost.toFixed(6));
        $('#token-total-cost').text(totalCost.toFixed(6));

        // Update pricing note
        if (data.pricing_note) {
            $('#pricing-note').text(data.pricing_note);
        }

        if (data.conversation_usage_missing) {
            displayError('Conversation token usage was not captured for this call (conversation shows 0 tokens). Re-run one call after clearing cache and verify again before continuing COST-001.');
        }
        if (data.realtime_modality_breakdown_missing) {
            displayError('Realtime cost estimate uses text-token rates only unless audio/token modality breakdown is stored. Compare against your provider billing before final COST-001 decisions.');
        }

        // Show metrics display
        $('#token-metrics-display').fadeIn();
    }

    /**
     * Display error message
     *
     * @param {string} message Error message to display
     */
    function displayError(message) {
        $('#token-error-message').text(message);
        $('#token-error-display').fadeIn();
    }

    /**
     * Format number with thousands separators
     *
     * @param {number} num Number to format
     * @return {string} Formatted number
     */
    function numberFormat(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    /**
     * Escape HTML to prevent XSS
     *
     * @param {string} text Text to escape
     * @return {string} Escaped text
     */
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    /**
     * Allow Enter key to trigger analysis
     */
    $('#token-callsid').on('keypress', function(e) {
        if (e.which === 13) { // Enter key
            e.preventDefault();
            $('#analyze-tokens').click();
        }
    });

    function runMinuteDrain(targetState) {
        var targetLabel = targetState === 'critical' ? 'Critical' : 'Low';
        var confirmMessage = 'This will consume real AI minutes in Firestore to force the ' + targetLabel + ' state for testing. Continue?';
        if (!confirm(confirmMessage)) {
            return;
        }

        var $btnLow = $('#sitestaffr-drain-to-low');
        var $btnCritical = $('#sitestaffr-drain-to-critical');
        var $spinner = $('#sitestaffr-drain-spinner');
        var $result = $('#sitestaffr-drain-result');

        $btnLow.prop('disabled', true);
        $btnCritical.prop('disabled', true);
        $spinner.addClass('is-active');
        $result.hide().text('');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sitestaffr_drain_minutes_test_state',
                target_state: targetState,
                nonce: sitestaffrDiagnostics.nonce
            },
            success: function(response) {
                if (response.success) {
                    var data = response.data || {};
                    var detail = (typeof data.before_total_minutes !== 'undefined' && typeof data.after_total_minutes !== 'undefined')
                        ? ' Before: ' + data.before_total_minutes + ' min, After: ' + data.after_total_minutes + ' min.'
                        : '';
                    var detailSeconds = (typeof data.before_total_seconds !== 'undefined' && typeof data.after_total_seconds !== 'undefined')
                        ? ' Before seconds: ' + data.before_total_seconds + ', After seconds: ' + data.after_total_seconds + '.'
                        : '';
                    var events = (typeof data.events_sent !== 'undefined')
                        ? ' Events sent: ' + data.events_sent + '.'
                        : '';
                    var message = (data.message || 'Minute drain completed.') + detail + detailSeconds + events;
                    $result.css({
                        background: '#edfaef',
                        borderLeftColor: '#1e8e3e',
                        color: '#1d2327'
                    }).text(message).show();
                } else {
                    var errorMessage = (response.data && (response.data.message || response.data.detail))
                        ? (response.data.message + (response.data.detail ? ' ' + response.data.detail : ''))
                        : 'Failed to drain minutes.';
                    $result.css({
                        background: '#fff3cd',
                        borderLeftColor: '#ffc107',
                        color: '#856404'
                    }).text(errorMessage).show();
                }
            },
            error: function(xhr, status, error) {
                $result.css({
                    background: '#fff3cd',
                    borderLeftColor: '#ffc107',
                    color: '#856404'
                }).text('AJAX request failed: ' + error).show();
            },
            complete: function() {
                $spinner.removeClass('is-active');
                $btnLow.prop('disabled', false);
                $btnCritical.prop('disabled', false);
            }
        });
    }

    $('#sitestaffr-drain-to-low').on('click', function() {
        runMinuteDrain('low');
    });

    $('#sitestaffr-drain-to-critical').on('click', function() {
        runMinuteDrain('critical');
    });

    /**
     * Reset to Fresh Install button click handler
     */
    $('#sitestaffr-reset-fresh-install').on('click', function() {
        if (!confirm('WARNING: This will permanently delete ALL SiteStaffr data (settings, calls, billing) and reset the site to a fresh install with a new trial.\n\nThis cannot be undone. Continue?')) {
            return;
        }

        if (!confirm('Are you absolutely sure? All call history, settings, and billing state will be lost.')) {
            return;
        }

        var $btn = $(this);
        var $spinner = $('#sitestaffr-reset-spinner');
        var $error = $('#sitestaffr-reset-error');

        $btn.prop('disabled', true);
        $spinner.addClass('is-active');
        $error.hide();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sitestaffr_reset_to_fresh_install',
                nonce: sitestaffrDiagnostics.nonce
            },
            success: function(response) {
                $spinner.removeClass('is-active');
                if (response.success && response.data.redirect_url) {
                    window.location.href = response.data.redirect_url;
                } else {
                    $error.text(response.data && response.data.message ? response.data.message : 'Reset failed.').show();
                    $btn.prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                $spinner.removeClass('is-active');
                $error.text('AJAX request failed: ' + error).show();
                $btn.prop('disabled', false);
            }
        });
    });
});
