// API Configuration
const API_BASE_URL = '/api'; // This will be proxied through nginx to the mbetterc API

// State Management
let currentUser = null;
let authToken = null;
let refreshToken = null;
let tokenExpiresAt = null;

// Token refresh timer
let tokenRefreshTimer = null;

// DOM Elements
const authModal = document.getElementById('authModal');
const loginForm = document.getElementById('login-form');
const signupForm = document.getElementById('signup-form');
const loginFormElement = document.getElementById('loginForm');
const signupFormElement = document.getElementById('signupForm');

// Modal Functions
function showAuthModal(tab = 'login') {
    if (authModal) {
        authModal.classList.add('active');
        // If signup is disabled and user tries to access signup tab, force login
        if (tab === 'signup' && !signupConfig.website_enabled) {
            tab = 'login';
        }
        switchTab(tab);
        document.body.style.overflow = 'hidden'; // Prevent background scrolling
    }
}

function closeAuthModal() {
    if (authModal) {
        authModal.classList.remove('active');
        document.body.style.overflow = ''; // Restore scrolling
    }
}

function selectBrokerRole() {
    // Wait for the modal to be visible, then select broker role
    setTimeout(() => {
        const roleSelect = document.getElementById('signup-role');
        if (roleSelect) {
            roleSelect.value = 'broker';
        }
    }, 100);
}

function switchTab(tab) {
    const tabButtons = document.querySelectorAll('.tab-btn');
    
    // Update active tab button
    tabButtons.forEach(btn => btn.classList.remove('active'));
    const activeButton = document.querySelector(`[data-tab="${tab}"]`);
    if (activeButton) {
        activeButton.classList.add('active');
    }
    
    // Show corresponding form
    if (tab === 'login') {
        loginForm.classList.add('active');
        signupForm.classList.remove('active');
    } else {
        signupForm.classList.add('active');
        loginForm.classList.remove('active');
    }
}

// Tab Switching Event Listeners
document.querySelectorAll('.tab-btn').forEach(button => {
    button.addEventListener('click', () => {
        const tab = button.dataset.tab;
        switchTab(tab);
    });
});

// Close modal when clicking outside
if (authModal) {
    authModal.addEventListener('click', (e) => {
        if (e.target === authModal) {
            closeAuthModal();
        }
    });
}

// Close modal with ESC key
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && authModal && authModal.classList.contains('active')) {
        closeAuthModal();
    }
});

// Login Form Submission (only if element exists - it's only on index.html)
if (loginFormElement) {
    loginFormElement.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = new FormData(loginFormElement);
    const loginData = {
        username: formData.get('email'),  // Send as username (can be username or email)
        password: formData.get('password'),
        remember: document.getElementById('login-remember')?.checked || false
    };
    
    try {
        const response = await fetch(`${API_BASE_URL}/auth/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(loginData)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // Store authentication data
            // API returns 'access_token' and optionally 'refresh_token'
            authToken = data.access_token || data.token;
            currentUser = data.user;
            
            // Store refresh token if provided (for persistent sessions)
            if (data.refresh_token) {
                refreshToken = data.refresh_token;
                localStorage.setItem('refreshToken', refreshToken);
            }
            
            // Store token expiration time
            if (data.expires_in) {
                tokenExpiresAt = Date.now() + (data.expires_in * 1000);
                localStorage.setItem('tokenExpiresAt', tokenExpiresAt.toString());
            }
            
            // Store in localStorage for persistence
            localStorage.setItem('authToken', authToken);
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            
            // Verify token was stored
            const storedToken = localStorage.getItem('authToken');
            console.log('Token stored:', !!storedToken, 'Token length:', storedToken ? storedToken.length : 0);
            
            // Set up automatic token refresh
            setupTokenRefresh();
            
            // Show success notification
            showNotification('Login successful!', 'success');
            
            // Close modal
            closeAuthModal();
            
            // Redirect to appropriate dashboard
            setTimeout(() => {
                redirectToDashboard(currentUser.role);
            }, 1000);
        } else {
            showNotification(data.message || 'Login failed. Please try again.', 'error');
        }
    } catch (error) {
        console.error('Login error:', error);
        showNotification('An error occurred. Please try again later.', 'error');
    }
});
}

// Sign Up Form Submission (only if element exists - it's only on index.html)
if (signupFormElement) {
    signupFormElement.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = new FormData(signupFormElement);
    const password = formData.get('password');
    const confirmPassword = formData.get('confirm_password');
    
    // Validate passwords match
    if (password !== confirmPassword) {
        showNotification('Passwords do not match.', 'error');
        return;
    }
    
    const signupData = {
        username: formData.get('name'),
        email: formData.get('email'),
        password: password,
        role: formData.get('role')
    };
    
    try {
        const response = await fetch(`${API_BASE_URL}/signup`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(signupData)
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            // Show success notification
            showNotification(data.message || 'Account created successfully! Please check your email to verify your account.', 'success');
            
            // Clear signup form
            signupFormElement.reset();
            
            // Switch to login tab
            switchTab('login');
        } else {
            showNotification(data.error || data.message || 'Sign up failed. Please try again.', 'error');
        }
    } catch (error) {
        console.error('Sign up error:', error);
        showNotification(error.message || 'An error occurred. Please try again later.', 'error');
    }
});
}

// Redirect to appropriate dashboard based on user role
function redirectToDashboard(role) {
    if (role === 'broker') {
        window.location.href = 'broker.html';
    } else if (role === 'player') {
        window.location.href = 'player.html';
    } else {
        showNotification('Invalid user role.', 'error');
    }
}

// Show notification
function showNotification(message, type) {
    // Remove existing notifications
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(notification => notification.remove());
    
    // Create new notification
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // Remove notification after 3 seconds
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

// Check if user is already logged in on page load
function checkAuthStatus() {
    // Check for OAuth callback tokens (stored by backend redirect)
    const oauthToken = localStorage.getItem('auth_token');
    const oauthUser = localStorage.getItem('user');
    
    // Migrate OAuth tokens to standard token names
    if (oauthToken && oauthUser) {
        localStorage.setItem('authToken', oauthToken);
        localStorage.setItem('currentUser', oauthUser);
        localStorage.removeItem('auth_token');
        localStorage.removeItem('user');
        console.log('Migrated OAuth tokens to standard token names');
    }
    
    const storedToken = localStorage.getItem('authToken');
    const storedUser = localStorage.getItem('currentUser');
    const storedRefreshToken = localStorage.getItem('refreshToken');
    const storedTokenExpiresAt = localStorage.getItem('tokenExpiresAt');
    
    if (storedToken && storedUser) {
        authToken = storedToken;
        currentUser = JSON.parse(storedUser);
        
        // Restore refresh token if available
        if (storedRefreshToken) {
            refreshToken = storedRefreshToken;
        }
        
        // Restore token expiration time if available
        if (storedTokenExpiresAt) {
            tokenExpiresAt = parseInt(storedTokenExpiresAt);
        }
        
        // Check if access token is expired and we have a refresh token
        if (tokenExpiresAt && Date.now() > tokenExpiresAt && refreshToken) {
            // Token expired, try to refresh
            refreshAccessToken().then(success => {
                if (success) {
                    setupTokenRefresh();
                    updateNavForLoggedInUser();
                    handleAutoRedirect();
                } else {
                    // Refresh failed, but keep user logged in if refresh token is still valid
                    // The refresh token is valid for 30 days, so user stays logged in
                    console.log('Token refresh failed, but session may still be valid');
                    updateNavForLoggedInUser();
                    handleAutoRedirect();
                }
            });
        } else {
            // Token still valid or no refresh token
            setupTokenRefresh();
            updateNavForLoggedInUser();
            handleAutoRedirect();
        }
    }
}

// Handle automatic redirect for logged-in users
function handleAutoRedirect() {
    // Only redirect if we're on the landing page (index.html)
    // Don't redirect if we're already on a dashboard page
    if (window.location.pathname.endsWith('index.html') || window.location.pathname === '/') {
        console.log('User is logged in:', currentUser.username, 'as', currentUser.role);
        // Auto-redirect to dashboard for logged-in users
        redirectToDashboard(currentUser.role);
    }
}

// Set up automatic token refresh
function setupTokenRefresh() {
    // Clear any existing timer
    if (tokenRefreshTimer) {
        clearTimeout(tokenRefreshTimer);
    }
    
    // If we have a refresh token, set up automatic refresh
    if (!refreshToken || !tokenExpiresAt) {
        return;
    }
    
    // Calculate when to refresh (5 minutes before expiration)
    const refreshTime = tokenExpiresAt - Date.now() - (5 * 60 * 1000);
    
    if (refreshTime > 0) {
        console.log(`Token refresh scheduled in ${Math.round(refreshTime / 1000 / 60)} minutes`);
        tokenRefreshTimer = setTimeout(async () => {
            console.log('Auto-refreshing access token...');
            const success = await refreshAccessToken();
            if (success) {
                setupTokenRefresh(); // Set up next refresh
            }
        }, refreshTime);
    } else if (Date.now() < tokenExpiresAt) {
        // Token expires in less than 5 minutes, refresh now
        console.log('Token expires soon, refreshing now...');
        refreshAccessToken().then(success => {
            if (success) {
                setupTokenRefresh();
            }
        });
    }
}

// Refresh access token using refresh token
async function refreshAccessToken() {
    if (!refreshToken) {
        console.log('No refresh token available');
        return false;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/auth/refresh`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                refresh_token: refreshToken
            })
        });
        
        if (response.ok) {
            const data = await response.json();
            
            // Update access token
            authToken = data.access_token;
            localStorage.setItem('authToken', authToken);
            
            // Update expiration time
            if (data.expires_in) {
                tokenExpiresAt = Date.now() + (data.expires_in * 1000);
                localStorage.setItem('tokenExpiresAt', tokenExpiresAt.toString());
            }
            
            console.log('Access token refreshed successfully');
            return true;
        } else {
            console.error('Token refresh failed:', response.status);
            // If refresh token is invalid, clear session
            if (response.status === 401) {
                console.log('Refresh token expired or invalid, clearing session');
                // Don't clear immediately - let user try to login again
                // The 30-day session should keep them logged in
            }
            return false;
        }
    } catch (error) {
        console.error('Token refresh error:', error);
        return false;
    }
}

