<template>
  <div class="hidden lg:flex bg-zinc-950 flex-row px-12 xl:px-48 py-5">
    <div class="grow inline-flex items-center gap-x-20">
      <NuxtLink :to="homepageURL">
        <DropWordmark class="h-8" />
      </NuxtLink>
      <nav class="inline-flex items-center">
        <ol class="inline-flex items-center gap-x-12">
          <template v-for="(nav, navIdx) in navigation" :key="navIdx">
            <!-- Community gets a hover submenu listing its sections, same
                 spot players already look for site nav, instead of only
                 being reachable by first landing on /community itself. The
                 link underneath still navigates normally on click/tap --
                 only hover (desktop) reveals the submenu. -->
            <div
              v-if="nav.prefix === '/community'"
              class="relative h-full group"
            >
              <NuxtLink
                :href="nav.route"
                :class="[
                  'transition hover:text-zinc-200 uppercase font-display font-semibold text-md',
                  navIdx === currentPageIndex
                    ? 'text-zinc-100'
                    : 'text-zinc-400',
                ]"
              >
                {{ nav.label }}
              </NuxtLink>
              <div
                class="absolute left-0 top-full pt-3 hidden group-hover:block group-focus-within:block z-50"
              >
                <PanelWidget class="flex-col gap-y-0.5 w-52">
                  <NuxtLink
                    v-for="sub in communitySubNav"
                    :key="sub.route"
                    :to="sub.route"
                    class="transition block rounded-sm px-4 py-2 text-sm font-display text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100"
                  >
                    {{ sub.label }}
                  </NuxtLink>
                </PanelWidget>
              </div>
            </div>
            <NuxtLink
              v-else
              :href="nav.route"
              :class="[
                'transition hover:text-zinc-200 uppercase font-display font-semibold text-md',
                navIdx === currentPageIndex ? 'text-zinc-100' : 'text-zinc-400',
              ]"
            >
              {{ nav.label }}
            </NuxtLink>
          </template>
        </ol>
      </nav>
    </div>
    <div class="inline-flex items-center">
      <ol class="inline-flex gap-3">
        <li>
          <!-- Social entry point: friends list, incoming requests, and a
               way into chat with a friend, matching the notifications
               bell's own Menu/MenuButton/MenuItems flyout pattern right
               next to it rather than a bare link to /community/friends. -->
          <Menu as="div" class="relative inline-block">
            <MenuButton>
              <UserHeaderWidget :notifications="incomingFriendRequestCount">
                <UserGroupIcon class="h-5" />
              </UserHeaderWidget>
            </MenuButton>

            <transition
              enter-active-class="transition ease-out duration-100"
              enter-from-class="transform opacity-0 scale-95"
              enter-to-class="transform opacity-100 scale-100"
              leave-active-class="transition ease-in duration-75"
              leave-from-class="transform opacity-100 scale-100"
              leave-to-class="transform opacity-0 scale-95"
            >
              <MenuItems
                class="absolute inset-x-0 -translate-x-1/2 top-10 z-50 w-96 focus:outline-none shadow-md"
              >
                <UserHeaderFriendsWidgetPanel :friends="friends" />
              </MenuItems>
            </transition>
          </Menu>
        </li>

        <li>
          <Menu as="div" class="relative inline-block">
            <MenuButton>
              <UserHeaderWidget :notifications="unreadNotifications.length">
                <BellIcon class="h-5" />
              </UserHeaderWidget>
            </MenuButton>

            <transition
              enter-active-class="transition ease-out duration-100"
              enter-from-class="transform opacity-0 scale-95"
              enter-to-class="transform opacity-100 scale-100"
              leave-active-class="transition ease-in duration-75"
              leave-from-class="transform opacity-100 scale-100"
              leave-to-class="transform opacity-0 scale-95"
            >
              <MenuItems
                class="absolute inset-x-0 -translate-x-1/2 top-10 z-50 w-96 focus:outline-none shadow-md"
              >
                <UserHeaderNotificationWidgetPanel
                  :notifications="unreadNotifications"
                />
              </MenuItems>
            </transition>
          </Menu>
        </li>
        <UserHeaderUserWidget />
      </ol>
    </div>
  </div>

  <div
    class="sticky lg:hidden top-0 z-40 flex h-16 justify-between items-center gap-x-4 border-b border-zinc-700 bg-zinc-950 px-4 shadow-sm sm:gap-x-6 sm:px-6 lg:px-8"
  >
    <NuxtLink :to="homepageURL">
      <DropWordmark class="mb-0.5" />
    </NuxtLink>

    <div class="flex gap-x-4 lg:gap-x-6">
      <div class="flex items-center gap-x-3">
        <!-- Profile dropdown -->
        <UserHeaderUserWidget />

        <button
          type="button"
          class="-m-2.5 p-2.5 text-zinc-400 lg:hidden"
          @click="sidebarOpen = true"
        >
          <span class="sr-only">{{ $t("header.openSidebar") }}</span>
          <Bars3Icon class="h-6 w-6" aria-hidden="true" />
        </button>
      </div>
    </div>
  </div>

  <TransitionRoot as="template" :show="sidebarOpen">
    <Dialog class="relative z-50 lg:hidden" @close="sidebarOpen = false">
      <TransitionChild
        as="template"
        enter="transition-opacity ease-linear duration-300"
        enter-from="opacity-0"
        enter-to="opacity-100"
        leave="transition-opacity ease-linear duration-300"
        leave-from="opacity-100"
        leave-to="opacity-0"
      >
        <div class="fixed inset-0 bg-zinc-900/80" />
      </TransitionChild>

      <div class="fixed inset-0 flex">
        <TransitionChild
          as="template"
          enter="transition ease-in-out duration-300 transform"
          enter-from="-translate-x-full"
          enter-to="translate-x-0"
          leave="transition ease-in-out duration-300 transform"
          leave-from="translate-x-0"
          leave-to="-translate-x-full"
        >
          <DialogPanel class="relative mr-16 flex w-full max-w-xs flex-1">
            <TransitionChild
              as="template"
              enter="ease-in-out duration-300"
              enter-from="opacity-0"
              enter-to="opacity-100"
              leave="ease-in-out duration-300"
              leave-from="opacity-100"
              leave-to="opacity-0"
            >
              <div
                class="absolute left-full top-0 flex w-16 justify-center pt-5"
              >
                <button
                  type="button"
                  class="-m-2.5 p-2.5"
                  @click="sidebarOpen = false"
                >
                  <span class="sr-only">{{
                    $t("userHeader.closeSidebar")
                  }}</span>
                  <XMarkIcon class="h-6 w-6 text-zinc-400" aria-hidden="true" />
                </button>
              </div>
            </TransitionChild>
            <!-- Sidebar component, swap this element with another sidebar if you like -->
            <div
              class="flex grow flex-col gap-y-5 overflow-y-auto bg-zinc-950 px-6 pb-4"
            >
              <div class="flex shrink-0 h-16 items-center justify-between">
                <NuxtLink :to="homepageURL">
                  <ApplicationLogo class="h-8 w-auto" />
                </NuxtLink>

                <UserHeaderUserWidget />
              </div>
              <nav class="flex flex-1 flex-col gap-y-8">
                <ol class="flex flex-col gap-y-3">
                  <template v-for="(nav, navIdx) in navigation" :key="navIdx">
                    <NuxtLink
                      :href="nav.route"
                      :class="[
                        'transition hover:text-zinc-200 uppercase font-display font-semibold text-md',
                        navIdx === currentPageIndex
                          ? 'text-zinc-100'
                          : 'text-zinc-400',
                      ]"
                    >
                      {{ nav.label }}
                    </NuxtLink>
                    <!-- No hover on touch, so the mobile sidebar lists
                         Community's sections inline instead of behind a
                         hover flyout. -->
                    <div
                      v-if="nav.prefix === '/community'"
                      class="flex flex-col gap-y-2 pl-4 border-l border-zinc-800"
                    >
                      <NuxtLink
                        v-for="sub in communitySubNav"
                        :key="sub.route"
                        :to="sub.route"
                        class="transition hover:text-zinc-200 font-display font-semibold text-sm text-zinc-500"
                      >
                        {{ sub.label }}
                      </NuxtLink>
                    </div>
                  </template>
                </ol>
                <div class="h-px w-full bg-zinc-700" />
                <div class="flex flex-row gap-x-4 justify-stretch">
                  <li class="w-full">
                    <NuxtLink to="/community/friends" class="block w-full">
                      <UserHeaderWidget
                        class="w-full"
                        :notifications="incomingFriendRequestCount"
                      >
                        <UserGroupIcon class="h-5" />
                      </UserHeaderWidget>
                    </NuxtLink>
                  </li>
                  <li class="w-full">
                    <UserHeaderWidget
                      class="w-full"
                      :notifications="unreadNotifications.length"
                    >
                      <BellIcon class="h-5" />
                    </UserHeaderWidget>
                  </li>
                  <li class="w-full">
                    <UserHeaderWidget class="w-full" />
                  </li>
                </div>
              </nav>
            </div>
          </DialogPanel>
        </TransitionChild>
      </div>
    </Dialog>
  </TransitionRoot>
