<template>
  <header class="topbar">
    <a class="skip-link" href="#main-content">Skip to content</a>
    <RouterLink class="profile" :to="homePath" @click="closeMenu">
      <div class="avatar" aria-hidden="true">
        <img src="@/assets/profile-avatar.jpg" alt="" />
      </div>
      <div>
        <div class="name">Brad Stein</div>
        <div class="role">{{ content.shortRole }}</div>
      </div>
    </RouterLink>

    <button
      ref="menuButton"
      class="menu-toggle"
      type="button"
      aria-controls="site-navigation"
      :aria-expanded="menuOpen ? 'true' : 'false'"
      aria-label="Toggle navigation"
      @click="toggleMenu"
    >
      <span></span>
      <span></span>
      <span></span>
    </button>

    <nav
      id="site-navigation"
      ref="navEl"
      class="links"
      :class="{ open: menuOpen }"
      aria-label="Primary navigation"
      @keydown="onNavKeydown"
    >
      <a v-for="link in sectionLinks" :key="link.href" class="nav-link" :href="link.href" @click="closeMenu">
        {{ link.label }}
      </a>
      <a class="nav-link professional-action" :href="`${homePath}#contact`" @click="closeMenu">Contact</a>

      <div class="mode-switch" aria-label="Homepage mode">
        <RouterLink
          v-for="mode in homepageModes"
          :key="mode.id"
          class="nav-link mode-link"
          :class="{ active: mode.id === currentMode }"
          :to="mode.path"
          @click="closeMenu"
        >
          {{ mode.label }}
        </RouterLink>
      </div>

      <div class="utility">
        <template v-if="!auth.ready">
          <button class="nav-link button" type="button" @click="doLogin">Login</button>
          <RouterLink class="nav-link" to="/request-access" @click="closeMenu">Register</RouterLink>
        </template>

        <template v-else-if="auth.authenticated">
          <RouterLink class="nav-link strong" :to="memberAction?.to || '/apps'" @click="closeMenu">
            {{ memberAction?.label || "Open Services" }}
          </RouterLink>
          <RouterLink class="nav-link" to="/account" @click="closeMenu">Account</RouterLink>
          <button class="nav-link button" type="button" @click="doLogout">Sign Out</button>
        </template>

        <template v-else>
          <button class="nav-link button" type="button" @click="doLogin">Login</button>
          <RouterLink class="nav-link" to="/request-access" @click="closeMenu">Register</RouterLink>
        </template>
      </div>
    </nav>
  </header>
</template>

<script setup>
import { computed, nextTick, onUnmounted, ref, watch } from "vue";
import { RouterLink, useRoute } from "vue-router";
import { auth, login, logout } from "@/auth";
import {
  homepageContentForMode,
  homepageModeFromRoute,
  homepageModes,
  homepagePathForMode,
} from "@/data/homepageContent";
import { useMemberAccessState } from "@/member/useMemberAccessState";

const { memberAction } = useMemberAccessState();
const route = useRoute();
const currentMode = computed(() => homepageModeFromRoute(route));
const content = computed(() => homepageContentForMode(currentMode.value));
const homePath = computed(() => homepagePathForMode(currentMode.value));

const sectionLinks = computed(() => [
  { label: "Work", href: `${homePath.value}#work` },
  { label: "Capabilities", href: `${homePath.value}#capabilities` },
  { label: "Platform", href: `${homePath.value}#platform` },
  { label: "Process", href: `${homePath.value}#process` },
]);

const menuOpen = ref(false);
const navEl = ref(null);
const menuButton = ref(null);

const focusableSelector = "a[href], button:not([disabled]), [tabindex]:not([tabindex='-1'])";

function closeMenu() {
  menuOpen.value = false;
}

async function toggleMenu() {
  menuOpen.value = !menuOpen.value;
  if (menuOpen.value) {
    await nextTick();
    const first = navEl.value?.querySelector(focusableSelector);
    first?.focus();
  }
}

function onWindowKeydown(event) {
  if (event.key !== "Escape" || !menuOpen.value) return;
  closeMenu();
  menuButton.value?.focus();
}

/**
 * WHY: Keep the opened mobile menu keyboard-contained and return Escape focus to the menu toggle.
 * @param {KeyboardEvent} event Navigation key event from the primary nav.
 */
function onNavKeydown(event) {
  if (event.key === "Escape") {
    closeMenu();
    menuButton.value?.focus();
    return;
  }
  if (event.key !== "Tab" || !menuOpen.value) return;

  const items = Array.from(navEl.value?.querySelectorAll(focusableSelector) || []);
  if (!items.length) return;
  const first = items[0];
  const last = items[items.length - 1];
  if (event.shiftKey && document.activeElement === first) {
    event.preventDefault();
    last.focus();
  } else if (!event.shiftKey && document.activeElement === last) {
    event.preventDefault();
    first.focus();
  }
}

