<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Puzzle - Your Creative Writing Hub</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
        <link rel="stylesheet" href="/static/css/style.css">
    </head>
<body class="bg-light">
    <div class="container mt-5">
        <h2 class="text-center">Register</h2>
        <form id="registerForm">
            <div class="mb-3">
                <label for="username" class="form-label">Username</label>
                <input type="text" class="form-control" id="username" name="username" required>
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">Email</label>
                <input type="text" class="form-control" id="email" name="email" required>
            </div>
            <div class="mb-3">
                <label for="phone_number" class="form-label">Phone Number</label>
                <input type="number" class="form-control" id="phone_number" name="phone_number" required>
            </div>
            <div id="message" class="mb-3"></div>
            <button type="submit" class="btn btn-primary w-100">Register</button>
        </form>
        <div class="mt-3 text-center">
            <a href="/login">Already have an account? Login here.</a>
        </div>
    </div>

    <script>
    document.getElementById('registerForm').addEventListener('submit', async function (e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        const messageDiv = document.getElementById('message');
        messageDiv.innerHTML = ''; // clear old messages

        try {
            const response = await fetch('/confirm-register', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (!response.ok) {
                messageDiv.innerHTML = `<div class="alert alert-danger">${result.error || 'Registration failed.'}</div>`;
            } else {
                // Registration successful, redirect to home page where password will be shown
                if (result.redirect) {
                    window.location.href = result.redirect;
                }
            }
        } catch (err) {
            messageDiv.innerHTML = `<div class="alert alert-danger">Error connecting to server.</div>`;
        }
    });
    </script>
</body>
</html>
