<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="flex items-center justify-center h-screen bg-gray-100">

  <form onsubmit="loginUser(event)" 
        class="flex flex-col bg-white p-8 rounded-lg shadow-lg w-full max-w-md space-y-4">
    <h2 class="text-2xl font-bold text-center text-gray-800">Login</h2>

    <input id="email" type="email" placeholder="Email" required
           class="px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">

    <input id="password" type="password" placeholder="Password" required
           class="px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">

    <button type="submit" 
            class="bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg font-semibold">
      Login
    </button>
  </form>

  <script>
  async function loginUser(e) {
    e.preventDefault();
    const email = document.getElementById("email").value;
    const password = document.getElementById("password").value;

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

      if (res.ok) {
        const data = await res.json();
        localStorage.setItem("token", data.access_token);

        // ✅ Redirect to dashboard only if token saved
        if (localStorage.getItem("token")) {
          window.location.href = "/logs/dashboard";
        } else {
          alert("Token save failed. Try again!");
        }
      } else {
        const errorData = await res.json().catch(() => ({}));
        alert("Login failed: " + (errorData.detail || "Invalid credentials"));
      }
    } catch (err) {
      console.error("Login error:", err);
      alert("Something went wrong. Please try again.");
    }
  }
  </script>

</body>
</html>