// Broker Dashboard JavaScript

// Check authentication on page load
document.addEventListener('DOMContentLoaded', () => {
    checkAuthStatus();
    
    // Debug: Log authentication state
    console.log('Broker page loaded');
    console.log('authToken:', authToken);
    console.log('currentUser:', currentUser);
    
    // Only load data if we have a valid token
    if (authToken) {
        // Check role-based access - only brokers can access this page
        if (currentUser && currentUser.role === 'player') {
            console.log('Player user attempted to access broker area, redirecting to player dashboard');
            showNotification('Players do not have access to the broker area.', 'error');
            window.location.href = 'player.html';
            return;
        }
        
        console.log('Loading broker data...');
        loadBrokerData();
    } else {
        console.log('No token found, redirecting to login...');
        // Redirect to login if no token
        window.location.href = 'index.html';
    }
});

// Load broker-specific data
async function loadBrokerData() {
    try {
        // Load API key
        const apiKeyData = await apiRequest('/broker/api-key');
        document.getElementById('api-key').textContent = apiKeyData.api_key || 'Not available';
        
        // Load membership info
        const membershipData = await apiRequest('/broker/membership');
        document.getElementById('membership-plan').textContent = membershipData.plan || 'Basic';
        document.getElementById('renewal-date').textContent = membershipData.renewal_date || 'N/A';
        document.getElementById('api-calls').textContent = membershipData.api_calls || '10,000';
        
        // Load stats
        const statsData = await apiRequest('/broker/stats');
        document.getElementById('total-bets').textContent = statsData.total_bets || 0;
        document.getElementById('active-apps').textContent = statsData.active_apps || 0;
        document.getElementById('revenue').textContent = `$${(statsData.revenue || 0).toFixed(2)}`;
        
        // Load webhook configuration
        const webhookData = await apiRequest('/broker/webhook');
        if (webhookData.url) {
            document.getElementById('webhook-url').value = webhookData.url;
        }
        
        // Load application settings
        const appData = await apiRequest('/broker/settings');
        if (appData.name) {
            document.getElementById('app-name').value = appData.name;
        }
        if (appData.url) {
            document.getElementById('app-url').value = appData.url;
        }
        if (appData.callback_url) {
            document.getElementById('callback-url').value = appData.callback_url;
        }
        
        // Update user name and avatar
        if (currentUser) {
            const displayName = currentUser.real_name || currentUser.name || currentUser.username || 'Broker';
            document.getElementById('user-name').textContent = displayName;
            
            // Update avatar with Gravatar
            const avatarElement = document.getElementById('user-avatar');
            if (avatarElement) {
                if (currentUser.avatar_url) {
                    avatarElement.src = currentUser.avatar_url;
                } else if (currentUser.email) {
                    const emailHash = md5Hash(currentUser.email.toLowerCase().trim());
                    avatarElement.src = `https://www.gravatar.com/avatar/${emailHash}?s=32&d=identicon`;
                }
            }
        }
    } catch (error) {
        console.error('Error loading broker data:', error);
        showNotification('Failed to load broker data. Please refresh the page.', 'error');
    }
}

// Regenerate API Key
async function regenerateApiKey() {
    if (!confirm('Are you sure you want to regenerate your API key? This will invalidate your current key.')) {
        return;
    }
    
    try {
        const response = await apiRequest('/broker/regenerate-api-key', {
            method: 'POST'
        });
        
        document.getElementById('api-key').textContent = response.api_key;
        showNotification('API key regenerated successfully!', 'success');
    } catch (error) {
        console.error('Error regenerating API key:', error);
        showNotification('Failed to regenerate API key. Please try again.', 'error');
    }
}

// Upgrade Membership
async function upgradeMembership() {
    try {
        const response = await apiRequest('/broker/upgrade-membership', {
            method: 'POST'
        });
        
        showNotification('Membership upgrade request submitted! You will be contacted shortly.', 'success');
        
        // Refresh membership data
        setTimeout(() => {
            loadBrokerData();
        }, 1000);
    } catch (error) {
        console.error('Error upgrading membership:', error);
        showNotification('Failed to upgrade membership. Please try again.', 'error');
    }
}

// Save Webhook Configuration
async function saveWebhookConfig() {
    const webhookUrl = document.getElementById('webhook-url').value;
    const webhookEvents = Array.from(document.getElementById('webhook-events').selectedOptions).map(option => option.value);
    
    if (!webhookUrl) {
        showNotification('Please enter a webhook URL.', 'error');
        return;
    }
    
    try {
        await apiRequest('/broker/webhook', {
            method: 'PUT',
            body: JSON.stringify({
                url: webhookUrl,
                events: webhookEvents
            })
        });
        
        showNotification('Webhook configuration saved successfully!', 'success');
    } catch (error) {
        console.error('Error saving webhook configuration:', error);
        showNotification('Failed to save webhook configuration. Please try again.', 'error');
    }
}