function updateNavForLoggedInUser() {
    const loggedOutNav = document.getElementById('nav-logged-out');
    const loggedInNav = document.getElementById('nav-logged-in');
    const navAvatar = document.getElementById('nav-avatar');
    const navWelcome = document.getElementById('nav-welcome');
    
    if (currentUser) {
        // Hide logged out buttons, show logged in user info
        if (loggedOutNav) loggedOutNav.style.display = 'none';
        if (loggedInNav) loggedInNav.style.display = 'block';
        
        // Set avatar (use Gravatar if no avatar_url)
        if (navAvatar) {
            const avatarUrl = currentUser.avatar_url || getGravatarUrl(currentUser.email);
            navAvatar.src = avatarUrl;
            navAvatar.onerror = function() {
                // Fallback to Gravatar if image fails to load
                this.src = getGravatarUrl(currentUser.email);
            };
        }
        
        // Set welcome text with real name
        if (navWelcome) {
            const displayName = currentUser.real_name || currentUser.username;
            navWelcome.textContent = `Welcome, ${displayName}`;
        }
    } else {
        // Show logged out buttons, hide logged in user info
        if (loggedOutNav) loggedOutNav.style.display = 'block';
        if (loggedInNav) loggedInNav.style.display = 'none';
    }
}

function getGravatarUrl(email) {
    // Generate Gravatar URL from email
    const hash = email ? email.toLowerCase().trim() : 'default';
    // Simple hash function for Gravatar
    let hashHex = '';
    for (let i = 0; i < hash.length; i++) {
        hashHex += hash.charCodeAt(i).toString(16);
    }
    return `https://www.gravatar.com/avatar/${hashHex}?d=identicon&s=64`;
}

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

function goToDashboard() {
    if (currentUser && currentUser.role) {
        redirectToDashboard(currentUser.role);
    }
}

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

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    checkAuthStatus();
});

// API Helper Functions
async function apiRequest(endpoint, options = {}) {
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        }
    };
    
    const mergedOptions = {
        ...defaultOptions,
        ...options,
        headers: {
            ...defaultOptions.headers,
            ...options.headers
        }
    };
    
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, mergedOptions);
        
        // Check content-type before parsing
        const contentType = response.headers.get('content-type');
        let data;
        
        if (contentType && contentType.includes('application/json')) {
            data = await response.json();
        } else {
            // Handle non-JSON responses (HTML error pages, etc.)
            const text = await response.text();
            console.error('API returned non-JSON response:', response.status, response.statusText);
            console.error('Response text:', text.substring(0, 500));
            throw new Error(`API returned non-JSON response (${response.status}): ${response.statusText}`);
        }
        
        if (!response.ok) {
            throw new Error(data.message || data.error || `API request failed with status ${response.status}`);
        }
        
        return data;
    } catch (error) {
        console.error('API request error:', error);
        throw error;
    }
}

