<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta charset="UTF-8">
   	<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
   	<meta name="_csrf" th:content="${_csrf.token}"/>
    <title>Create Thyme Crunch Account</title>
    <link rel="stylesheet" th:href="@{css/create-account.css}">
    <link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
    <script th:src="@{/js/bad-words-list.js}"></script>
</head>
<body>

<div class="header-wrap">
<a th:href="@{/explore}">
<header class="top-header">
    <img th:src="@{/images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
    <h1 class="site-name">
    Thyme Crunch
    </h1>
    <img th:src="@{/images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
</header>
</a>
</div>

<div class="align-decor">
  <!-- Decor Left -->
  <img th:src="@{images/decor_left.png}" alt="Violin f-hole shape to the left of header." class="vert_swirl">

<!-- Main Content -->
<main class="main-content">
    <div class="login-box">
        <h2>Create Account</h2>

        <form id="createUserForm">
            <div class="rows">
                <label for="username">Username</label>
                <input type="text" id="username" required>
            </div>
            <div class="rows">
                <label for="email">Email</label>
                <input type="email" id="email" required>
            </div>
            <div class="rows">
                <label for="password">Password</label>
                <input type="password" id="password" required>
            </div>
            <div class="rows">
                <label for="confirmPassword">Confirm Password</label>
                <input type="password" id="confirmPassword" required>
            </div>
            <p id="passwordError"></p>

            <button type="submit">Create</button>
        </form>
    </div>
</main>

<!-- Decor Right -->
    <img th:src="@{images/decor_right.png}" alt="Violin f-hole shape to the left of header." class="vert_swirl">
    </div>

</body>
</html>

<script>

function isProfane(str) {
	  const lower = str.toLowerCase().trim();
	  return bannedWords.some(word => new RegExp(`\\b${word}\\b`).test(lower));
	}
	
	function showError(input, message) {
		  input.classList.add('invalid');

		  let error = input.parentElement.querySelector('.error-message');
		  if (!error) {
		    error = document.createElement('p');
		    error.className = 'error-message';
		    error.style.color = 'red';
		    error.style.fontSize = '0.9em';
		    error.style.marginTop = '6px';
		    input.parentElement.appendChild(error);
		  }

		  error.textContent = message;
		}
	
    document.addEventListener("DOMContentLoaded", function () {

        const form = document.getElementById("createUserForm");
        const passwordField = document.getElementById("password");
        const confirmPasswordField = document.getElementById("confirmPassword");
        const passwordError = document.getElementById("passwordError");

        function checkPasswords() {
            if (confirmPasswordField.value === "") {
                confirmPasswordField.classList.remove("invalid");
                passwordError.textContent = "Password cannot be blank";
                return;
            }
            

            if (passwordField.value !== confirmPasswordField.value) {
                confirmPasswordField.classList.add("invalid");
                passwordError.textContent = "Passwords do not match.";
            } else {
                confirmPasswordField.classList.remove("invalid");
                passwordError.textContent = "";
            }
        }

        passwordField.addEventListener("input", checkPasswords);
        confirmPasswordField.addEventListener("input", checkPasswords);

        form.addEventListener("submit", async function(e) {
            e.preventDefault();

            const password = passwordField.value;
            const confirmPassword = confirmPasswordField.value;
            const name = document.getElementById("username").value;
            const email = document.getElementById("email").value;

            if (password !== confirmPassword) {
                confirmPasswordField.classList.add("invalid");
                passwordError.textContent = "Passwords do not match.";
                return;
            }
            
            if (isProfane(document.getElementById("username").value)) {
        	    showError(username, 'Username contains inappropriate language');
        	    return;
          	}
            


            const userData = {
                username: document.getElementById("username").value,
                email: document.getElementById("email").value,
                hashedpassword: password,
                role: "ROLE_USER"
            };

            const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
            const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

            try {
                const response = await fetch("/api/users", {
                    method: "POST",
                    headers: {
                        [csrfHeader]: csrfToken,
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify(userData)
                });

                if (response.ok) {
                    passwordError.style.color = "green";
                    passwordError.textContent = "Account created successfully. Redirecting to login...";
                    setTimeout(function () {
                        window.location.href = "/login";
                    }, 1500);
                } else {
                    const errorText = await response.text();
                    passwordError.style.color = "red";
                    passwordError.textContent = "Account creation failed. Please try a different username or email.";
                    console.error("Create account failed:", errorText);
                }
            } catch (error) {
                passwordError.style.color = "red";
                passwordError.textContent = "Could not connect to the server.";
                console.error("Request error:", error);
            }
        });

    });
</script>