// Save Application Settings
async function saveAppSettings() {
    const appName = document.getElementById('app-name').value;
    const appUrl = document.getElementById('app-url').value;
    const callbackUrl = document.getElementById('callback-url').value;
    
    if (!appName) {
        showNotification('Please enter an application name.', 'error');
        return;
    }
    
    try {
        await apiRequest('/broker/settings', {
            method: 'PUT',
            body: JSON.stringify({
                name: appName,
                url: appUrl,
                callback_url: callbackUrl
            })
        });
        
        showNotification('Application settings saved successfully!', 'success');
    } catch (error) {
        console.error('Error saving application settings:', error);
        showNotification('Failed to save application settings. Please try again.', 'error');
    }
}

// Test API Connection
async function testApiConnection() {
    try {
        const response = await apiRequest('/broker/test-connection', {
            method: 'POST'
        });
        
        showNotification('API connection successful!', 'success');
    } catch (error) {
        console.error('API connection test failed:', error);
        showNotification('API connection test failed. Please check your configuration.', 'error');
    }
}

// Copy API Key to Clipboard
function copyApiKey() {
    const apiKey = document.getElementById('api-key').textContent;
    navigator.clipboard.writeText(apiKey).then(() => {
        showNotification('API key copied to clipboard!', 'success');
    }).catch(err => {
        console.error('Failed to copy API key:', err);
        showNotification('Failed to copy API key. Please try again.', 'error');
    });
}

// View API Logs
async function viewApiLogs() {
    try {
        const logs = await apiRequest('/broker/logs');
        
        // Create a modal to display logs
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h2>API Logs</h2>
                    <button class="close-btn" onclick="this.closest('.modal').remove()">&times;</button>
                </div>
                <div class="modal-body">
                    <pre>${JSON.stringify(logs, null, 2)}</pre>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
    } catch (error) {
        console.error('Error loading API logs:', error);
        showNotification('Failed to load API logs. Please try again.', 'error');
    }
}