// Logout function
async function logout() {
    // Clear refresh timer
    if (tokenRefreshTimer) {
        clearTimeout(tokenRefreshTimer);
        tokenRefreshTimer = null;
    }
    
    // Call logout API to revoke tokens on server
    if (refreshToken) {
        try {
            await fetch(`${API_BASE_URL}/auth/logout`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${authToken}`
                },
                body: JSON.stringify({
                    refresh_token: refreshToken
                })
            });
        } catch (error) {
            console.error('Logout API error:', error);
        }
    }
    
    // Clear all auth data
    localStorage.removeItem('authToken');
    localStorage.removeItem('currentUser');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('tokenExpiresAt');
    authToken = null;
    currentUser = null;
    refreshToken = null;
    tokenExpiresAt = null;
    
    updateNavForLoggedInUser(); // Update nav UI
    window.location.href = 'index.html';
}

// ============================================
// Social Login Functions (OAuth)
// ============================================

// OAuth Configuration
const OAUTH_CONFIG = {
    google: {
        clientId: '', // To be configured in backend
        redirectUri: `${window.location.origin}/api/oauth/callback/google`,
        authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
        scope: 'email profile',
        responseType: 'code'
    },
    facebook: {
        clientId: '', // To be configured in backend
        redirectUri: `${window.location.origin}/api/oauth/callback/facebook`,
        authUrl: 'https://www.facebook.com/v18.0/dialog/oauth',
        scope: 'email,public_profile',
        responseType: 'code'
    },
    discord: {
        clientId: '', // To be configured in backend
        redirectUri: `${window.location.origin}/api/oauth/callback/discord`,
        authUrl: 'https://discord.com/api/oauth2/authorize',
        scope: 'identify email',
        responseType: 'code'
    },
    github: {
        clientId: '', // To be configured in backend
        redirectUri: `${window.location.origin}/api/oauth/callback/github`,
        authUrl: 'https://github.com/login/oauth/authorize',
        scope: 'user:email',
        responseType: 'code'
    }
};

/**
 * Initiate social login flow
 * @param {string} provider - The OAuth provider (google, facebook, discord)
 */
async function socialLogin(provider) {
    const config = OAUTH_CONFIG[provider];
    if (!config) {
        showNotification(`Unknown login provider: ${provider}`, 'error');
        return;
    }

    // Check if we're on the signup form by checking which tab is active
    // Note: signupForm and loginForm are global variables defined at the top of this file
    const roleSelect = document.getElementById('signup-role');
    const isSignupForm = signupForm && signupForm.classList.contains('active');
    
    console.log('OAuth Debug - signupForm:', signupForm);
    console.log('OAuth Debug - isSignupForm:', isSignupForm);
    console.log('OAuth Debug - active class:', signupForm ? signupForm.classList.contains('active') : 'N/A');
    console.log('OAuth Debug - disabled class:', signupForm ? signupForm.classList.contains('disabled') : 'N/A');
    
    // If on signup form, require role selection
    if (isSignupForm && roleSelect) {
        if (!roleSelect.value) {
            showNotification('Please select a role (Player or Broker) before signing up', 'error');
            roleSelect.focus();
            return;
        }
    }

    try {
        // Get OAuth configuration from backend
        const response = await fetch(`${API_BASE_URL}/oauth/config/${provider}`);
        
        if (response.ok) {
            const data = await response.json();
            
            if (data.enabled && data.clientId) {
                // Build OAuth URL with backend-provided client ID
                const state = generateRandomState();
                localStorage.setItem('oauth_state', state);
                localStorage.setItem('oauth_provider', provider);
                localStorage.setItem('oauth_redirect', window.location.href);
                
                // Determine form type (login or signup)
                const formType = isSignupForm ? 'signup' : 'login';
                console.log('OAuth Debug - form_type:', formType);
                
                // Get selected role (required for signup only)
                const role = (isSignupForm && roleSelect && roleSelect.value) ? roleSelect.value : 'player';
                console.log('OAuth Debug - role:', role);
                
                // Store in localStorage as backup for POST callback
                localStorage.setItem('oauth_form_type', formType);
                localStorage.setItem('oauth_role', role);
                
                // Build OAuth URL with form_type and role encoded in state
                const authUrl = buildOAuthUrl(provider, data.clientId, config, state, formType, role);
                
                // Open OAuth in a popup window for better UX
                const width = 600;
                const height = 700;
                const left = window.screenX + (window.outerWidth - width) / 2;
                const top = window.screenY + (window.outerHeight - height) / 2;
                
                const popup = window.open(
                    authUrl,
                    `${provider}_oauth`,
                    `width=${width},height=${height},left=${left},top=${top},toolbar=no,menubar=no,location=no,status=no`
                );
                
                // If popup was blocked, fall back to redirect
                if (!popup || popup.closed || typeof popup.closed === 'undefined') {
                    console.log('Popup blocked, falling back to redirect');
                    window.location.href = authUrl;
                }
            } else {
                showNotification(`${provider.charAt(0).toUpperCase() + provider.slice(1)} login is not enabled. Please contact support.`, 'error');
            }
        } else {
            // Fallback: Show notification that OAuth needs backend configuration
            showNotification(`${provider.charAt(0).toUpperCase() + provider.slice(1)} login requires backend configuration. Please use email signup.`, 'info');
        }
    } catch (error) {
        console.error('OAuth config fetch error:', error);
        showNotification(`Failed to initiate ${provider} login. Please try again.`, 'error');
    }
}

/**
 * Build OAuth authorization URL
 * @param {string} provider - OAuth provider name
 * @param {string} clientId - OAuth client ID
 * @param {object} config - OAuth configuration
 * @param {string} state - Random state for CSRF protection
 * @param {string} formType - 'login' or 'signup'
 * @param {string} role - 'player' or 'broker' (for signup)
 */
function buildOAuthUrl(provider, clientId, config, state, formType, role) {
    // Encode form_type and role in the state parameter
    // Format: base64(JSON object with state, form_type, role)
    const stateData = {
        state: state,
        form_type: formType || 'login',
        role: role || 'player'
    };
    const encodedState = btoa(JSON.stringify(stateData));
    
    const params = new URLSearchParams({
        client_id: clientId,
        redirect_uri: config.redirectUri,
        response_type: config.responseType,
        scope: config.scope,
        state: encodedState
    });

    // Add provider-specific parameters
    // Note: We don't force 'prompt=consent' to allow seamless login for returning users
    if (provider === 'google') {
        params.append('access_type', 'offline');
        // Use 'select_account' to allow account switching without forcing consent
        // Remove this line entirely for completely seamless login
        params.append('prompt', 'select_account');
    }

    return `${config.authUrl}?${params.toString()}`;
}

/**
 * Generate cryptographically secure random state
 */
function generateRandomState() {
    const array = new Uint8Array(32);
    crypto.getRandomValues(array);
    return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}

/**
 * Handle OAuth callback via postMessage (from popup window)
 */
function setupOAuthMessageListener() {
    window.addEventListener('message', async (event) => {
        // Accept messages from same origin or from the callback page
        if (!event.data || typeof event.data !== 'object') {
            return;
        }
        
        // Check for OAuth callback data
        if (event.data.success && (event.data.token || event.data.access_token)) {
            console.log('Received OAuth callback message:', event.data);
            
            // Store authentication data
            authToken = event.data.access_token || event.data.token;
            currentUser = event.data.user;
            
            // Store refresh token if provided (for persistent sessions)
            if (event.data.refresh_token) {
                refreshToken = event.data.refresh_token;
                localStorage.setItem('refreshToken', refreshToken);
            }
            
            // Store token expiration time
            if (event.data.expires_in) {
                tokenExpiresAt = Date.now() + (event.data.expires_in * 1000);
                localStorage.setItem('tokenExpiresAt', tokenExpiresAt.toString());
            }
            
            localStorage.setItem('authToken', authToken);
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            
            // Set up automatic token refresh
            setupTokenRefresh();
            
            clearOAuthState();
            
            // Use real_name if available, otherwise username
            const displayName = currentUser.real_name || currentUser.username;
            showNotification(`Welcome, ${displayName}!`, 'success');
            
            // Verify token was stored before redirecting
            console.log('OAuth: Token stored, verifying...', {
                tokenStored: localStorage.getItem('authToken') ? 'yes' : 'no',
                tokenLength: localStorage.getItem('authToken')?.length || 0
            });
            
            // Redirect to appropriate dashboard after ensuring storage is complete
            // Use a longer delay to ensure localStorage is synced
            setTimeout(() => {
                // Double-check token before redirect
                const storedToken = localStorage.getItem('authToken');
                if (storedToken) {
                    console.log('OAuth: Redirecting with valid token');
                    redirectToDashboard(currentUser.role);
                } else {
                    console.error('OAuth: Token not found in localStorage after storage!');
                    showNotification('Authentication error. Please try again.', 'error');
                }
            }, 1500);
        } else if (event.data.error) {
            console.error('OAuth error:', event.data.error);
            showNotification(event.data.error, 'error');
            clearOAuthState();
        }
    });
}

/**
 * Handle OAuth callback (called on page load if oauth_callback params present)
 * This handles the case where OAuth redirects back to the main page with code in URL
 */
async function handleOAuthCallback() {
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    const encodedState = urlParams.get('state');
    const error = urlParams.get('error');
    const storedState = localStorage.getItem('oauth_state');
    const provider = localStorage.getItem('oauth_provider');

    // Check if this is an OAuth callback
    if (!code && !error) {
        return false;
    }

    // Clean up URL
    window.history.replaceState({}, document.title, window.location.pathname);

    if (error) {
        const errorDesc = urlParams.get('error_description') || error;
        showNotification(`Login failed: ${errorDesc}`, 'error');
        clearOAuthState();
        return true;
    }

    // Decode state to get form_type and role
    let state = encodedState;
    let formType = 'login';
    let role = 'player';
    
    try {
        // Try to decode the state parameter (may be base64 encoded JSON)
        const stateData = JSON.parse(atob(encodedState));
        state = stateData.state;
        formType = stateData.form_type || 'login';
        role = stateData.role || 'player';
        console.log('OAuth Debug - Decoded state:', { state, formType, role });
    } catch (e) {
        // If decoding fails, state is not base64 encoded (legacy format)
        console.log('OAuth Debug - State not encoded, using localStorage fallback');
        formType = localStorage.getItem('oauth_form_type') || 'login';
        role = localStorage.getItem('oauth_role') || 'player';
    }

    // Verify state to prevent CSRF
    if (!state || state !== storedState) {
        showNotification('Invalid login state. Please try again.', 'error');
        clearOAuthState();
        return true;
    }

    if (!provider) {
        showNotification('Login session expired. Please try again.', 'error');
        clearOAuthState();
        return true;
    }

    try {
        showNotification('Completing login...', 'info');

        // Exchange code for token via backend
        const response = await fetch(`${API_BASE_URL}/oauth/callback/${provider}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                code: code,
                state: state,
                role: role,
                form_type: formType
            })
        });

        const data = await response.json();

        if (response.ok && data.success) {
            // Store authentication data
            authToken = data.access_token || data.token;
            currentUser = data.user;
            
            // Store refresh token if provided (for persistent sessions)
            if (data.refresh_token) {
                refreshToken = data.refresh_token;
                localStorage.setItem('refreshToken', refreshToken);
            }
            
            // Store token expiration time
            if (data.expires_in) {
                tokenExpiresAt = Date.now() + (data.expires_in * 1000);
                localStorage.setItem('tokenExpiresAt', tokenExpiresAt.toString());
            }
            
            localStorage.setItem('authToken', authToken);
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            
            // Set up automatic token refresh
            setupTokenRefresh();
            
            clearOAuthState();
            
            // Use real_name if available, otherwise username
            const displayName = currentUser.real_name || currentUser.username;
            showNotification(`Welcome, ${displayName}!`, 'success');
            
            // Redirect to appropriate dashboard
            setTimeout(() => {
                redirectToDashboard(currentUser.role);
            }, 1000);
        } else {
            showNotification(data.error || 'Login failed. Please try again.', 'error');
            clearOAuthState();
        }
    } catch (error) {
        console.error('OAuth callback error:', error);
        showNotification('An error occurred during login. Please try again.', 'error');
        clearOAuthState();
    }

    return true;
}

