<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login - Chat</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      background-color: #0D0B2F; 
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      font-family: Arial, sans-serif;
    }
    .login-container {
      background-color: #ffffff;
      padding: 20px;
      border-radius: 12px;
      box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.3);
      text-align: center;
      width: 100%;
      max-width: 400px;
    }
    .login-container h2 {
      margin-bottom: 20px;
    }
    .form-group {
      margin-bottom: 15px;
      text-align: left;
    }
    .form-group label {
      display: block;
      font-size: 14px;
      margin-bottom: 5px;
    }
    .form-group input {
      width: 100%;
      padding: 10px;
      font-size: 14px;
      border: 1px solid #ccc;
      border-radius: 8px;
    }
    .form-group button {
      width: 100%;
      padding: 10px;
      background-color: #8e44ad;
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 16px;
    }
    .form-group button:hover {
      background-color: #732d91;
    }
    .error-message {
      color: red;
      font-size: 12px;
    }
  </style>
</head>
<body>
  <div class="login-container">
    <h2>Login to Chat</h2>
    <div class="form-group">
      <label for="email">Email</label>
      <input type="email" id="email" placeholder="Enter your email" />
    </div>
    <div class="form-group">
      <label for="username">Username</label>
      <input type="text" id="username" placeholder="Choose a username" />
    </div>
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" id="password" placeholder="Enter your password" />
    </div>
    <div class="form-group">
      <button id="login-button">Login / Register</button>
    </div>
    <div class="error-message" id="error-message"></div>
  </div>

  <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/10.10.0/firebase-app.js";
    import { getDatabase, ref, set, get, onValue } from "https://www.gstatic.com/firebasejs/10.10.0/firebase-database.js";

    // Configura Firebase
    const firebaseConfig = {
      apiKey: "AIzaSyBE_YtgmdjSvldxuO_1vDO3IzUqMPd6SH8",
      authDomain: "chatnet-login.firebaseapp.com",
      databaseURL: "https://chatnet-login-default-rtdb.firebaseio.com",
      projectId: "chatnet-login",
      storageBucket: "chatnet-login.appspot.com",
      messagingSenderId: "153392732064",
      appId: "1:153392732064:web:3762ceed39be67f39ef6c5",
      measurementId: "G-F57XCL7LPN"
    };

    const app = initializeApp(firebaseConfig);
    const db = getDatabase();

    // Riferimenti agli elementi
    const emailInput = document.getElementById('email');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const loginButton = document.getElementById('login-button');
    const errorMessage = document.getElementById('error-message');

    loginButton.addEventListener('click', async () => {
      const email = emailInput.value.trim();
      const username = usernameInput.value.trim();
      const password = passwordInput.value.trim();

      if (!email || !username || !password) {
        errorMessage.textContent = "All fields are required!";
        return;
      }

      try {
        const userRef = ref(db, `users/${username}`);
        const snapshot = await get(userRef);

        if (snapshot.exists()) {
          const userData = snapshot.val();

          // Controlla se l'utente è bannato
          if (userData.banned && new Date().getTime() < userData.banTimestamp) {
            window.location.href = "banned.html";
            return;
          }

          // Aggiorna il ban se è scaduto
          if (userData.banned && new Date().getTime() >= userData.banTimestamp) {
            await set(userRef, { ...userData, banned: false, banTimestamp: null });
          }
        } else {
          // Registra un nuovo utente
          await set(userRef, {
            email,
            username,
            password,
            banned: false,
            banTimestamp: null
          });
        }

        localStorage.setItem("currentUser", username);
        window.location.href = "chat.html";
      } catch (error) {
        errorMessage.textContent = "An error occurred. Please try again.";
        console.error(error);
      }
    });
  </script>
</body>
</html>