// Export API Documentation
function exportApiDocs() {
    const docsContent = document.querySelector('.api-docs').innerHTML;
    const blob = new Blob([docsContent], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'tcl-api-documentation.html';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    showNotification('API documentation exported successfully!', 'success');
}

// Toggle user dropdown menu
function toggleUserDropdown() {
    const dropdown = document.getElementById('user-dropdown');
    if (dropdown) {
        dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
    }
}

// Close dropdown when clicking outside
document.addEventListener('click', function(e) {
    const dropdown = document.getElementById('user-dropdown');
    const userProfile = document.querySelector('.user-profile');
    if (dropdown && userProfile && !userProfile.contains(e.target)) {
        dropdown.style.display = 'none';
    }
});

// Simple MD5 hash function for Gravatar
function md5Hash(string) {
    function md5cycle(x, k) {
        var a = x[0], b = x[1], c = x[2], d = x[3];
        a = ff(a, b, c, d, k[0], 7, -680876936);
        d = ff(d, a, b, c, k[1], 12, -389564586);
        c = ff(c, d, a, b, k[2], 17, 606105819);
        b = ff(b, c, d, a, k[3], 22, -1044525330);
        a = ff(a, b, c, d, k[4], 7, -176418897);
        d = ff(d, a, b, c, k[5], 12, 1200080426);
        c = ff(c, d, a, b, k[6], 17, -1473231341);
        b = ff(b, c, d, a, k[7], 22, -45705983);
        a = ff(a, b, c, d, k[8], 7, 1770035416);
        d = ff(d, a, b, c, k[9], 12, -1958414417);
        c = ff(c, d, a, b, k[10], 17, -42063);
        b = ff(b, c, d, a, k[11], 22, -1990404162);
        a = ff(a, b, c, d, k[12], 7, 1804603682);
        d = ff(d, a, b, c, k[13], 12, -40341101);
        c = ff(c, d, a, b, k[14], 17, -1502002290);
        b = ff(b, c, d, a, k[15], 22, 1236535329);
        a = gg(a, b, c, d, k[1], 5, -165796510);
        d = gg(d, a, b, c, k[6], 9, -1069501632);
        c = gg(c, d, a, b, k[11], 14, 643717713);
        b = gg(b, c, d, a, k[0], 20, -373897302);
        a = gg(a, b, c, d, k[5], 5, -701558691);
        d = gg(d, a, b, c, k[10], 9, 38016083);
        c = gg(c, d, a, b, k[15], 14, -660478335);
        b = gg(b, c, d, a, k[4], 20, -405537848);
        a = gg(a, b, c, d, k[9], 5, 568446438);
        d = gg(d, a, b, c, k[14], 9, -1019803690);
        c = gg(c, d, a, b, k[3], 14, -187363961);
        b = gg(b, c, d, a, k[8], 20, 1163531501);
        a = gg(a, b, c, d, k[13], 5, -1444681467);
        d = gg(d, a, b, c, k[2], 9, -51403784);
        c = gg(c, d, a, b, k[7], 14, 1735328473);
        b = gg(b, c, d, a, k[12], 20, -1926607734);
        a = hh(a, b, c, d, k[5], 4, -378558);
        d = hh(d, a, b, c, k[8], 11, -2022574463);
        c = hh(c, d, a, b, k[11], 16, 1839030562);
        b = hh(b, c, d, a, k[14], 23, -35309556);
        a = hh(a, b, c, d, k[1], 4, -1530992060);
        d = hh(d, a, b, c, k[4], 11, 1272893353);
        c = hh(c, d, a, b, k[7], 16, -155497632);
        b = hh(b, c, d, a, k[10], 23, -1094730640);
        a = hh(a, b, c, d, k[13], 4, 681279174);
        d = hh(d, a, b, c, k[0], 11, -358537222);
        c = hh(c, d, a, b, k[3], 16, -722521979);
        b = hh(b, c, d, a, k[6], 23, 76029189);
        a = hh(a, b, c, d, k[9], 4, -640364487);
        d = hh(d, a, b, c, k[12], 11, -421815835);
        c = hh(c, d, a, b, k[15], 16, 530742520);
        b = hh(b, c, d, a, k[2], 23, -995338651);
        a = ii(a, b, c, d, k[0], 6, -198630844);
        d = ii(d, a, b, c, k[7], 10, 1126891415);
        c = ii(c, d, a, b, k[14], 15, -1416354905);
        b = ii(b, c, d, a, k[5], 21, -57434055);
        a = ii(a, b, c, d, k[12], 6, 1700485571);
        d = ii(d, a, b, c, k[3], 10, -1894986606);
        c = ii(c, d, a, b, k[10], 15, -1051523);
        b = ii(b, c, d, a, k[1], 21, -2054922799);
        a = ii(a, b, c, d, k[8], 6, 1873313359);
        d = ii(d, a, b, c, k[15], 10, -30611744);
        c = ii(c, d, a, b, k[6], 15, -1560198380);
        b = ii(b, c, d, a, k[13], 21, 1309151649);
        a = ii(a, b, c, d, k[4], 6, -145523070);
        d = ii(d, a, b, c, k[11], 10, -1120210379);
        c = ii(c, d, a, b, k[2], 15, 718787259);
        b = ii(b, c, d, a, k[9], 21, -343485551);
        x[0] = add32(a, x[0]);
        x[1] = add32(b, x[1]);
        x[2] = add32(c, x[2]);
        x[3] = add32(d, x[3]);
    }
    function cmn(q, a, b, x, s, t) { a = add32(add32(a, q), add32(x, t)); return add32((a << s) | (a >>> (32 - s)), b); }
    function ff(a, b, c, d, x, s, t) { return cmn((b & c) | ((~b) & d), a, b, x, s, t); }
    function gg(a, b, c, d, x, s, t) { return cmn((b & d) | (c & (~d)), a, b, x, s, t); }
    function hh(a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t); }
    function ii(a, b, c, d, x, s, t) { return cmn(c ^ (b | (~d)), a, b, x, s, t); }
    function md51(s) {
        var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i;
        for (i = 64; i <= s.length; i += 64) { md5cycle(state, md5blk(s.substring(i - 64, i))); }
        s = s.substring(i - 64);
        var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        for (i = 0; i < s.length; i++) tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
        tail[i >> 2] |= 0x80 << ((i % 4) << 3);
        if (i > 55) { md5cycle(state, tail); for (i = 0; i < 16; i++) tail[i] = 0; }
        tail[14] = n * 8;
        md5cycle(state, tail);
        return state;
    }
    function md5blk(s) {
        var md5blks = [], i;
        for (i = 0; i < 64; i += 4) { md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24); }
        return md5blks;
    }
    var hex_chr = '0123456789abcdef'.split('');
    function rhex(n) { var s = '', j = 0; for (; j < 4; j++) s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; return s; }
    function hex(x) { for (var i = 0; i < x.length; i++) x[i] = rhex(x[i]); return x.join(''); }
    function add32(a, b) { return (a + b) & 0xFFFFFFFF; }
    return hex(md51(string));
}