/**
 * Clear OAuth state from localStorage
 */
function clearOAuthState() {
    localStorage.removeItem('oauth_state');
    localStorage.removeItem('oauth_provider');
    localStorage.removeItem('oauth_redirect');
    localStorage.removeItem('oauth_role');
    localStorage.removeItem('oauth_form_type');
}

// Check for OAuth callback on page load
document.addEventListener('DOMContentLoaded', () => {
    checkAuthStatus();
    setupOAuthMessageListener();  // Listen for OAuth callback from popup
    handleOAuthCallback();
    checkForPasswordReset();
    loadOAuthConfiguration();
    loadSignupConfiguration();
    loadCurrencyConfiguration();
});

// ============================================
// Signup Configuration Loading
// ============================================

// Signup configuration - defaults to disabled for security
// These values should be loaded from the backend API
let signupConfig = {
    website_enabled: false,
    dashboard_enabled: false
};

async function loadSignupConfiguration() {
    try {
        const response = await fetch(`${API_BASE_URL}/signup-settings`);
        
        if (response.ok) {
            const data = await response.json();
            if (data.success) {
                signupConfig = data.settings;
            }
        }
    } catch (error) {
        console.error('Failed to load signup configuration:', error);
    }
    
    // Update UI based on signup settings
    updateSignupUI();
}

