import { getSession, logout } from "./api.js";

const welcomeMessage = document.getElementById("welcomeMessage");
const logoutBtn = document.getElementById("logoutBtn");
const mobilePageNavToggle = document.getElementById("mobilePageNavToggle");
const projectPageNav = document.getElementById("projectPageNav");

let mobileNavOpen = false;

function setMobileNavState(isOpen) {
  mobileNavOpen = Boolean(isOpen);
  if (!mobilePageNavToggle || !projectPageNav) return;

  projectPageNav.classList.toggle("page-nav-mobile-open", mobileNavOpen);
  mobilePageNavToggle.setAttribute("aria-expanded", mobileNavOpen ? "true" : "false");
}

function syncMobileHeader() {
  if (!mobilePageNavToggle || !projectPageNav) return;

  const isMobile = window.innerWidth <= 860;
  mobilePageNavToggle.classList.toggle("hidden", !isMobile);

  if (isMobile) {
    projectPageNav.classList.toggle("page-nav-mobile-open", mobileNavOpen);
    return;
  }

  projectPageNav.classList.remove("page-nav-mobile-open");
  mobilePageNavToggle.setAttribute("aria-expanded", "false");
  mobileNavOpen = false;
}

async function init() {
  const session = await getSession();
  const username = String(session.user?.username ?? "").toLocaleLowerCase("tr");
  if (!session.authenticated || (username !== "emir" && username !== "ece")) {
    window.location.replace("index.php");
    return;
  }

  welcomeMessage.textContent = `Hoş geldin ${session.user.username}`;

  logoutBtn?.addEventListener("click", async () => {
    try {
      await logout();
    } finally {
      window.location.replace("index.php");
    }
  });

  mobilePageNavToggle?.addEventListener("click", () => {
    setMobileNavState(!mobileNavOpen);
  });

  window.addEventListener("resize", syncMobileHeader);
  syncMobileHeader();
}

init();
