/**
 * Aysa Credits Component
 * 
 * Handles the frontend functionality for the Aysa credits component
 */

(function($) {
    'use strict';
    
    let creditsAmount = 0;

    function extractSnapshotMeta(payload) {
        if (!payload || typeof payload !== 'object') {
            return {};
        }
        if (payload.snapshot && typeof payload.snapshot === 'object') {
            return payload.snapshot;
        }
        return payload;
    }

    function labelForUsageAction(actionKey, reference) {
        const key = String(actionKey || '');
        const ref = String(reference || '');

        if (key === 'aysa_setup_conversation_message' || ref.indexOf('setup_conversation') !== -1) {
            return 'Last usage: setup conversation';
        }
        if (key === 'aysa_adjustments_conversation_message' || ref.indexOf('adjustments') !== -1) {
            return 'Last usage: AYSA conversation';
        }
        if (key === 'aysa_monitoring_rank_refresh' || ref.indexOf('monitoring') !== -1 || ref.indexOf('rank_refresh') !== -1) {
            return 'Last usage: monitoring refresh';
        }
        if (key === 'aysa_adverlink_create_order' || ref.indexOf('offpage_create_order') !== -1) {
            return 'Last usage: off-page order';
        }
        if (key === 'aysa_content_strategy_generate') {
            return 'Last usage: content strategy';
        }
        return 'Last usage';
    }

    function formatCreditsMeta(payload) {
        const meta = extractSnapshotMeta(payload);
        const amount = Math.abs(Number(meta.latest_usage_amount_cents || 0));
        if (!Number.isFinite(amount) || amount <= 0) {
            return 'AI chat, monitoring, and AYSA execution actions use credits based on cost.';
        }

        const label = labelForUsageAction(meta.latest_usage_action_key, meta.latest_usage_reference);
        return label + ': ' + Math.floor(amount) + ' credit' + (Math.floor(amount) === 1 ? '' : 's');
    }

    function extractAjaxMessage(xhr, response) {
        if (response && typeof response === 'object') {
            if (response.data && typeof response.data.message === 'string') {
                return response.data.message;
            }
            if (typeof response.data === 'string') {
                return response.data;
            }
        }
        if (xhr && xhr.responseJSON) {
            if (xhr.responseJSON.data && typeof xhr.responseJSON.data.message === 'string') {
                return xhr.responseJSON.data.message;
            }
            if (typeof xhr.responseJSON.data === 'string') {
                return xhr.responseJSON.data;
            }
        }
        if (xhr && typeof xhr.responseText === 'string') {
            return xhr.responseText;
        }
        return '';
    }

    function isExpectedCreditsUnavailable(xhr, response) {
        const message = String(extractAjaxMessage(xhr, response) || '').toLowerCase();
        return (xhr && Number(xhr.status) === 403)
            || message.indexOf('authentication required') !== -1
            || message.indexOf('invalid project id') !== -1;
    }
    
    /**
     * Get project ID from various sources
     */
    function getProjectId() {
        // First try localized credits params (single source for all admin pages).
        if (
            typeof aysa_credits_params !== 'undefined' &&
            aysa_credits_params.project_id &&
            Number(aysa_credits_params.project_id) > 0
        ) {
            return parseInt(aysa_credits_params.project_id, 10);
        }

        // Fallback: legacy localized params from older screens.
        if (typeof aysaParams !== 'undefined' && aysaParams.project_id && aysaParams.project_id > 0) {
            return aysaParams.project_id;
        }

        // Do not use localStorage as source of truth for project_id; it can drift across sites/projects.
        return 0;
    }
    
    /**
     * Initialize the credits component
     */
    function init() {
        // Skip initialization when credits widget is not present on this page.
        if (!$('.aysa-credits-amount').length && !$('.aysa-credits-widget').length) {
            return;
        }

        // Fetch credits on load
        fetchCredits();
        
        // Add event listener for buy button
        $(document).on('click', '.aysa-buy-credits-btn', function(e) {
            e.preventDefault();
            buyCredits();
        });
        
        // Set up refresh interval (every 5 minutes)
        setInterval(fetchCredits, 5 * 60 * 1000);
    }
    
    /**
     * Fetch credits from the server
     */
    function fetchCredits() {
        const projectId = getProjectId();
        
        if (!projectId) {
            // No project yet (e.g. setup not completed) - show neutral value.
            updateCreditsDisplay(0);
            return;
        }

        fetchCreditsViaAjax();
    }
    
    /**
     * Fallback method to fetch credits via WordPress AJAX
     */
    function fetchCreditsViaAjax() {
        const projectId = getProjectId();

        $.ajax({
            url: aysa_credits_params.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_adverlink_credit_balance',
                nonce: aysa_credits_params.standard_nonce || aysa_credits_params.nonce,
                project_id: projectId
            },
            success: function(response) {
                if (response && response.success && response.data !== undefined) {
                    const amount = Number(
                        response.data.available_credits ??
                        response.data.actual_credits ??
                        response.data.credits ??
                        0
                    );
                    creditsAmount = Number.isFinite(amount) ? amount : 0;
                    updateCreditsDisplay(creditsAmount, response.data || {});
                    return;
                }
                if (isExpectedCreditsUnavailable(null, response)) {
                    updateCreditsDisplay(0, {});
                    return;
                }
                fetchCreditsViaLegacy(projectId);
            },
            error: function(xhr) {
                if (isExpectedCreditsUnavailable(xhr, null)) {
                    updateCreditsDisplay(0, {});
                    return;
                }
                fetchCreditsViaLegacy(projectId);
            }
        });
    }

    function fetchCreditsViaLegacy(projectId) {
        $.ajax({
            url: aysa_credits_params.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_credits',
                nonce: aysa_credits_params.nonce,
                project_id: projectId
            },
            success: function(response) {
                if (response && response.success && response.data !== undefined) {
                    const amount = Number(
                        response.data.credits ??
                        response.data.totalCredits ??
                        response.data.currentBalance ??
                        response.data ??
                        0
                    );
                    creditsAmount = Number.isFinite(amount) ? amount : 0;
                    updateCreditsDisplay(creditsAmount, response.data || {});
                } else {
                    if (isExpectedCreditsUnavailable(null, response)) {
                        updateCreditsDisplay(0, {});
                        return;
                    }
                    const message = response && response.data && response.data.message ? response.data.message : 'Unknown error';
                    console.error('Failed to fetch credits:', message);
                    // Show default value if everything fails
                    updateCreditsDisplay(0, {});
                }
            },
            error: function(xhr, status, error) {
                if (isExpectedCreditsUnavailable(xhr, null)) {
                    updateCreditsDisplay(0, {});
                    return;
                }
                console.error('Error fetching credits via AJAX:', error);
                // Show default value if everything fails
                updateCreditsDisplay(0, {});
            }
        });
    }
    
    /**
     * Update the credits display in all instances of the component
     * 
     * @param {number} amount - The credits amount to display
     */
    function updateCreditsDisplay(amount, payload) {
        // Convert to integer by using Math.floor
        const integerAmount = Math.floor(amount);
        $('.aysa-credits-amount').text(integerAmount);
        $('.aysa-credits-meta').text(formatCreditsMeta(payload));
    }
    
    /**
     * Initiate the process to buy more credits
     */
    function createTopupOrder(creditsCents, handlers = {}) {
        const projectId = getProjectId();
        if (!projectId) {
            return Promise.reject(new Error('Project ID missing. Complete setup first.'));
        }
        const normalizedCredits = parseInt(creditsCents, 10);
        if (!Number.isFinite(normalizedCredits) || normalizedCredits <= 0) {
            return Promise.reject(new Error('Invalid credits amount.'));
        }

        return new Promise(function(resolve, reject) {
            $.ajax({
                url: aysa_credits_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_buy_credits',
                    nonce: aysa_credits_params.nonce,
                    project_id: projectId,
                    credits_cents: normalizedCredits
                },
                success: function(response) {
                    if (response && response.success) {
                        const paymentLink = response?.data?.payment_link || '';
                        if (typeof handlers.onSuccess === 'function') {
                            handlers.onSuccess(response, paymentLink);
                        }
                        resolve({
                            response: response,
                            paymentLink: paymentLink,
                            order: response?.data?.order || null
                        });
                        return;
                    }

                    const message = response && response.data && response.data.message
                        ? response.data.message
                        : 'Failed to create credit order.';
                    if (typeof handlers.onError === 'function') {
                        handlers.onError(message, response);
                    }
                    reject(new Error(message));
                },
                error: function(xhr, status, error) {
                    const message = error || 'Failed to create credit order. Please try again.';
                    if (typeof handlers.onError === 'function') {
                        handlers.onError(message, xhr);
                    }
                    reject(new Error(message));
                }
            });
        });
    }

    function startTopupCheckout(creditsCents, handlers = {}) {
        return createTopupOrder(creditsCents, handlers).then(function(result) {
            if (result.paymentLink) {
                window.open(result.paymentLink, '_blank', 'noopener');
                fetchCredits();
                return result;
            }

            const orderId = result?.order?.id || '';
            const message = `Order #${orderId} created, but checkout link is missing.`;
            if (typeof handlers.onMissingLink === 'function') {
                handlers.onMissingLink(message, result);
            } else {
                alert(message);
            }
            return result;
        });
    }

    function buyCredits() {
        const projectId = getProjectId();
        
        if (!projectId) {
            // No project yet (e.g. setup not completed) - keep UI silent.
            return;
        }

        const packages = [
            { label: '10 EUR', creditsCents: 1000 },
            { label: '25 EUR', creditsCents: 2500 },
            { label: '50 EUR', creditsCents: 5000 }
        ];
        const optionsText = packages.map(function(pkg, index) {
            return (index + 1) + '. ' + pkg.label;
        }).join('\n');
        const choiceText = window.prompt('Choose a top-up package:\n' + optionsText, '2');
        if (choiceText === null) {
            return;
        }

        const packageIndex = parseInt(String(choiceText).replace(/[^\d]/g, ''), 10) - 1;
        const selectedPackage = packages[packageIndex];
        if (!selectedPackage) {
            alert('Invalid package. Please choose 1, 2 or 3.');
            return;
        }

        const creditsCents = selectedPackage.creditsCents;
        startTopupCheckout(creditsCents, {
            onError: function(message, response) {
                console.error('Failed to create credit order:', response || message);
                alert(message);
            }
        });
    }
    
    /**
     * Alternative method to directly trigger the credit purchase flow
     * This can be called from other components if needed
     */
    function openCreditPurchaseModal() {
        // Create a modal for credit purchase if it doesn't exist
        if ($('#aysa-credit-purchase-modal').length === 0) {
            const $modal = $(`
                <div id="aysa-credit-purchase-modal" class="aysa-modal">
                    <div class="aysa-modal-content">
                        <span class="aysa-modal-close">&times;</span>
                        <h2>Purchase Credits</h2>
                        <div class="aysa-modal-body">
                            <p>Choose an amount of credits to purchase:</p>
                            <div class="aysa-credit-options">
                                <div class="aysa-credit-option" data-amount="1000">
                                    <h3>1,000 Credits</h3>
                                    <p class="aysa-credit-price">$10</p>
                                    <button class="aysa-select-credit-btn">Select</button>
                                </div>
                                <div class="aysa-credit-option" data-amount="5000">
                                    <h3>5,000 Credits</h3>
                                    <p class="aysa-credit-price">$45</p>
                                    <p class="aysa-credit-savings">Save 10%</p>
                                    <button class="aysa-select-credit-btn">Select</button>
                                </div>
                                <div class="aysa-credit-option" data-amount="10000">
                                    <h3>10,000 Credits</h3>
                                    <p class="aysa-credit-price">$80</p>
                                    <p class="aysa-credit-savings">Save 20%</p>
                                    <button class="aysa-select-credit-btn">Select</button>
                                </div>
                            </div>
                            <button id="aysa-confirm-purchase" class="aysa-confirm-purchase-btn" disabled>Proceed to Payment</button>
                        </div>
                    </div>
                </div>
            `);
            
            $('body').append($modal);
            
            // Close modal when clicking X
            $modal.find('.aysa-modal-close').on('click', function() {
                $modal.hide();
            });
            
            // Close modal when clicking outside
            $(window).on('click', function(e) {
                if ($(e.target).is($modal)) {
                    $modal.hide();
                }
            });
            
            // Handle credit selection
            $modal.find('.aysa-select-credit-btn').on('click', function() {
                $modal.find('.aysa-credit-option').removeClass('selected');
                $(this).closest('.aysa-credit-option').addClass('selected');
                $modal.find('#aysa-confirm-purchase').prop('disabled', false);
            });
            
            // Handle purchase confirmation
            $modal.find('#aysa-confirm-purchase').on('click', function() {
                const selectedAmount = $modal.find('.aysa-credit-option.selected').data('amount');
                if (selectedAmount) {
                    proceedToCreditPurchase(selectedAmount);
                    $modal.hide();
                }
            });
        }
        
        // Show the modal
        $('#aysa-credit-purchase-modal').show();
    }
    
    /**
     * Process the credit purchase
     * 
     * @param {number} amount - The amount of credits to purchase
     */
    function proceedToCreditPurchase(amount) {
        startTopupCheckout(amount, {
            onError: function(message, response) {
                console.error('Failed to create credit order:', response || message);
                alert(message);
            }
        });
    }
    
    // Initialize when document is ready
    $(document).ready(init);
    
    // Expose public methods
    window.AysaCredits = {
        refreshCredits: fetchCredits,
        openPurchaseModal: openCreditPurchaseModal,
        createTopupOrder: createTopupOrder,
        startTopupCheckout: startTopupCheckout
    };
    
    })(jQuery); 
