<script setup>
/**
 * Renders one column of submenu rows (links + nested toggle groups). Shared so sections can wrap it in <details>.
 */
import { ref, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useLayout } from "./composables/layout";

const props = defineProps({
  entries: { type: Array, required: true },
  parentPath: { type: String, default: "" },
});

const route = useRoute();
const router = useRouter();
const { layoutState } = useLayout();

function getItemPath(item, basePath) {
  return item.to || basePath + (item.path || "");
}

function isActive(item, basePath) {
  const itemPath = getItemPath(item, basePath);
  if (!itemPath) return false;
  const current = route.path.replace(/\/$/, "");
  const target = itemPath.replace(/\/$/, "");
  return current === target || current.startsWith(target + "/");
}

function isNestedChildActive(child, parentBasePath, index) {
  if (isActive(child, parentBasePath)) return true;
  const parentPathNorm = parentBasePath.replace(/\/$/, "");
  const current = route.path.replace(/\/$/, "");
  if (current !== parentPathNorm) return false;
  return index === 0;
}

function hasNestedItems(item) {
  return item.items && item.items.length > 0;
}

function groupKey(item) {
  return (
    item.label +
    "_" +
    (getItemPath(item, props.parentPath) || item.path || "")
  );
}

function routeUnderItem(item) {
  const itemPath = getItemPath(item, props.parentPath);
  return route.path === itemPath || route.path.startsWith(itemPath + "/");
}

const expandedGroups = ref(new Set());

function isExpanded(item) {
  return expandedGroups.value.has(groupKey(item));
}

function getFirstDescendantPath(items, basePath) {
  if (!items?.length) return null;
  const first = items[0];
  if (hasNestedItems(first)) {
    const firstChild = first.items[0];
    if (firstChild)
      return (
        firstChild.to ||
        getItemPath(first, basePath) + (firstChild.path || "")
      );
  }
  return getItemPath(first, basePath);
}

function toggleGroup(item) {
  const key = groupKey(item);
  const wasExpanded = expandedGroups.value.has(key);
  const next = new Set(expandedGroups.value);
  if (wasExpanded) next.delete(key);
  else next.add(key);
  expandedGroups.value = next;

  if (!wasExpanded) {
    const firstPath = getFirstDescendantPath(
      item.items,
      getItemPath(item, props.parentPath),
    );
    if (firstPath && route.path !== firstPath) {
      nextTick(() => router.push(firstPath).catch(() => {}));
    }
  }
}

watch(
  () => [route.path, props.entries],
  () => {
    const next = new Set(expandedGroups.value);
    props.entries?.forEach((item) => {
      if (!hasNestedItems(item)) return;
      if (routeUnderItem(item)) next.add(groupKey(item));
    });
    expandedGroups.value = next;
  },
  { immediate: true, deep: true },
);

function handleSubmenuClick() {
  layoutState.sidebarExpanded = false;
}
</script>

<template>
  <template v-for="entry in entries" :key="groupKey(entry)">
    <router-link
      v-if="!hasNestedItems(entry)"
      :to="getItemPath(entry, parentPath)"
      :class="[
        'vertical-submenu-item',
        'vertical-submenu-item--root',
        '!py-2.5',
        { active: isActive(entry, parentPath) },
      ]"
      @click="handleSubmenuClick"
    >
      <span class="vertical-submenu-label">{{ entry.label }}</span>
    </router-link>
    <div v-else class="vertical-submenu-group">
      <button
        type="button"
        :class="[
          'vertical-submenu-item',
          'vertical-submenu-item--root',
          'vertical-submenu-item--toggle',
          '!py-2.5',
          { 'vertical-submenu-item--expanded': isExpanded(entry) },
        ]"
        :aria-expanded="isExpanded(entry)"
        @click="toggleGroup(entry)"
      >
        <span class="vertical-submenu-label">{{ entry.label }}</span>
        <i
          :class="[
            'pi',
            'vertical-submenu-chevron',
            isExpanded(entry) ? 'pi-chevron-down' : 'pi-chevron-right',
          ]"
          aria-hidden="true"
        />
      </button>
      <nav
        v-show="isExpanded(entry)"
        class="vertical-submenu-nav vertical-submenu-nav--nested"
        role="list"
      >
        <router-link
          v-for="(child, childIdx) in entry.items"
          :key="child.label + '_' + (child.to || child.path)"
          :to="
            child.to || getItemPath(entry, parentPath) + (child.path || '')
          "
          :class="[
            'vertical-submenu-item',
            'vertical-submenu-item--nested',
            '!py-2.5',
            {
              active: isNestedChildActive(
                child,
                getItemPath(entry, parentPath),
                childIdx,
              ),
            },
          ]"
          @click="handleSubmenuClick"
        >
          <i
            v-if="child.icon"
            :class="child.icon"
            class="vertical-submenu-icon"
          />
          <span class="vertical-submenu-label">{{ child.label }}</span>
        </router-link>
      </nav>
    </div>
  </template>
</template>