const doLogout = () => {
  closeMenu();
  logout();
};

const doLogin = () => {
  closeMenu();
  login();
};

watch(menuOpen, (open) => {
  if (open) {
    window.addEventListener("keydown", onWindowKeydown);
  } else {
    window.removeEventListener("keydown", onWindowKeydown);
  }
});

onUnmounted(() => {
  window.removeEventListener("keydown", onWindowKeydown);
});
</script>

<style scoped>
.topbar {
  position: sticky;
  top: 0;
  z-index: 30;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
  padding: 12px 28px;
  background: rgba(5, 9, 20, 0.94);
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(12px);
}

.skip-link {
  position: fixed;
  top: 8px;
  left: 8px;
  transform: translateY(-140%);
  background: var(--text-strong);
  color: var(--bg-deep);
  padding: 10px 12px;
  border-radius: 8px;
  font-weight: 800;
  z-index: 60;
}

.skip-link:focus {
  transform: translateY(0);
}

.profile {
  display: flex;
  align-items: center;
  gap: 12px;
  color: inherit;
  text-decoration: none;
  min-height: 48px;
  border-radius: 10px;
}

.avatar {
  width: 44px;
  height: 44px;
  aspect-ratio: 1 / 1;
  flex-shrink: 0;
  border-radius: 50%;
  border: 1px solid rgba(255, 255, 255, 0.14);
  overflow: hidden;
  display: grid;
  place-items: center;
  background: linear-gradient(135deg, rgba(0, 229, 197, 0.5), rgba(127, 124, 255, 0.45));
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  border-radius: 50%;
}

.name {
  color: var(--text-strong);
  font-weight: 800;
}

.role {
  color: var(--text-muted);
  font-size: 13px;
}

.links {
  display: flex;
  align-items: center;
  gap: 8px;
}

.utility {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 4px;
  padding-left: 12px;
  border-left: 1px solid rgba(255, 255, 255, 0.08);
}

.mode-switch {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-left: 4px;
  padding-left: 10px;
  border-left: 1px solid rgba(255, 255, 255, 0.08);
}

.nav-link {
  min-height: 44px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--text-primary);
  font-weight: 700;
  text-decoration: none;
  padding: 9px 11px;
  border-radius: 10px;
  border: 1px solid transparent;
  white-space: nowrap;
}

.mode-link {
  min-height: 36px;
  padding: 7px 9px;
  color: var(--text-muted);
}

.mode-link.active {
  color: var(--accent-cyan);
  border-color: rgba(0, 229, 197, 0.28);
  background: rgba(0, 229, 197, 0.07);
}

.button {
  background: transparent;
  cursor: pointer;
  font: inherit;
}

.professional-action,
.nav-link.strong {
  border-color: rgba(0, 229, 197, 0.22);
  color: var(--accent-cyan);
  background: rgba(0, 229, 197, 0.06);
}

.nav-link:hover,
.nav-link:focus-visible,
.profile:focus-visible,
.button:focus-visible,
.menu-toggle:focus-visible {
  outline: 2px solid rgba(0, 229, 197, 0.72);
  outline-offset: 2px;
  border-color: rgba(255, 255, 255, 0.16);
  color: var(--accent-cyan);
}

.muted {
  color: var(--text-muted);
}

.menu-toggle {
  display: none;
  width: 44px;
  height: 44px;
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(255, 255, 255, 0.04);
  color: var(--text-strong);
  padding: 10px;
  cursor: pointer;
}

.menu-toggle span {
  display: block;
  height: 2px;
  background: currentColor;
  border-radius: 999px;
  margin: 5px 0;
}

@media (max-width: 1120px) {
  .topbar {
    padding: 12px 18px;
  }

  .menu-toggle {
    display: block;
  }

  .links {
    position: fixed;
    top: 73px;
    right: 14px;
    left: 14px;
    display: none;
    align-items: stretch;
    flex-direction: column;
    gap: 8px;
    padding: 14px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: var(--radius-sm);
    background: rgba(5, 9, 20, 0.98);
    box-shadow: var(--shadow-strong);
  }

  .links.open {
    display: flex;
  }

  .utility {
    margin-left: 0;
    padding-left: 0;
    padding-top: 10px;
    border-left: 0;
    border-top: 1px solid rgba(255, 255, 255, 0.08);
    align-items: stretch;
    flex-direction: column;
  }

  .mode-switch {
    margin-left: 0;
    padding-left: 0;
    padding-top: 10px;
    border-left: 0;
    border-top: 1px solid rgba(255, 255, 255, 0.08);
    align-items: stretch;
    flex-direction: column;
  }

  .nav-link {
    justify-content: flex-start;
    white-space: normal;
  }
}

@media (max-width: 520px) {
  .role {
    max-width: 190px;
  }
}
</style>
