---
// Simple test page for the new auth system
---

<html>
<head>
    <title>New Auth System Test</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .auth-form {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }
        .auth-form input {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .auth-form button {
            background: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .auth-form button:hover {
            background: #0056b3;
        }
        .auth-form button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .error {
            color: #dc3545;
            background: #f8d7da;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success {
            color: #155724;
            background: #d4edda;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .info {
            color: #0c5460;
            background: #d1ecf1;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .loading {
            text-align: center;
            padding: 20px;
        }
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 2s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 New Authentication System Test</h1>
        
        <div class="info">
            <strong>System Status:</strong> <span id="system-status">Loading...</span>
        </div>
        
        <div id="auth-status" class="info">
            <strong>Authentication Status:</strong> <span id="auth-state">Checking...</span>
        </div>
        
        <div id="user-info" style="display: none;">
            <h3>User Information</h3>
            <p><strong>Email:</strong> <span id="user-email"></span></p>
            <p><strong>Role:</strong> <span id="user-role"></span></p>
            <p><strong>Permissions:</strong> <span id="user-permissions"></span></p>
        </div>
        
        <div id="login-form" class="auth-form">
            <h3>Sign In</h3>
            <form id="signin-form">
                <input type="email" id="email" placeholder="Email" required>
                <input type="password" id="password" placeholder="Password" required>
                <button type="submit" id="signin-btn">Sign In</button>
            </form>
        </div>
        
        <div id="signup-form" class="auth-form" style="display: none;">
            <h3>Sign Up</h3>
            <form id="signup-form-el">
                <input type="email" id="signup-email" placeholder="Email" required>
                <input type="password" id="signup-password" placeholder="Password" required>
                <input type="password" id="signup-confirm" placeholder="Confirm Password" required>
                <button type="submit" id="signup-btn">Sign Up</button>
            </form>
        </div>
        
        <div id="error-display" class="error" style="display: none;"></div>
        <div id="success-display" class="success" style="display: none;"></div>
        
        <div id="actions" style="display: none;">
            <button id="signout-btn">Sign Out</button>
            <button id="toggle-forms">Toggle Sign Up</button>
        </div>
        
        <div id="loading" class="loading" style="display: none;">
            <div class="spinner"></div>
            <p>Loading...</p>
        </div>
    </div>

    <script type="module">
        // Test the new auth system
        console.log('🧪 Testing new auth system...');
        
        // Mock the auth system for testing
        const mockAuthSystem = {
            state: {
                user: null,
                session: null,
                isLoading: false,
                isAuthenticated: false,
                error: null
            },
            
            async signIn(credentials) {
                showLoading(true);
                
                // Simulate API call
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                if (credentials.email === 'test@example.com' && credentials.password === 'password123') {
                    this.state = {
                        user: {
                            id: '1',
                            email: credentials.email,
                            roleType: 'admin',
                            isActive: true,
                            emailVerified: true,
                            createdAt: new Date().toISOString(),
                            updatedAt: new Date().toISOString()
                        },
                        session: {
                            accessToken: 'mock-token',
                            refreshToken: 'mock-refresh',
                            expiresAt: Math.floor(Date.now() / 1000) + 3600
                        },
                        isLoading: false,
                        isAuthenticated: true,
                        error: null
                    };
                    
                    showLoading(false);
                    updateUI();
                    showSuccess('Sign in successful!');
                    return { user: this.state.user, session: this.state.session, error: null };
                } else {
                    showLoading(false);
                    const error = { code: 'invalid_credentials', message: 'Invalid email or password' };
                    showError(error.message);
                    return { user: null, session: null, error };
                }
            },
            
            async signUp(credentials) {
                showLoading(true);
                
                // Simulate API call
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                if (credentials.password !== credentials.confirmPassword) {
                    showLoading(false);
                    showError('Passwords do not match');
                    return { user: null, session: null, error: { code: 'password_mismatch', message: 'Passwords do not match' } };
                }
                
                showLoading(false);
                showSuccess('Account created successfully! Please sign in.');
                return { user: null, session: null, error: null };
            },
            
            async signOut() {
                showLoading(true);
                
                // Simulate API call
                await new Promise(resolve => setTimeout(resolve, 500));
                
                this.state = {
                    user: null,
                    session: null,
                    isLoading: false,
                    isAuthenticated: false,
                    error: null
                };
                
                showLoading(false);
                updateUI();
                showSuccess('Signed out successfully!');
            },
            
            hasPermission(permission) {
                if (!this.state.user) return false;
                
                const permissions = {
                    admin: ['canManageEvents', 'canManageUsers', 'canAccessAdminPanel'],
                    user: [],
                    super_admin: ['canManageEvents', 'canManageUsers', 'canAccessAdminPanel', 'canManageTerritories'],
                    territory_manager: ['canManageEvents', 'canManageTerritories']
                };
                
                return permissions[this.state.user.roleType]?.includes(permission) || false;
            }
        };
        
        // UI Helper functions
        function showLoading(show) {
            document.getElementById('loading').style.display = show ? 'block' : 'none';
        }
        
        function showError(message) {
            const errorEl = document.getElementById('error-display');
            errorEl.textContent = message;
            errorEl.style.display = 'block';
            setTimeout(() => errorEl.style.display = 'none', 5000);
        }
        
        function showSuccess(message) {
            const successEl = document.getElementById('success-display');
            successEl.textContent = message;
            successEl.style.display = 'block';
            setTimeout(() => successEl.style.display = 'none', 5000);
        }
        
        function updateUI() {
            const { user, isAuthenticated } = mockAuthSystem.state;
            
            // Update system status
            document.getElementById('system-status').textContent = 'New Auth System Loaded ✅';
            
            // Update auth status
            document.getElementById('auth-state').textContent = isAuthenticated ? 'Authenticated ✅' : 'Not Authenticated ❌';
            
            // Show/hide elements based on auth state
            document.getElementById('login-form').style.display = isAuthenticated ? 'none' : 'block';
            document.getElementById('actions').style.display = isAuthenticated ? 'block' : 'none';
            document.getElementById('user-info').style.display = isAuthenticated ? 'block' : 'none';
            
            if (user) {
                document.getElementById('user-email').textContent = user.email;
                document.getElementById('user-role').textContent = user.roleType;
                
                const permissions = [];
                ['canManageEvents', 'canManageUsers', 'canAccessAdminPanel', 'canManageTerritories'].forEach(perm => {
                    if (mockAuthSystem.hasPermission(perm)) {
                        permissions.push(perm);
                    }
                });
                
                document.getElementById('user-permissions').textContent = permissions.join(', ') || 'None';
            }
        }
        
        // Event listeners
        document.getElementById('signin-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            
            await mockAuthSystem.signIn({ email, password });
        });
        
        document.getElementById('signup-form-el').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const email = document.getElementById('signup-email').value;
            const password = document.getElementById('signup-password').value;
            const confirmPassword = document.getElementById('signup-confirm').value;
            
            await mockAuthSystem.signUp({ email, password, confirmPassword });
        });
        
        document.getElementById('signout-btn').addEventListener('click', async () => {
            await mockAuthSystem.signOut();
        });
        
        document.getElementById('toggle-forms').addEventListener('click', () => {
            const signupForm = document.getElementById('signup-form');
            const isVisible = signupForm.style.display !== 'none';
            signupForm.style.display = isVisible ? 'none' : 'block';
        });
        
        // Initialize UI
        updateUI();
        
        // Display test credentials
        console.log('📝 Test credentials:');
        console.log('Email: test@example.com');
        console.log('Password: password123');
        
        // Show info about the auth system
        const infoEl = document.createElement('div');
        infoEl.className = 'info';
        infoEl.innerHTML = `
            <h3>📋 Test Instructions</h3>
            <p><strong>Test Credentials:</strong></p>
            <ul>
                <li>Email: test@example.com</li>
                <li>Password: password123</li>
            </ul>
            <p><strong>Features to Test:</strong></p>
            <ul>
                <li>✅ Sign In/Sign Out</li>
                <li>✅ Sign Up</li>
                <li>✅ Role-based permissions</li>
                <li>✅ Error handling</li>
                <li>✅ Loading states</li>
            </ul>
        `;
        document.querySelector('.container').appendChild(infoEl);
    </script>
</body>
</html>