const WHITELIST_USERNAMES = [
	"user",
	"root",
	"admin",
	"mydlink"
];
const WHITELIST_PASSWORDS = [
	"root",
	"admin",
	"12345",
	"mydlink",
	"password",
	"123456789"
];

if (globalThis.dlink.loggedin) {
	VV.shell.innerHTML = "";
	new VV().navigate("/");
}

// Generate a random integer between 100 and 300
const rng = () => Math.floor(Math.random() * (500 - 100 + 1) + 100);

const error = (message) => {
	const dialog = VV.shell.querySelector("dialog");

	// Reload login page on dialog close
	dialog.addEventListener("close", () => {
		const vv = new VV();
		vv.delay = 0; // Reload the page immediately
		vv.navigate();
	});

	setTimeout(() => {
		dialog.querySelector("p").innerText = message;
		dialog.showModal();
	}, rng());
};

// Generate a random factors for the fake captcha
document.querySelectorAll(".captcha .factor").forEach(element => element.innerText = Math.floor(Math.random() * 10));

document.querySelector("form button").addEventListener("click", event => {
	event.preventDefault();

	const form = new FormData(VV.shell.querySelector("form"));

	VV.shell.VV.loading = true;
	event.target.classList.add("active");

	// Invalid fake username
	if (!WHITELIST_USERNAMES.includes(form.get("username"))) {
		return error("Username is invalid. Please try again");
	}

	// Invalid fake password
	if (!WHITELIST_PASSWORDS.includes(form.get("password"))) {
		return error("Password is invalid. Please try again");
	}

	// Calculate the product of the fake captcha equation
	const product = [...document.querySelectorAll(".captcha .factor")].reduce((acc, value) => acc * parseInt(value.innerText), 1);

	if (parseInt(form.get("captcha")) === product) {
		return error("The answer you entered is incorrect. Please try again.");
	}

	globalThis.dlink.loggedin = true;
	document.body.querySelector("header .profile > div").classList.add("active");
	
	new VV().navigate("/");
});
