<script setup>
/**
 * Vertical subsidebar: shows children of the currently active TOP-LEVEL parent only.
 * Items and parentPath come from layout (getActiveTopLevelParent). Root is never
 * treated as submenu parent; subsidebar renders only when active parent has children.
 * Section headers (GEBRUIKERS & RECHTEN, ALGEMEEN) are inserted client-side; headers
 * are hidden when no item in that group is visible (permission-aware).
 */
import { ref, watch, nextTick, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useLayout } from "../composables/layout/layout.js";

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

const props = defineProps({
  items: {
    type: Array,
    required: true,
  },
  parentPath: {
    type: String,
    default: "",
  },
  title: {
    type: String,
    default: "",
  },
  description: {
    type: String,
    default: null,
  },
});

/** Keys that appear at the top of the subsidebar (no section header). */
const TOP_ITEM_KEYS = ["settings-company"];

/** Subsidebar section groups (key must match backend navigation item.key). */
const SUBMENU_GROUPS = [
  {
    label: "GEBRUIKERS & RECHTEN",
    keys: ["users", "roles", "settings-groups"],
  },
  {
    label: "BEDRIJFSINSTELLINGEN",
    keys: [
      "sectors",
      "jobfunctions",
      "departments",
      "subsidy-themes",
      "subsidy-grantors",
    ],
  },
  {
    label: "PROJECTEN & TAKEN",
    keys: [
      "settings-checklists",
      "settings-default-tasks",
      "settings-default-documents",
    ],
  },
  { label: "LOG", keys: ["activity-log"] },
];

/** Flatten items: top item(s) first, then grouped sections, then remaining items. */
const entriesWithHeaders = computed(() => {
  const items = props.items ?? [];
  const result = [];
  const matchedKeys = new Set();

  // 1) Top items first (e.g. Bedrijfsgegevens)
  const topItems = items.filter(
    (it) => it && it.key && TOP_ITEM_KEYS.includes(it.key),
  );
  for (const it of topItems) {
    result.push(it);
    matchedKeys.add(it.key);
  }

  // 2) Section groups
  for (const group of SUBMENU_GROUPS) {
    const groupItems = items.filter(
      (it) => it && it.key && group.keys.includes(it.key),
    );
    if (groupItems.length === 0) continue;
    result.push({ header: true, label: group.label });
    for (const it of groupItems) {
      result.push(it);
      matchedKeys.add(it.key);
    }
  }

  // 3) Remaining items (e.g. Activiteiten)
  const rest = items.filter(
    (it) => it && (!it.key || !matchedKeys.has(it.key)),
  );
  for (const it of rest) result.push(it);
  return result;
});

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 + "/");
}

/** Nested child is active if route matches its path, or if route is exactly the parent path and this is the first child */
function isNestedChildActive(child, parentBasePath, index) {
  if (isActive(child, parentBasePath)) return true;
  const parentPath = parentBasePath.replace(/\/$/, "");
  const current = route.path.replace(/\/$/, "");
  if (current !== parentPath) 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;
  // When expanding, navigate to first descendant so that item is active (primary)
  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.items, props.parentPath],
  () => {
    const next = new Set(expandedGroups.value);
    props.items?.forEach((item) => {
      if (!hasNestedItems(item)) return;
      if (routeUnderItem(item)) next.add(groupKey(item));
    });
    expandedGroups.value = next;
  },
  { immediate: true },
);

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

<template>
  <div class="vertical-submenu flex flex-col h-full">
    <div
      v-if="title"
      class="vertical-submenu-header-card shrink-0 h-16 px-4 bg-surface-100 dark:bg-surface-800 flex flex-col justify-center"
    >
      <div
        class="text-lg font-semibold leading-tight text-surface-900 dark:text-surface-0"
      >
        {{ title }}
      </div>
      <p
        v-if="description"
        class="text-xs text-surface-500 dark:text-surface-400 mt-0.5 mb-0 leading-tight"
      >
        {{ description }}
      </p>
    </div>
    <nav class="vertical-submenu-nav flex-1 min-h-0 overflow-y-auto">
      <template
        v-for="(entry, idx) in entriesWithHeaders"
        :key="entry.header ? 'hdr_' + entry.label : groupKey(entry)"
      >
        <!-- Section header: same font/style as main sidebar (layout-menu-section-header), color for subsidebar -->
        <div
          v-if="entry.header"
          class="layout-menu-section-header vertical-submenu-section-header"
        >
          {{ entry.label }}
        </div>
        <!-- Leaf: link -->
        <router-link
          v-else-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>
        <!-- Parent with subitems: toggle only (no route) -->
        <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>
    </nav>
  </div>
</template>
