<script setup>
import { useLayout } from "../composables/layout/layout.js";
import { useSubSidebarContext } from "../composables/layout/context.js";
import { useAuth } from "../composables/useAuth.js";
import { getFirstPermittedSettingsPath } from "../composables/useSettingsNavigation.js";
import { computed, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";

const { layoutState, isCompact, shouldCollapseSidebar, isMaestroMode } =
  useLayout();
const { activateContext } = useSubSidebarContext();
const { permissions } = useAuth();
const route = useRoute();
const router = useRouter();

const props = defineProps({
  item: { type: Object, default: () => ({}) },
  root: { type: Boolean, default: true },
  parentPath: { type: String, default: null },
  /** When true (main sidebar), do not render nested children here; they appear only in the white subsidebar. */
  topLevelOnly: { type: Boolean, default: false },
});

const fullPath = computed(() => {
  if (props.item.path)
    return props.parentPath
      ? props.parentPath + props.item.path
      : props.item.path;
  if (props.item.to) return props.item.to;
  return null;
});
const isActive = computed(() => {
  const path = fullPath.value;
  if (!layoutState.activePath) return false;
  if (props.item.path)
    return (
      layoutState.activePath === path ||
      layoutState.activePath.startsWith(path + "/")
    );
  return (
    layoutState.activePath === props.item.to ||
    (path &&
      (layoutState.activePath === path ||
        layoutState.activePath.startsWith(path + "/")))
  );
});

const isLeaf = computed(() => !props.item.items?.length);
/** For top-level parents with children: link to first child so user lands on a page they can access. For Settings, use first permitted path (backend order may put company first; we use permission-aware order). */
const effectiveTo = computed(() => {
  const item = props.item;
  if (props.topLevelOnly && item.items?.length) {
    const isSettings = item.to === "/settings" || item.key === "settings";
    const isCompanies = item.to === "/companies" || item.key === "companies";
    if (isSettings) {
      const firstPermitted = getFirstPermittedSettingsPath(
        permissions.value ?? [],
      );
      if (firstPermitted) return firstPermitted;
    }
    if (isCompanies) {
      // Companies parent: always link root item to the companies index,
      // even when company-specific children are hydrated for the subsidebar.
      return item.to || "/companies";
    }
    if (item.items[0]?.to) return item.items[0].to;
  }
  return item.to ?? null;
});
const isLink = computed(
  () => effectiveTo.value && (isLeaf.value || props.topLevelOnly),
);
const tooltipLabel = computed(() => {
  const text = props.item.tooltip ?? props.item.label;
  if (!text) return null;
  // Show tooltip only when sidebar is collapsed (icon-only) in Maestro mode
  if (isMaestroMode.value && !layoutState.sidebarExpanded) return text;
  return null;
});
const showToggler = computed(
  () =>
    !props.topLevelOnly &&
    props.item.items &&
    !shouldCollapseSidebar &&
    !isMaestroMode.value,
);

function getFirstDescendantPath() {
  const item = props.item;
  const first = item.items?.[0];
  if (!first) return null;
  const firstPath = first.to || fullPath.value + (first.path || "");
  if (props.root && first.items?.length) {
    const grand = first.items[0];
    return grand.to || firstPath + (grand.path || "");
  }
  return firstPath;
}

function itemClick(event, item) {
  if (item.disabled) {
    event.preventDefault();
    return;
  }
  item.command?.({ originalEvent: event, item });

  // If this menu item is linked to a sub-sidebar context, activate it on click
  if (item.contextKey) {
    activateContext(item.contextKey);
  }

  if (!isLeaf.value) {
    event.preventDefault();
    if (isActive.value) {
      layoutState.activePath = props.parentPath ?? null;
    } else {
      layoutState.activePath = fullPath.value;
      layoutState.menuHoverActive = true;
      if (isMaestroMode.value) {
        const firstChild = item.items[0];
        layoutState.sidebarExpanded = !firstChild?.items?.length;
        const path = getFirstDescendantPath();
        if (path && route.path !== path)
          nextTick(() => router.push(path).catch(() => {}));
      }
    }
  } else {
    layoutState.overlayMenuActive = false;
    layoutState.mobileMenuActive = false;
    layoutState.menuHoverActive = false;
    layoutState.sidebarExpanded = true;
    if (isMaestroMode.value) layoutState.activePath = null;
    if (isLink.value && effectiveTo.value && route.path !== effectiveTo.value) {
      nextTick(() => {
        router.push(effectiveTo.value).catch(() => {});
      });
    }
  }
}
</script>

<template>
  <li
    :class="{
      'layout-root-menuitem': root,
      'layout-menuitem-root-link': root && (topLevelOnly || isLeaf),
      'active-menuitem': isActive,
    }"
  >
    <div
      v-if="!(root && (topLevelOnly || isLeaf))"
      class="layout-menuitem-root-text"
    >
      {{ item.label }}
    </div>
    <component
      :is="isLink ? 'router-link' : 'a'"
      v-if="item.visible !== false"
      v-tooltip.hover="tooltipLabel"
      :class="item.class"
      :to="isLink ? effectiveTo : undefined"
      :href="!isLink ? item.url || '#' : undefined"
      :target="!isLink ? item.target : undefined"
      tabindex="0"
      exact-active-class="active-route"
      @click="itemClick($event, item)"
    >
      <i :class="item.icon" class="layout-menuitem-icon" />
      <span
        class="layout-menuitem-text label-small text-inherit"
        :class="{ 'hidden-when-collapsed': shouldCollapseSidebar }"
        >{{ item.label }}</span
      >
      <i
        v-if="showToggler"
        class="pi pi-fw pi-angle-down layout-submenu-toggler"
      />
    </component>

    <ul
      v-if="
        !topLevelOnly &&
        item.items &&
        item.visible !== false &&
        (!isMaestroMode || root)
      "
      :class="{ 'layout-root-submenulist': root }"
    >
      <app-menu-item
        v-for="child in item.items"
        :key="child.label + '_' + (child.to || child.path)"
        :item="child"
        :root="false"
        :parent-path="fullPath"
      />
    </ul>
  </li>
</template>