</template>

<script setup lang="ts">
import { BellIcon, UserGroupIcon } from "@heroicons/vue/16/solid";
import {
  Dialog,
  DialogPanel,
  TransitionChild,
  TransitionRoot,
  Menu,
  MenuButton,
  MenuItems,
} from "@headlessui/vue";
import type { NavigationItem } from "../composables/types";
import { Bars3Icon } from "@heroicons/vue/24/outline";
import { XMarkIcon } from "@heroicons/vue/24/solid";

const router = useRouter();
const { t } = useI18n();

const homepageURL = "/store";
const navigation: Ref<Array<NavigationItem>> = computed(() => [
  {
    prefix: "/store",
    route: "/store",
    label: t("store.title"),
  },
  {
    prefix: "/library",
    route: "/library",
    label: t("userHeader.links.library"),
  },
  {
    prefix: "/community",
    route: "/community",
    label: t("userHeader.links.community"),
  },
  {
    prefix: "/news",
    route: "/news",
    label: t("userHeader.links.news"),
  },
]);

const currentPageIndex = useCurrentNavigationIndex(navigation.value);

// Community submenu -- the sections the user asked to have reachable from
// the main nav (Friends, Chat, Devices, Mods at minimum; Servers, Issues,
// and Achievements fit the exact same "one page per community feature"
// pattern so they're included too). A plain list, not NavigationItem[]:
// these are never the "current top-level section" for the prefix-matching
// highlighter above, they're always rendered as a flat submenu.
const communitySubNav = computed(() => [
  { route: "/community/friends", label: t("community.friends.title") },
  { route: "/community/chat", label: t("community.chat.title") },
  { route: "/community/devices", label: t("community.devices.title") },
  { route: "/community/mods", label: t("community.mods.title") },
  { route: "/community/servers", label: t("community.servers.title") },
  { route: "/community/issues", label: t("community.issues.title") },
  {
    route: "/community/achievements",
    label: t("community.achievements.title"),
  },
]);

const notifications = useNotifications();
const unreadNotifications = computed(() =>
  notifications.value.filter((e) => !e.read),
);

// Friends widget (people icon) -- fetched on mount rather than at module
// scope like notifications' websocket, since this is a plain request that
// only makes sense once a signed-in user exists. Re-fetched on every
// "friend.request" event (new request, accept, decline) the same way
// pages/community/friends.vue already does, so the header badge and any
// open flyout both stay live without a page reload.
const user = useUser();
const friends = useCommunityFriends();
const incomingFriendRequestCount = computed(
  () => friends.value?.incomingRequests.length ?? 0,
);

onMounted(() => {
  if (user.value) refreshCommunityFriends();
});

const communityChat = useCommunityChatSocket();
communityChat.on((envelope) => {
  if (envelope.t === "friend.request" && user.value) refreshCommunityFriends();
});

const sidebarOpen = ref(false);
router.afterEach(() => (sidebarOpen.value = false));
</script>
