document.addEventListener("DOMContentLoaded", function () {
  "use strict";

  /************************************************************
   * 1) Define a static Bearer token & helper for fetch calls
   ************************************************************/
  const STATIC_BEARER_TOKEN = "50afb255cfa3a36834e0a51185b1eb09";

  /**
   * Provide headers for JSON + static bearer
   */
  function getHeaders() {
	return {
	  "Content-Type": "application/json",
	  Authorization: `Bearer ${STATIC_BEARER_TOKEN}`,
	};
  }

  /**
   * If response not OK => remove user from localStorage & redirect
   */
  function handleNotOkResponse(response) {
	console.error(`API responded with status ${response.status}: ${response.statusText}`);
	alert("Session or token invalid. Redirecting to sign in...");
	localStorage.removeItem("user");
	window.location.href = "index.html";
  }

  /**
   * If the server data indicates an error => also remove user & redirect
   * (You can tailor the condition to match your server's error messages)
   */
  function checkSessionError(data) {
	if (!data) return;
	const errStr = String(data.error || "").toLowerCase();
	if (errStr.includes("invalid") || errStr.includes("session") || errStr.includes("expired")) {
	  alert("Session or token invalid. Redirecting to sign in...");
	  localStorage.removeItem("user");
	  window.location.href = "index.html";
	}
  }

  /************************************************************
   * 2) Grab DOM references
   ************************************************************/
  const container = document.querySelector(".card-body");
  if (!container) {
	console.error("Container for the form not found!");
	return;
  }

  const emailField = document.querySelector("input[name='email']");
  const form = document.getElementById("kt_sign_up_form");
  const submitButton = document.getElementById("kt_sign_up_submit");
  let passwordMeter;

  // Grab the token from the URL
  const urlParams = new URLSearchParams(window.location.search);
  const token = urlParams.get("token");

  if (!token) {
	console.error("No token found in the URL!");
	return;
  }

  /************************************************************
   * 3) Fetch the email using the token, adding static bearer
   ************************************************************/
  fetch(`${API_BASE_URL}?api=fetch-email&token=${encodeURIComponent(token)}`, {
	method: "GET",
	headers: getHeaders(),
  })
	.then((response) => {
	  if (!response.ok) {
		handleNotOkResponse(response);
		return null; // short-circuit
	  }
	  return response.json();
	})
	.then((data) => {
	  if (!data) return; // short-circuit if null

	  // Check server's JSON for session/bearer issues
	  checkSessionError(data);

	  if (data.success) {
		emailField.value = data.email;
		emailField.setAttribute("readonly", true);
		initSignupForm(); // Initialize the signup form
	  } else {
		// Show invalid token notification
		container.innerHTML = `
		  <div class="alert alert-danger text-center" role="alert">
			<strong>Invalid Token!</strong> The verification link is invalid or has expired. 
			Please request a new verification email.
		  </div>
		`;
	  }
	})
	.catch((error) => {
	  console.error("Error fetching email:", error);
	  container.innerHTML = `
		<div class="alert alert-danger text-center" role="alert">
		  <strong>Error!</strong> An unexpected error occurred. Please try again later.
		</div>
	  `;
	});

  /************************************************************
   * 4) Setup the sign-up form (KT validation code)
   ************************************************************/
  function initSignupForm() {
	const KTSignupGeneral = (function () {
	  const validatePasswordStrength = () => passwordMeter.getScore() === 100;

	  return {
		init: function () {
		  passwordMeter = KTPasswordMeter.getInstance(
			form.querySelector('[data-kt-password-meter="true"]')
		  );

		  // Form validation setup
		  const validation = FormValidation.formValidation(form, {
			fields: {
			  email: {
				validators: {
				  regexp: {
					regexp: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
					message: "The value is not a valid email address",
				  },
				  notEmpty: {
					message: "Email address is required",
				  },
				},
			  },
			  password: {
				validators: {
				  notEmpty: {
					message: "The password is required",
				  },
				  callback: {
					message: "Please enter a valid password",
					callback: function (input) {
					  if (input.value.length > 0) return validatePasswordStrength();
					},
				  },
				},
			  },
			  "confirm-password": {
				validators: {
				  notEmpty: {
					message: "The password confirmation is required",
				  },
				  identical: {
					compare: function () {
					  return form.querySelector('input[name="password"]').value;
					},
					message: "The password and its confirm are not the same",
				  },
				},
			  },
			},
			plugins: {
			  trigger: new FormValidation.plugins.Trigger({
				event: { password: false },
			  }),
			  bootstrap: new FormValidation.plugins.Bootstrap5({
				rowSelector: ".fv-row",
				eleInvalidClass: "",
				eleValidClass: "",
			  }),
			},
		  });

		  // Handle form submission
		  submitButton.addEventListener("click", function (event) {
			event.preventDefault();

			// Validate the form
			validation.validate().then((status) => {
			  if (status === "Valid") {
				submitButton.setAttribute("data-kt-indicator", "on");
				submitButton.disabled = true;

				// Collect form data
				const email = emailField.value.trim();
				const password = form.querySelector('input[name="password"]').value.trim();

				// Submit the signup request => using static bearer
				fetch(`${API_BASE_URL}?api=signup`, {
				  method: "POST",
				  headers: getHeaders(),
				  body: JSON.stringify({ email, password }),
				})
				  .then((response) => {
					if (!response.ok) {
					  handleNotOkResponse(response);
					  return null; // short-circuit
					}
					return response.json();
				  })
				  .then((data) => {
					if (!data) return; // short-circuit if null

					checkSessionError(data);

					if (data.success) {
					  Swal.fire({
						text: "You have successfully signed up!",
						icon: "success",
						buttonsStyling: false,
						confirmButtonText: "Ok, got it!",
						customClass: { confirmButton: "btn btn-primary" },
					  }).then((result) => {
						if (result.isConfirmed) {
						  form.reset();
						  passwordMeter.reset();
						  const redirectUrl = form.getAttribute("data-kt-redirect-url");
						  if (redirectUrl) location.href = redirectUrl;
						}
					  });
					} else {
					  Swal.fire({
						text: data.error || "Signup failed. Please try again.",
						icon: "error",
						buttonsStyling: false,
						confirmButtonText: "Ok, got it!",
						customClass: { confirmButton: "btn btn-primary" },
					  });
					}
				  })
				  .catch((error) => {
					console.error("Signup error:", error);
					Swal.fire({
					  text: "An unexpected error occurred. Please try again.",
					  icon: "error",
					  buttonsStyling: false,
					  confirmButtonText: "Ok, got it!",
					  customClass: { confirmButton: "btn btn-primary" },
					});
				  })
				  .finally(() => {
					submitButton.removeAttribute("data-kt-indicator");
					submitButton.disabled = false;
				  });
			  } else {
				Swal.fire({
				  text: "Sorry, looks like there are some errors detected. Please try again.",
				  icon: "error",
				  buttonsStyling: false,
				  confirmButtonText: "Ok, got it!",
				  customClass: { confirmButton: "btn btn-primary" },
				});
			  }
			});
		  });

		  // Revalidate the password field on input
		  form.querySelector('input[name="password"]').addEventListener("input", function () {
			if (this.value.length > 0)
			  validation.updateFieldStatus("password", "NotValidated");
		  });
		},
	  };
	})();

	KTSignupGeneral.init();
  }
});