const passwordInput = document.getElementById("password");
const togglePassword = document.getElementById("togglePassword");
const toggleIcon = togglePassword.querySelector("i");
const loginForm = document.getElementById("loginForm");
const errorBox = document.getElementById("error");

/* 👁 Показ / скрытие пароля */
togglePassword.addEventListener("click", () => {
    const isPassword = passwordInput.type === "password";
    passwordInput.type = isPassword ? "text" : "password";

    toggleIcon.classList.toggle("bi-eye");
    toggleIcon.classList.toggle("bi-eye-slash");
});

/* 📨 Отправка формы */
loginForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    errorBox.classList.add("d-none");

    const password = passwordInput.value.trim();
    if (!password) {
        showError("Введите пароль");
        return;
    }

    try {
        const response = await fetch("/login", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ password })
        });

        const data = await response.json();

        if (data.status?.toLowerCase() === "ok") {
            window.location.href = "/";
        } else {
            showError(data.message || "Неверный пароль");
        }
    } catch {
        showError("Ошибка соединения");
    }
});

function showError(message) {
    errorBox.textContent = message;
    errorBox.classList.remove("d-none");
}