{% extends "base_auth.html" %}
{% block title %}Log In — TheNicheQuiz{% endblock %}
{% block content %}
<h1 class="auth-title">Welcome back</h1>
<p class="auth-subtitle">Log in to your niche empire</p>

<div id="auth-error" class="auth-error" style="display:none;"></div>

<form id="login-form">
    <div class="form-group">
        <label class="form-label">Email</label>
        <input type="email" name="email" id="email" class="form-input" placeholder="you@example.com" required autofocus>
    </div>
    <div class="form-group">
        <label class="form-label">Password</label>
        <input type="password" name="password" id="password" class="form-input" placeholder="Your password" required>
    </div>
    <button type="submit" class="auth-btn" id="submit-btn">Log In →</button>
</form>

<script>
document.getElementById('login-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    const btn = document.getElementById('submit-btn');
    const errDiv = document.getElementById('auth-error');
    btn.disabled = true;
    btn.textContent = 'Logging in...';
    errDiv.style.display = 'none';
    
    try {
        const resp = await fetch('/api/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                email: document.getElementById('email').value,
                password: document.getElementById('password').value
            })
        });
        const data = await resp.json();
        if (data.success) {
            window.location.href = data.redirect || '/app';
        } else {
            errDiv.textContent = data.error || 'Invalid email or password.';
            errDiv.style.display = 'block';
            btn.disabled = false;
            btn.textContent = 'Log In →';
        }
    } catch (err) {
        errDiv.textContent = 'Connection error. Please try again.';
        errDiv.style.display = 'block';
        btn.disabled = false;
        btn.textContent = 'Log In →';
    }
});
</script>
{% endblock %}

{% block footer %}
<div class="auth-footer">
    Don't have an account? <a href="/signup">Sign up free</a>
</div>
{% endblock %}
