document.addEventListener("DOMContentLoaded", () => {
  const form = document.querySelector(".form");

  form.addEventListener("submit", async (e) => {
    e.preventDefault();

    const username = document.querySelector("#username").value.trim();
    const password = document.querySelector("#password").value.trim();

    if (!username || !password) {
      alert("Lūdzu aizpildi visus laukus!");
      return;
    }

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

      const data = await response.json();

      if (response.ok) {
        // Save user info
        localStorage.setItem("user", JSON.stringify(data.user));

        alert("Pieslēgšanās veiksmīga!");
        window.location.href = "dashboard.html";
      } else {
        alert(data.message || "Pieslēgšanās neizdevās!");
      }
    } catch (error) {
      console.error("Kļūda:", error);
      alert("Servera kļūda. Mēģini vēlreiz vēlāk.");
    }
  });
});
