// Firebase Configuration
const firebaseConfig = {
  apiKey: "AIzaSyC2jdXkwJGqHHmJDWzm1aVZL75OujQvUvI",
  authDomain: "computero-213b5.firebaseapp.com",
  databaseURL: "https://computero-213b5-default-rtdb.firebaseio.com",
  projectId: "computero-213b5",
  storageBucket: "computero-213b5.appspot.com",
  messagingSenderId: "300084057509",
  appId: "1:300084057509:web:cc9d92f5f70a92b7b4044c"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();

// Handle Preloader
window.addEventListener('load', () => {
  const preloader = document.getElementById('preloader');
  preloader.classList.add('fade-out');
  setTimeout(() => {
    preloader.style.display = 'none';
  }, 1000);
});

// Check Authentication State
auth.onAuthStateChanged((user) => {
  if (user) {
    const email = user.email;
    let userName = email.substring(0, email.indexOf("@"));

    // Special checks for specific emails
    if (email.toLowerCase() === "dr.rayan1243@gmail.com") {
      userName = "Rayan";
    } else if (email.toLowerCase() === "sz294989@gmail.com") {
      userName = "Zain";
    } else {
      userName = userName.charAt(0).toUpperCase() + userName.slice(1);
    }

    document.getElementById("profile-name").textContent = userName;

    if (userName.toLowerCase() === "zain") {
      document.getElementById("user-page").style.display = "block";
      document.getElementById("profile-role").textContent = "Computero admin";
    } else {
      document.getElementById("profile-role").textContent = "Computero user";
    }
  } else {
    window.location.replace("/Login"); // Use replace to prevent back navigation
  }
});



// Logout Functionality
document.getElementById("log_out").addEventListener("click", () => {
  auth.signOut()
    .then(() => {
      window.location.replace("/Login"); // Redirect after logout
    })
    .catch((error) => {
      console.error("Sign out error:", error);
    });
});

// Handle Browser Back Button
window.addEventListener('popstate', () => {
  auth.onAuthStateChanged((user) => {
    if (!user) {
      window.location.replace("/Login"); // Redirect if not authenticated
    }
  });
});

// Sidebar Toggle
let sidebar = document.querySelector(".sidebar");
let closeBtn = document.querySelector("#btn");
let navList = document.querySelector(".nav-list");

closeBtn.addEventListener("click", () => {
  sidebar.classList.toggle("open");
  navList.classList.toggle("scroll");
  menuBtnChange();
});

// Update Menu Button Icon
function menuBtnChange() {
  if (sidebar.classList.contains("open")) {
    closeBtn.classList.replace("bx-menu", "bx-menu-alt-right");
  } else {
    closeBtn.classList.replace("bx-menu-alt-right", "bx-menu");
  }
}

// Clear browser history to prevent navigating back to the login page
window.history.replaceState(null, null, window.location.href);