function updateSignupUI() {
    const signupEnabled = signupConfig.website_enabled;
    
    // Get signup-related elements
    const signupTabBtn = document.querySelector('[data-tab="signup"]');
    const signupFormDiv = document.getElementById('signup-form');
    const heroSignupBtn = document.querySelector('.hero-cta .btn-primary');
    const heroLoginBtn = document.querySelector('.hero-cta .btn-secondary');
    const ctaSignupBtn = document.querySelector('.cta-buttons .btn-primary');
    const pricingButtons = document.querySelectorAll('.pricing-card .btn');
    const navSignupBtn = document.querySelector('#nav-logged-out .btn-primary');
    
    // If signup is disabled, hide all signup buttons and change their behavior
    if (!signupEnabled) {
        // Hide signup tab from the login modal
        if (signupTabBtn) {
            signupTabBtn.style.display = 'none';
        }
        
        // Hide signup form from the login modal using class (not inline style)
        // This ensures the form won't be shown even if active class is added
        if (signupFormDiv) {
            signupFormDiv.classList.add('disabled');
        }
        
        // Change hero CTA buttons
        if (heroSignupBtn) {
            heroSignupBtn.textContent = 'Learn More';
            heroSignupBtn.onclick = () => document.getElementById('about').scrollIntoView({ behavior: 'smooth' });
        }
        
        // Change hero login button text
        if (heroLoginBtn) {
            heroLoginBtn.textContent = 'Login';
        }
        
        // Change CTA section button
        if (ctaSignupBtn) {
            ctaSignupBtn.textContent = 'Login to Play';
            ctaSignupBtn.onclick = () => showAuthModal('login');
        }
        
        // Change pricing buttons to "Contact Us"
        pricingButtons.forEach(btn => {
            btn.textContent = 'Contact Us';
            btn.onclick = () => window.location.href = 'mailto:support@townshipscombat.com';
        });
        
        // Change nav signup button
        if (navSignupBtn) {
            navSignupBtn.textContent = 'Login';
            navSignupBtn.onclick = () => showAuthModal('login');
        }
        
        // Add notice to login form about registration
        const loginFormFooter = document.querySelector('#login-form .form-footer');
        if (loginFormFooter && !document.getElementById('signup-disabled-notice')) {
            const notice = document.createElement('p');
            notice.id = 'signup-disabled-notice';
            notice.className = 'form-footer';
            notice.style.marginTop = '15px';
            notice.innerHTML = '<small class="text-muted">New user registration is currently disabled. Please contact support for assistance.</small>';
            loginFormFooter.parentNode.insertBefore(notice, loginFormFooter.nextSibling);
        }
    } else {
        // Signup is enabled - show signup tab and form in modal
        if (signupTabBtn) {
            signupTabBtn.style.display = '';
        }
        
        // Remove disabled class from signup form (visibility is controlled by .active class in CSS)
        if (signupFormDiv) {
            signupFormDiv.classList.remove('disabled');
        }
        
        // Hero signup button opens modal with signup tab
        if (heroSignupBtn) {
            heroSignupBtn.textContent = 'Join the League';
            heroSignupBtn.onclick = () => showAuthModal('signup');
        }
        
        if (heroLoginBtn) {
            heroLoginBtn.textContent = 'Login to Play';
        }
        
        // CTA button opens modal with signup tab
        if (ctaSignupBtn) {
            ctaSignupBtn.textContent = 'Get Started Now';
            ctaSignupBtn.onclick = () => showAuthModal('signup');
        }
        
        // Pricing buttons open modal with signup tab and select broker role
        pricingButtons.forEach(btn => {
            btn.textContent = 'Get Started';
            btn.onclick = () => { showAuthModal('signup'); selectBrokerRole(); };
        });
        
        // Nav signup button opens modal with signup tab
        if (navSignupBtn) {
            navSignupBtn.textContent = 'Sign Up';
            navSignupBtn.onclick = () => showAuthModal('signup');
        }
        
        // Remove signup disabled notice if exists
        const notice = document.getElementById('signup-disabled-notice');
        if (notice) {
            notice.remove();
        }
    }
}

// ============================================
// OAuth Configuration Loading
// ============================================

let oauthConfig = {
    google: { enabled: false },
    facebook: { enabled: false },
    discord: { enabled: false }
};

async function loadOAuthConfiguration() {
    try {
        const response = await fetch(`${API_BASE_URL}/oauth-config`);
        console.log('OAuth config response status:', response.status);
        
        if (response.ok) {
            const data = await response.json();
            console.log('OAuth config data:', data);
            oauthConfig = data;
            updateOAuthButtonsVisibility();
        } else {
            console.error('OAuth config response not OK:', response.status, response.statusText);
            // Default to hiding buttons if config fails to load
            oauthConfig = {
                google: { enabled: false },
                facebook: { enabled: false },
                discord: { enabled: false }
            };
            updateOAuthButtonsVisibility();
        }
    } catch (error) {
        console.error('Failed to load OAuth configuration:', error);
        // Default to hiding buttons if config fails to load
        oauthConfig = {
            google: { enabled: false },
            facebook: { enabled: false },
            discord: { enabled: false }
        };
        updateOAuthButtonsVisibility();
    }
}

