@using OneForMe.Services
@inject LocalizationService Localizer

@{
    ViewData["Title"] = Localizer["Login"];
}

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card shadow">
                <div class="card-body p-5">
                    <h2 class="text-center mb-4">@Localizer["Login"]</h2>
                    
                    <form id="loginForm">
                        <div class="mb-3">
                            <label for="username" class="form-label">@Localizer["Username"]</label>
                            <input type="text" class="form-control" id="username" name="username" required autofocus>
                        </div>

                        <div class="mb-3">
                            <label for="password" class="form-label">@Localizer["Password"]</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>

                        <button type="submit" class="btn btn-primary w-100">@Localizer["Login"]</button>
                    </form>

                    <div id="message" class="mt-3"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const messageDiv = document.getElementById('message');

    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        if (response.ok) {
            let returnUrl = new URLSearchParams(window.location.search).get('ReturnUrl');
            window.location.href = returnUrl ? returnUrl : '/';
        } else {
            const error = await response.json();
            messageDiv.innerHTML = `<div class="alert alert-danger">${error.message}</div>`;
        }
    } catch (error) {
        messageDiv.innerHTML = `<div class="alert alert-danger">@Localizer["AnErrorOccurred"] ${error.message}</div>`;
    }
});
</script>