/**
 * Aysa Credit Tracker
 * Automatic credit deduction tracking based on API endpoint usage
 * Maps endpoint costs from the .NET CreditDeductionMiddleware
 */

const aysaCreditNativeConsole = window.console || {
    log: function() {},
    warn: function() {},
    error: function() {}
};
var console = {
    log: function() {
        if (window.AYSA_DEBUG === true) {
            aysaCreditNativeConsole.log.apply(aysaCreditNativeConsole, arguments);
        }
    },
    warn: function() {
        if (window.AYSA_DEBUG === true) {
            aysaCreditNativeConsole.warn.apply(aysaCreditNativeConsole, arguments);
        }
    },
    error: function() {
        aysaCreditNativeConsole.error.apply(aysaCreditNativeConsole, arguments);
    }
};

const AysaCreditTracker = (function($) {
    'use strict';
    
    // Endpoint credit mapping based on the .NET middleware configuration
    const ENDPOINT_COSTS = {
        // FREE ENDPOINTS (No Credit Cost)
        'api/aysa-plugin/version-check': { cost: 0, name: 'version_check' },
        'api/aysa-plugin/user-verify': { cost: 0, name: 'user_verify' },
        'api/aysa-plugin/project-by-domain': { cost: 0, name: 'project_by_domain' },
        'api/aysa-plugin/seo-settings': { cost: 0, name: 'seo_settings' },
        'api/AysaCredits/get-total-credits': { cost: 0, name: 'credit_balance' },
        'api/AysaCredits/transactions': { cost: 0, name: 'credit_history' },
        'api/AysaCredits/transaction-summary': { cost: 0, name: 'credit_summary' },
        'api/AysaCredits/process-order': { cost: 0, name: 'process_order' },
        'api/aysa-plugin/support-report-issue': { cost: 0, name: 'support_report_issue' },
        'api/aysa-plugin/support-contact': { cost: 0, name: 'support_contact' },
        'api/suggestedkeywords/insert-one': { cost: 0, name: 'suggested_keyword_insert' },

        // AI CONTENT GENERATION (High Cost)
        'api/aysa-plugin/keyword-associations': { cost: 75, name: 'keyword_associations', category: 'ai content generation' },
        'api/aysa-plugin/product-category-title': { cost: 55, name: 'product_category_title', category: 'ai content generation' },
        'api/generalinformation/byproject': { cost: 15, name: 'general_info_generation', category: 'ai content generation' },

        // DOMAIN ANALYSIS & RESEARCH (Medium-High Cost)
        'api/ProjectDomainAuthority': { cost: 20, name: 'domain_authority', category: 'domain analysis' },
        'api/ProjectDomainAuthority/BySecret': { cost: 20, name: 'project_domain_authority', category: 'domain analysis' },
        'api/aysa-plugin/datasks/domain-authority-avg': { cost: 25, name: 'domain_authority_avg', category: 'domain analysis' },

        // COMPETITOR ANALYSIS (Medium-High Cost)
        'api/keywordsgap/keywords-gap': { cost: 60, name: 'keywords_gap', category: 'competitor analysis' },
        'api/aysa-plugin/dataforseo-domain-rank': { cost: 35, name: 'dataforseo_domain_rank', category: 'competitor analysis' },
        'api/aysa-plugin/ranked-keywords': { cost: 40, name: 'ranked_keywords', category: 'competitor analysis' },
        'api/seo/ranked-keywords-for-tracked-keywords': { cost: 40, name: 'ranked_keywords_tracked', category: 'competitor analysis' },

        // PERFORMANCE ANALYSIS (Medium Cost)
        'api/pagespeed/metrics': { cost: 20, name: 'pagespeed_metrics', category: 'performance analysis' },
        'api/pagespeed/overview': { cost: 15, name: 'pagespeed_overview', category: 'performance analysis' },
        'api/aysa-plugin/analyze-performance': { cost: 20, name: 'pagespeed_metrics', category: 'performance analysis' },
        'api/aysa-plugin/analyze-mobile-friendly': { cost: 15, name: 'mobile_friendly', category: 'performance analysis' },
        'api/aysa-plugin/internal-linking/search-links': { cost: 0, name: 'internal_linking', category: 'technical optimization' },

        // LINK BUILDING & MANAGEMENT (Variable Cost)
        'api/aysa-plugin/wordtolink-search': { cost: 10, name: 'wordtolink_search', category: 'link building' },
        'api/aysa-plugin/cancel-wordtolink': { cost: 0, name: 'cancel_wordtolink', category: 'link building' },

        // SEARCH INTENT ANALYSIS (Medium Cost)
        'api/SearchIntent/batch': { cost: 30, name: 'search_intent_batch', category: 'search intent analysis' },
        'api/searchintent/batch': { cost: 30, name: 'search_intent_batch', category: 'search intent analysis' },
        'api/searchintent/project': { cost: 25, name: 'search_intent_by_project', category: 'search intent analysis' },

        // RESEARCH & TASK MANAGEMENT (Low-Medium Cost)
        'api/researchtasks': { cost: 10, name: 'research_tasks', category: 'research management' },
        'api/researchtasks/byproject': { cost: 7, name: 'research_tasks_by_project', category: 'research management' },
        'api/researchtasks/taskdetails': { cost: 8, name: 'research_task_details', category: 'research management' },

        // TECHNICAL SEO (Low Cost)
        'api/redirect': { cost: 3, name: 'redirects', category: 'technical seo' },
        'api/redirect/auto-create': { cost: 7, name: 'auto_create_redirect', category: 'technical seo' },
        'api/goneurl': { cost: 3, name: 'gone_urls', category: 'technical seo' },
        'api/notfoundurl/unprocessed': { cost: 15, name: 'unprocessed_bulk', category: 'technical seo' },

        // KEYWORD & ASSOCIATION MANAGEMENT (Low Cost)
        'api/association': { cost: 5, name: 'associations', category: 'keyword management' },
        'api/association/setistracked': { cost: 3, name: 'associations_set_tracked', category: 'keyword management' },
        'api/association/upsert': { cost: 5, name: 'upsert_entity', category: 'keyword management' },
        'api/association/insertmany': { cost: 10, name: 'insert_many_keywords', category: 'keyword management' },
        'api/association/by-entity': { cost: 3, name: 'delete_entity_associations', category: 'keyword management' },

        // API-BILLED V2 FLOWS (display only in plugin)
        'v1/keywords/mapping/v1/workspace': { cost: 0, name: 'keyword_mapping_workspace_v2', category: 'api billed' },
        'v1/keywords/mapping/v1/selection': { cost: 0, name: 'keyword_mapping_selection_v2', category: 'api billed' },
        'v1/keywords/mapping/v1/missing-pages': { cost: 0, name: 'missing_pages_workspace_v2', category: 'api billed' },
        'v1/content/strategy/workspace': { cost: 0, name: 'content_strategy_workspace_v2', category: 'api billed' },
        'v1/content/strategy/generate': { cost: 0, name: 'content_strategy_generate_v2', category: 'api billed' }
    };
    
    // Track API calls
    let callHistory = [];
    let totalCreditsUsed = 0;

    function getProjectId() {
        if (typeof aysaCreditTrackerParams !== 'undefined' && Number(aysaCreditTrackerParams.project_id) > 0) {
            return Number(aysaCreditTrackerParams.project_id);
        }
        if (typeof aysa_params !== 'undefined' && Number(aysa_params.project_id) > 0) {
            return Number(aysa_params.project_id);
        }
        return 0;
    }
    
    /**
     * Normalize URL to match endpoint pattern
     */
    function normalizeUrl(url) {
        // Remove base URL if present
        let normalized = String(url || '')
            .replace(/^https?:\/\/api\.aysa\.ai\//i, '');
        
        // Remove query parameters
        normalized = normalized.split('?')[0];
        
        // Remove trailing slash
        normalized = normalized.replace(/\/$/, '');
        
        // Replace numeric IDs with generic pattern
        normalized = normalized.replace(/\/\d+/g, '');
        
        return normalized;
    }
    
    /**
     * Get credit cost for a specific endpoint
     */
    function getCreditCost(url) {
        const normalized = normalizeUrl(url);
        
        // Try exact match first
        if (ENDPOINT_COSTS[normalized]) {
            return ENDPOINT_COSTS[normalized];
        }
        
        // Try partial match (for endpoints with parameters)
        for (const [pattern, cost] of Object.entries(ENDPOINT_COSTS)) {
            if (normalized.includes(pattern) || pattern.includes(normalized)) {
                return cost;
            }
        }
        
        return null;
    }
    
    /**
     * Track an API call and update credits if cost > 0
     */
    function trackApiCall(url, method = 'GET') {
        const costInfo = getCreditCost(url);
        
        if (!costInfo) {
            console.log('[AysaCreditTracker] Unknown endpoint:', url);
            return;
        }
        
        const call = {
            url: url,
            method: method,
            cost: costInfo.cost,
            name: costInfo.name,
            category: costInfo.category || 'general',
            timestamp: new Date().toISOString()
        };
        
        callHistory.push(call);
        
        // If this call costs credits, log it and refresh credit display
        if (costInfo.cost > 0) {
            totalCreditsUsed += costInfo.cost;
            
            console.log(`[AysaCreditTracker] 💰 API call cost ${costInfo.cost} credits:`, {
                name: costInfo.name,
                category: costInfo.category,
                totalUsed: totalCreditsUsed
            });
            
            // Refresh credits display after a short delay (to allow backend to update)
            setTimeout(function() {
                refreshCredits();
            }, 1000);

            reportUsageToWallet(call);
        }
        
        return call;
    }

    function reportUsageToWallet(call) {
        const projectId = getProjectId();
        if (!projectId) {
            return;
        }
        const ajaxUrl = (typeof aysaCreditTrackerParams !== 'undefined' && aysaCreditTrackerParams.ajax_url)
            ? aysaCreditTrackerParams.ajax_url
            : (typeof ajaxurl !== 'undefined' ? ajaxurl : null);
        const nonce = (typeof aysaCreditTrackerParams !== 'undefined' && aysaCreditTrackerParams.nonce)
            ? aysaCreditTrackerParams.nonce
            : null;
        if (!ajaxUrl || !nonce) {
            return;
        }

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'aysa_wallet_track_usage',
                nonce: nonce,
                project_id: projectId,
                endpoint: call.url,
                cost_cents: call.cost,
                name: call.name || '',
                category: call.category || ''
            }
        });
    }
    
    /**
     * Refresh credits display from all credit components
     */
    function refreshCredits() {
        console.log('[AysaCreditTracker] 🔄 Refreshing credits display...');
        
        // Call the credits component refresh if available
        if (typeof window.AysaCredits !== 'undefined' && window.AysaCredits.refreshCredits) {
            window.AysaCredits.refreshCredits();
        }
        
        // Also trigger a custom event that other components can listen to
        $(document).trigger('aysa:credits:refresh');
    }
    
    /**
     * Get call history
     */
    function getCallHistory() {
        return callHistory;
    }
    
    /**
     * Get total credits used in this session
     */
    function getTotalCreditsUsed() {
        return totalCreditsUsed;
    }
    
    /**
     * Reset tracking (useful for testing)
     */
    function reset() {
        callHistory = [];
        totalCreditsUsed = 0;
    }
    
    /**
     * Get statistics by category
     */
    function getStatsByCategory() {
        const stats = {};
        
        callHistory.forEach(call => {
            const category = call.category || 'general';
            if (!stats[category]) {
                stats[category] = {
                    calls: 0,
                    totalCost: 0
                };
            }
            stats[category].calls++;
            stats[category].totalCost += call.cost;
        });
        
        return stats;
    }
    
    /**
     * Initialize the credit tracker
     */
    function init() {
        console.log('[AysaCreditTracker] Credit tracking system initialized');
        console.log('[AysaCreditTracker] Monitoring', Object.keys(ENDPOINT_COSTS).length, 'endpoints');
    }
    
    // Public API
    return {
        init: init,
        trackApiCall: trackApiCall,
        getCreditCost: getCreditCost,
        refreshCredits: refreshCredits,
        getCallHistory: getCallHistory,
        getTotalCreditsUsed: getTotalCreditsUsed,
        getStatsByCategory: getStatsByCategory,
        reset: reset
    };
    
})(jQuery);

// Initialize when document is ready
jQuery(document).ready(function() {
    AysaCreditTracker.init();
});