function updateOAuthButtonsVisibility() {
    console.log('Updating OAuth buttons visibility with config:', oauthConfig);
    
    // Update login form buttons
    const googleLoginBtn = document.querySelector('#login-form .btn-google');
    const facebookLoginBtn = document.querySelector('#login-form .btn-facebook');
    const discordLoginBtn = document.querySelector('#login-form .btn-discord');
    
    console.log('Login buttons found:', {
        google: !!googleLoginBtn,
        facebook: !!facebookLoginBtn,
        discord: !!discordLoginBtn
    });
    
    if (googleLoginBtn) {
        const show = oauthConfig.google?.enabled ? 'flex' : 'none';
        console.log('Setting Google login button display:', show, 'enabled:', oauthConfig.google?.enabled);
        googleLoginBtn.style.display = show;
    }
    if (facebookLoginBtn) {
        facebookLoginBtn.style.display = oauthConfig.facebook?.enabled ? 'flex' : 'none';
    }
    if (discordLoginBtn) {
        discordLoginBtn.style.display = oauthConfig.discord?.enabled ? 'flex' : 'none';
    }
    
    // Update signup form buttons
    const googleSignupBtn = document.querySelector('#signup-form .btn-google');
    const facebookSignupBtn = document.querySelector('#signup-form .btn-facebook');
    const discordSignupBtn = document.querySelector('#signup-form .btn-discord');
    
    console.log('Signup buttons found:', {
        google: !!googleSignupBtn,
        facebook: !!facebookSignupBtn,
        discord: !!discordSignupBtn
    });
    
    if (googleSignupBtn) {
        const show = oauthConfig.google?.enabled ? 'flex' : 'none';
        console.log('Setting Google signup button display:', show, 'enabled:', oauthConfig.google?.enabled);
        googleSignupBtn.style.display = show;
    }
    if (facebookSignupBtn) {
        facebookSignupBtn.style.display = oauthConfig.facebook?.enabled ? 'flex' : 'none';
    }
    if (discordSignupBtn) {
        discordSignupBtn.style.display = oauthConfig.discord?.enabled ? 'flex' : 'none';
    }
    
    // Hide social dividers if no OAuth providers are enabled
    const loginDivider = document.querySelector('#login-form .social-divider');
    const signupDivider = document.querySelector('#signup-form .social-divider');
    
    const anyEnabled = oauthConfig.google?.enabled || oauthConfig.facebook?.enabled || oauthConfig.discord?.enabled;
    console.log('Any OAuth enabled:', anyEnabled);
    
    if (loginDivider) {
        loginDivider.style.display = anyEnabled ? 'flex' : 'none';
    }
    if (signupDivider) {
        signupDivider.style.display = anyEnabled ? 'flex' : 'none';
    }
}

// ============================================
// Forgot Password Functions
// ============================================

const forgotPasswordModal = document.getElementById('forgot-password-modal');
const resetPasswordModal = document.getElementById('reset-password-modal');
const forgotPasswordForm = document.getElementById('forgotPasswordForm');
const resetPasswordForm = document.getElementById('resetPasswordForm');

function showForgotPasswordModal() {
    if (forgotPasswordModal) {
        forgotPasswordModal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

function closeForgotPasswordModal() {
    if (forgotPasswordModal) {
        forgotPasswordModal.classList.remove('active');
        document.body.style.overflow = '';
    }
}

function showResetPasswordModal() {
    if (resetPasswordModal) {
        resetPasswordModal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

function closeResetPasswordModal() {
    if (resetPasswordModal) {
        resetPasswordModal.classList.remove('active');
        document.body.style.overflow = '';
    }
}

// Forgot Password Form Submission
if (forgotPasswordForm) {
    forgotPasswordForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const formData = new FormData(forgotPasswordForm);
        const email = formData.get('email');
        
        try {
            const response = await fetch(`${API_BASE_URL}/auth/forgot-password`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                showNotification(data.message || 'If an account exists with this email, a password reset link has been sent.', 'success');
                closeForgotPasswordModal();
                forgotPasswordForm.reset();
            } else {
                showNotification(data.error || 'Failed to send reset link. Please try again.', 'error');
            }
        } catch (error) {
            console.error('Forgot password error:', error);
            showNotification('An error occurred. Please try again later.', 'error');
        }
    });
}

// Reset Password Form Submission
if (resetPasswordForm) {
    resetPasswordForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const formData = new FormData(resetPasswordForm);
        const password = formData.get('password');
        const confirmPassword = formData.get('confirm_password');
        
        // Validate passwords match
        if (password !== confirmPassword) {
            showNotification('Passwords do not match.', 'error');
            return;
        }
        
        // Get token from URL
        const urlParams = new URLSearchParams(window.location.search);
        const token = urlParams.get('token');
        
        if (!token) {
            showNotification('Invalid or expired reset link.', 'error');
            return;
        }
        
        try {
            const response = await fetch(`${API_BASE_URL}/auth/reset-password`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    token: token,
                    new_password: password
                })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                showNotification('Password reset successfully! You can now log in.', 'success');
                closeResetPasswordModal();
                resetPasswordForm.reset();
                
                // Clean up URL
                window.history.replaceState({}, document.title, window.location.pathname);
                
                // Show login modal
                setTimeout(() => {
                    showAuthModal('login');
                }, 1000);
            } else {
                showNotification(data.error || 'Failed to reset password. Please try again.', 'error');
            }
        } catch (error) {
            console.error('Reset password error:', error);
            showNotification('An error occurred. Please try again later.', 'error');
        }
    });
}

// Check for password reset token in URL
function checkForPasswordReset() {
    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('token');
    
    if (token) {
        showResetPasswordModal();
    }
}

// Close modals when clicking outside
if (forgotPasswordModal) {
    forgotPasswordModal.addEventListener('click', (e) => {
        if (e.target === forgotPasswordModal) {
            closeForgotPasswordModal();
        }
    });
}

if (resetPasswordModal) {
    resetPasswordModal.addEventListener('click', (e) => {
        if (e.target === resetPasswordModal) {
            closeResetPasswordModal();
        }
    });
}

// Close modals with ESC key
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        if (forgotPasswordModal && forgotPasswordModal.classList.contains('active')) {
            closeForgotPasswordModal();
        }
        if (resetPasswordModal && resetPasswordModal.classList.contains('active')) {
            closeResetPasswordModal();
        }
    }
});

// ============================================
// Currency Configuration Loading
// ============================================

let currencyConfig = {
    code: 'USD',
    symbol: '$',
    position: 'before',
    exchange_rate: 1.0
};

async function loadCurrencyConfiguration() {
    try {
        const response = await fetch(`${API_BASE_URL}/currency-settings`);
        
        if (response.ok) {
            const data = await response.json();
            if (data.success && data.settings) {
                currencyConfig = {
                    code: data.settings.primary_currency_code || 'USD',
                    symbol: data.settings.primary_currency_symbol || '$',
                    position: data.settings.position || 'before',
                    exchange_rate: data.settings.exchange_rate || 1.0
                };
                updatePricingDisplay();
            }
        }
    } catch (error) {
        console.error('Failed to load currency configuration:', error);
        // Use defaults
    }
}

