<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Create Thyme Crunch Account</title>
  <link rel="stylesheet" th:href="@{css/create-account.css}">
</head>
<body>

<header class="top-header">
    <img 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 src="images/header_right.png" alt="Violin f-hole shape to the right of header." class="swirl">

  </header>

    <!-- 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>
  </div>
</body>
</html>

<script>
document.addEventListener("DOMContentLoaded", function () {

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

function checkPasswords() {

  if (confirmPasswordField.value === "") {
    confirmPasswordField.classList.remove("invalid");
    return;
  }

  if (passwordField.value !== confirmPasswordField.value) {
    confirmPasswordField.classList.add("invalid");
  } else {
    confirmPasswordField.classList.remove("invalid");
  }
}

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

document.getElementById("createUserForm").addEventListener("submit", function(e) {

  const password = passwordField.value;
  const confirmPassword = confirmPasswordField.value;

  if (password !== confirmPassword) {
    e.preventDefault();
    confirmPasswordField.classList.add("invalid");
    return;
  }

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

  fetch("http://localhost:8080/api/users", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(userData)
  });

  e.preventDefault();
});

});
</script>