{% extends "base.html" %}

{% block title %}Bedrock Server Manager - Register{% endblock %}

{% block content %}
<div class="container">
    <h1>Register a new account</h1>
    <form id="register-form">
        <div class="form-group">
            <label for="username">Username</label>
            <input type="text" id="username" name="username" class="form-input" required autocomplete="username">
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" id="password" name="password" class="form-input" required autocomplete="new-password">
        </div>
        <div class="form-group">
            <label for="confirm_password">Confirm Password</label>
            <input type="password" id="confirm_password" name="confirm_password" class="form-input" required autocomplete="new-password">
        </div>
        <button type="button" class="start-button" onclick="submitForm()">Register</button>
    </form>
</div>
{% endblock %}

{% block body_scripts %}
<script>
function submitForm() {
    const form = document.getElementById('register-form');
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const confirm_password = document.getElementById('confirm_password').value;

    if (!username || !password || !confirm_password) {
        showStatusMessage('All fields are required.', 'error');
        return;
    }

    if (password !== confirm_password) {
        showStatusMessage('Passwords do not match.', 'error');
        return;
    }

    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());

    sendServerActionRequest(null, "{{ url_for('register_user', token=token) }}", 'POST', data)
        .then(response => {
            if (response && response.status === 'success') {
                window.location.href = response.redirect_url;
            }
        });
}

document.getElementById('register-form').addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        event.preventDefault();
        submitForm();
    }
});
</script>
{% endblock %}