function updatePricingDisplay() {
    // Update all price amounts on the page
    const priceAmounts = document.querySelectorAll('.price-amount');
    
    priceAmounts.forEach(element => {
        const originalText = element.textContent;
        // Extract numeric value (remove currency symbols)
        const numericValue = parseFloat(originalText.replace(/[^0-9.]/g, ''));
        
        if (!isNaN(numericValue)) {
            // Convert from USD to primary currency
            const convertedValue = numericValue * currencyConfig.exchange_rate;
            
            // Format with currency symbol
            if (currencyConfig.position === 'before') {
                element.textContent = `${currencyConfig.symbol}${convertedValue.toFixed(0)}`;
            } else {
                element.textContent = `${convertedValue.toFixed(0)}${currencyConfig.symbol}`;
            }
        }
    });
    
    // Update monthly revenue in dashboard if exists
    const monthlyRevenue = document.getElementById('monthly-revenue');
    if (monthlyRevenue) {
        const currentText = monthlyRevenue.textContent;
        const numericValue = parseFloat(currentText.replace(/[^0-9.]/g, ''));
        if (!isNaN(numericValue)) {
            const convertedValue = numericValue * currencyConfig.exchange_rate;
            if (currencyConfig.position === 'before') {
                monthlyRevenue.textContent = `${currencyConfig.symbol}${convertedValue.toFixed(2)}`;
            } else {
                monthlyRevenue.textContent = `${convertedValue.toFixed(2)}${currencyConfig.symbol}`;
            }
        }
    }
}

function formatCurrency(amount, includeCode = false) {
    const convertedAmount = amount * currencyConfig.exchange_rate;
    
    let formatted;
    if (currencyConfig.position === 'before') {
        formatted = `${currencyConfig.symbol}${convertedAmount.toFixed(2)}`;
    } else {
        formatted = `${convertedAmount.toFixed(2)}${currencyConfig.symbol}`;
    }
    
    if (includeCode) {
        formatted += ` ${currencyConfig.code}`;
    }
    
    return formatted;
}

// ============================================
// Wallet Functions
// ============================================

let walletData = null;

/**
 * Get wallet data for the current user
 */
async function getWallet() {
    try {
        const response = await apiRequest('/wallet');
        if (response.success) {
            walletData = response.wallet;
            updateWalletDisplay();
            return walletData;
        }
        return null;
    } catch (error) {
        console.error('Error getting wallet:', error);
        return null;
    }
}

/**
 * Update wallet display elements on the page
 */
function updateWalletDisplay() {
    if (!walletData) return;
    
    // Update balance displays
    const balanceElements = document.querySelectorAll('[id*="balance"]');
    balanceElements.forEach(el => {
        if (el.id === 'user-balance') {
            el.textContent = `Balance: ${formatCurrency(walletData.balance)}`;
        } else if (el.id === 'account-balance') {
            el.textContent = formatCurrency(walletData.balance);
        } else if (el.id === 'available-balance') {
            el.textContent = formatCurrency(walletData.available_balance || walletData.balance);
        } else if (el.id === 'pending-balance') {
            el.textContent = formatCurrency(walletData.pending_balance || 0);
        }
    });
    
    // Update wallet-specific elements if they exist
    const walletBalance = document.getElementById('wallet-balance');
    if (walletBalance) {
        walletBalance.textContent = formatCurrency(walletData.balance);
    }
    
    const totalDeposited = document.getElementById('total-deposited');
    if (totalDeposited) {
        totalDeposited.textContent = formatCurrency(walletData.total_deposited || 0);
    }
    
    const totalWithdrawn = document.getElementById('total-withdrawn');
    if (totalWithdrawn) {
        totalWithdrawn.textContent = formatCurrency(walletData.total_withdrawn || 0);
    }
}

/**
 * Deposit funds to wallet
 */
async function depositToWallet(amount, paymentGateway = null, paymentReference = null, description = null) {
    try {
        const response = await apiRequest('/wallet/deposit', 'POST', {
            amount: parseFloat(amount),
            payment_gateway: paymentGateway,
            payment_reference: paymentReference,
            description: description
        });
        
        if (response.success) {
            walletData = response.wallet || walletData;
            updateWalletDisplay();
            showNotification(`Successfully deposited ${formatCurrency(amount)}`, 'success');
            return response;
        } else {
            showNotification(response.error || 'Deposit failed', 'error');
            return response;
        }
    } catch (error) {
        console.error('Error depositing to wallet:', error);
        showNotification('Error processing deposit', 'error');
        return { error: 'Error processing deposit' };
    }
}

/**
 * Withdraw funds from wallet
 */
async function withdrawFromWallet(amount, description = null) {
    try {
        const response = await apiRequest('/wallet/withdraw', 'POST', {
            amount: parseFloat(amount),
            description: description
        });
        
        if (response.success) {
            walletData = response.wallet || walletData;
            updateWalletDisplay();
            showNotification(`Withdrawal of ${formatCurrency(amount)} submitted`, 'success');
            return response;
        } else {
            showNotification(response.error || 'Withdrawal failed', 'error');
            return response;
        }
    } catch (error) {
        console.error('Error withdrawing from wallet:', error);
        showNotification('Error processing withdrawal', 'error');
        return { error: 'Error processing withdrawal' };
    }
}

/**
 * Get wallet transaction history
 */
async function getWalletTransactions(limit = 20, offset = 0, transactionType = null) {
    try {
        let url = `/wallet/transactions?limit=${limit}&offset=${offset}`;
        if (transactionType) {
            url += `&transaction_type=${transactionType}`;
        }
        
        const response = await apiRequest(url);
        return response;
    } catch (error) {
        console.error('Error getting transactions:', error);
        return { error: 'Error getting transactions' };
    }
}

// ============================================
// Profile Functions
// ============================================

let profileData = null;

/**
 * Get profile data for the current user
 */
async function getProfile() {
    try {
        const response = await apiRequest('/profile');
        if (response.success) {
            profileData = response.profile;
            updateProfileDisplay();
            return profileData;
        }
        return null;
    } catch (error) {
        console.error('Error getting profile:', error);
        return null;
    }
}

/**
 * Update profile display elements on the page
 */
function updateProfileDisplay() {
    if (!profileData) return;
    
    // Update username displays
    const userNameElements = document.querySelectorAll('#user-name');
    userNameElements.forEach(el => {
        el.textContent = `Welcome, ${profileData.username}`;
    });
    
    // Update profile-specific elements if they exist
    const profileUsername = document.getElementById('profile-username');
    if (profileUsername) {
        profileUsername.textContent = profileData.username;
    }
    
    const profileEmail = document.getElementById('profile-email');
    if (profileEmail) {
        profileEmail.textContent = profileData.email;
    }
    
    const currentEmail = document.getElementById('current-email');
    if (currentEmail) {
        currentEmail.value = profileData.email;
    }
    
    const profileRole = document.getElementById('profile-role');
    if (profileRole) {
        profileRole.textContent = `Role: ${profileData.role || 'Player'}`;
    }
    
    const profileMemberSince = document.getElementById('profile-member-since');
    if (profileMemberSince && profileData.created_at) {
        const date = new Date(profileData.created_at);
        profileMemberSince.textContent = `Member since: ${date.toLocaleDateString()}`;
    }
    
    const avatarImage = document.getElementById('avatar-image');
    if (avatarImage && profileData.avatar_url) {
        avatarImage.src = profileData.avatar_url;
    }
}

