<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KPI Analysis Dashboard - Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            padding: 40px;
            width: 100%;
            max-width: 400px;
        }
        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .login-header h1 {
            color: #333;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 10px;
        }
        .login-header .subtitle {
            color: #666;
            font-size: 14px;
        }
        .form-label {
            font-weight: 600;
            color: #333;
        }
        .form-control {
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            padding: 12px 15px;
            font-size: 14px;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .btn-login {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 8px;
            padding: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }
        .demo-credentials {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
        }
        .demo-credentials h6 {
            color: #495057;
            margin-bottom: 10px;
        }
        .alert {
            border-radius: 8px;
            margin-top: 15px;
        }
        .loading {
            display: none;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <i class="fas fa-chart-line fa-2x text-primary mb-3"></i>
            <h1>KPI Analysis Dashboard</h1>
            <p class="subtitle">Please sign in to continue</p>
        </div>
        
        <form id="loginForm">
            <div class="mb-3">
                <label for="username" class="form-label">Username</label>
                <input type="text" class="form-control" id="username" value="admin" required>
            </div>
            
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" class="form-control" id="password" value="super" required>
            </div>
            
            <button type="submit" class="btn btn-primary btn-login w-100" id="loginBtn">
                <span class="login-text">
                    <i class="fas fa-sign-in-alt me-2"></i>
                    Sign In
                </span>
                <span class="loading">
                    <i class="fas fa-spinner fa-spin me-2"></i>
                    Signing In...
                </span>
            </button>
            
            <div id="alertMessage"></div>
        </form>
        
        <div class="demo-credentials">
            <h6><i class="fas fa-info-circle me-2"></i>Demo Credentials</h6>
            <p class="mb-1"><strong>Username:</strong> admin</p>
            <p class="mb-0"><strong>Password:</strong> super</p>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('loginForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const loginBtn = document.getElementById('loginBtn');
            const loginText = loginBtn.querySelector('.login-text');
            const loading = loginBtn.querySelector('.loading');
            const alertDiv = document.getElementById('alertMessage');
            
            // Show loading state
            loginText.style.display = 'none';
            loading.style.display = 'inline';
            loginBtn.disabled = true;
            alertDiv.innerHTML = '';
            
            try {
                console.log('Attempting login...');
                const response = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password
                    })
                });
                
                const result = await response.json();
                console.log('Login response:', result);
                
                if (response.ok && result.success) {
                    // Store token and user data
                    localStorage.setItem('kpi_token', result.access_token);
                    localStorage.setItem('kpi_user', JSON.stringify(result.user));
                    
                    // Show success and redirect
                    alertDiv.innerHTML = `
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-1"></i>
                            Login successful! Redirecting...
                        </div>
                    `;
                    
                    setTimeout(() => {
                        window.location.href = '/dashboard';
                    }, 1000);
                    
                } else {
                    // Show error
                    alertDiv.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-1"></i>
                            ${result.detail || 'Invalid credentials'}
                        </div>
                    `;
                }
                
            } catch (error) {
                console.error('Login error:', error);
                alertDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-1"></i>
                        Network error. Please try again.
                    </div>
                `;
            } finally {
                // Reset button state
                loginText.style.display = 'inline';
                loading.style.display = 'none';
                loginBtn.disabled = false;
            }
        });
        
        // Check if already logged in
        const token = localStorage.getItem('kpi_token');
        if (token) {
            // Verify token is still valid
            fetch('/api/auth/me', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            }).then(response => {
                if (response.ok) {
                    // Token is valid, redirect to dashboard
                    window.location.href = '/dashboard';
                } else {
                    // Token is invalid, clear it
                    localStorage.removeItem('kpi_token');
                    localStorage.removeItem('kpi_user');
                }
            }).catch(() => {
                // Network error, clear token
                localStorage.removeItem('kpi_token');
                localStorage.removeItem('kpi_user');
            });
        }
    </script>
</body>
</html>