b/**
 * EnglishSpeak — Student Login
 * Handles show/hide password toggle and form submission via fetch.
 */

document.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById("login-form");
  const toggleBtn = document.getElementById("toggle-password");
  const passwordInput = document.getElementById("password");
  const errorBox = document.getElementById("login-error");
  const submitBtn = document.getElementById("login-submit");

  // SVG icons for eye toggle
  const eyeOpen = `<svg class="eye-icon" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`;
  const eyeClosed = `<svg class="eye-icon" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>`;

  // Show / hide password
  if (toggleBtn && passwordInput) {
    // Initialize with open eye (password hidden = show eye-off? No, show eye-open to mean "click to view")
    toggleBtn.innerHTML = eyeOpen;

    toggleBtn.addEventListener("click", () => {
      const isPassword = passwordInput.type === "password";
      passwordInput.type = isPassword ? "text" : "password";
      toggleBtn.innerHTML = isPassword ? eyeClosed : eyeOpen;
    });
  }

  // Handle form submission
  if (form) {
    form.addEventListener("submit", async (e) => {
      e.preventDefault();

      // Hide any previous error
      if (errorBox) {
        errorBox.style.display = "none";
        errorBox.textContent = "";
      }

      // Disable button to prevent double-submit
      if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.textContent = "Đang đăng nhập...";
      }

      const formData = new FormData(form);

      try {
        const response = await fetch("api/student-login.php", {
          method: "POST",
          body: formData,
        });

        const data = await response.json();

        if (data.success) {
          // Redirect on success
          window.location.href = data.redirect || "student-home.php";
        } else {
          // Show error
          if (errorBox) {
            errorBox.textContent = data.message || "Đăng nhập thất bại.";
            errorBox.style.display = "block";
          }
        }
      } catch (err) {
        if (errorBox) {
          errorBox.textContent = "Lỗi kết nối. Vui lòng thử lại.";
          errorBox.style.display = "block";
        }
      } finally {
        if (submitBtn) {
          submitBtn.disabled = false;
          submitBtn.textContent = "Đăng nhập";
        }
      }
    });
  }
});