/**
 * Change user password
 */
async function changePassword(currentPassword, newPassword) {
    try {
        const response = await apiRequest('/profile/password', 'POST', {
            current_password: currentPassword,
            new_password: newPassword
        });
        
        if (response.success) {
            showNotification('Password changed successfully', 'success');
            return response;
        } else {
            showNotification(response.error || 'Failed to change password', 'error');
            return response;
        }
    } catch (error) {
        console.error('Error changing password:', error);
        showNotification('Error changing password', 'error');
        return { error: 'Error changing password' };
    }
}

/**
 * Request email change
 */
async function requestEmailChange(newEmail) {
    try {
        const response = await apiRequest('/profile/email', 'POST', {
            new_email: newEmail
        });
        
        if (response.success) {
            showNotification(response.message || 'Verification email sent', 'success');
            return response;
        } else {
            showNotification(response.error || 'Failed to request email change', 'error');
            return response;
        }
    } catch (error) {
        console.error('Error requesting email change:', error);
        showNotification('Error requesting email change', 'error');
        return { error: 'Error requesting email change' };
    }
}

/**
 * Verify email change with token
 */
async function verifyEmailChange(token) {
    try {
        const response = await apiRequest('/profile/email/verify', 'POST', {
            token: token
        });
        
        if (response.success) {
            showNotification('Email changed successfully', 'success');
            await getProfile(); // Refresh profile data
            return response;
        } else {
            showNotification(response.error || 'Verification failed', 'error');
            return response;
        }
    } catch (error) {
        console.error('Error verifying email change:', error);
        showNotification('Error verifying email', 'error');
        return { error: 'Error verifying email' };
    }
}

/**
 * Update user avatar
 */
async function updateAvatar(avatarData = null, avatarUrl = null) {
    try {
        const payload = {};
        if (avatarData) {
            payload.avatar_data = avatarData;
        }
        if (avatarUrl) {
            payload.avatar_url = avatarUrl;
        }
        
        const response = await apiRequest('/profile/avatar', 'POST', payload);
        
        if (response.success) {
            if (profileData) {
                profileData.avatar_url = response.avatar_url;
            }
            updateProfileDisplay();
            showNotification('Avatar updated successfully', 'success');
            return response;
        } else {
            showNotification(response.error || 'Failed to update avatar', 'error');
            return response;
        }
    } catch (error) {
        console.error('Error updating avatar:', error);
        showNotification('Error updating avatar', 'error');
        return { error: 'Error updating avatar' };
    }
}

// ============================================
// API Request Helper
// ============================================

/**
 * Make an authenticated API request
 */
async function apiRequest(endpoint, method = 'GET', data = null) {
    const token = localStorage.getItem('authToken');
    
    console.log('API Request:', {
        endpoint: endpoint,
        method: method,
        hasToken: !!token,
        tokenLength: token ? token.length : 0,
        tokenPreview: token ? token.substring(0, 30) + '...' : 'none'
    });
    
    const options = {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        }
    };
    
    if (token) {
        options.headers['Authorization'] = `Bearer ${token}`;
    }
    
    if (data && method !== 'GET') {
        options.body = JSON.stringify(data);
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, options);
        
        // Check content-type before parsing
        const contentType = response.headers.get('content-type');
        let result;
        
        if (contentType && contentType.includes('application/json')) {
            result = await response.json();
        } else {
            // Handle non-JSON responses (HTML error pages, etc.)
            const text = await response.text();
            console.error('API returned non-JSON response:', response.status, response.statusText);
            console.error('Response text:', text.substring(0, 500));
            return { error: `API returned non-JSON response (${response.status}): ${response.statusText}` };
        }
        
        // Handle token expiration
        if (response.status === 401) {
            // Try to refresh token
            const refreshed = await refreshAccessToken();
            if (refreshed) {
                // Retry the request
                options.headers['Authorization'] = `Bearer ${localStorage.getItem('authToken')}`;
                const retryResponse = await fetch(`${API_BASE_URL}${endpoint}`, options);
                
                // Check content-type for retry response too
                const retryContentType = retryResponse.headers.get('content-type');
                if (retryContentType && retryContentType.includes('application/json')) {
                    return await retryResponse.json();
                } else {
                    const retryText = await retryResponse.text();
                    console.error('API retry returned non-JSON response:', retryResponse.status);
                    return { error: 'API retry failed' };
                }
            } else {
                // Only redirect if we're on a protected page and can't refresh
                const isProtectedPage = window.location.pathname.includes('player.html') ||
                                        window.location.pathname.includes('broker.html') ||
                                        window.location.pathname.includes('profile.html') ||
                                        window.location.pathname.includes('wallet.html');
                if (isProtectedPage) {
                    localStorage.removeItem('authToken');
                    localStorage.removeItem('refreshToken');
                    window.location.href = 'index.html';
                }
                return { error: 'Authentication required' };
            }
        }
        
        return result;
    } catch (error) {
        console.error('API request error:', error);
        return { error: 'Network error' };
    }
}

/**
 * Refresh the access token
 */
async function refreshAccessToken() {
    const refreshToken = localStorage.getItem('refreshToken');
    if (!refreshToken) {
        return false;
    }
    
    try {
        const response = await fetch('/api/auth/refresh', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ refresh_token: localStorage.getItem('refreshToken') })
        });
        
        if (response.ok) {
            const data = await response.json();
            localStorage.setItem('authToken', data.access_token);
            if (data.refresh_token) {
                localStorage.setItem('refreshToken', data.refresh_token);
            }
            return true;
        }
        return false;
    } catch (error) {
        console.error('Token refresh error:', error);
        return false;
    }
}

// Initialize wallet and profile on protected pages
document.addEventListener('DOMContentLoaded', async function() {
    const token = localStorage.getItem('authToken');
    const isProtectedPage = window.location.pathname.includes('player.html') ||
                            window.location.pathname.includes('broker.html') ||
                            window.location.pathname.includes('profile.html') ||
                            window.location.pathname.includes('wallet.html');
    
    if (token && isProtectedPage) {
        await getProfile();
        await getWallet();
    }
});