import { computed, ref } from "vue";

import { userRef } from "./useAuth";

/**
 * Static menu tree (Diamond-style): each item may set `permission` (Spatie string).
 * The sidebar/menu is rebuilt with `filterMenuItems` — not a backend nav API like some TLP apps.
 */
const STATIC_MENU = [
  {
    key: "root",
    label: "App",
    items: [
      {
        key: "dashboard",
        label: "Dashboard",
        icon: "pi pi-fw pi-home",
        to: "/dashboard",
      },
      {
        key: "settings",
        label: "Settings",
        icon: "pi pi-fw pi-cog",
        to: "/settings",
        description:
          "Organization, users, roles, and activity log — shown by permission.",
        pinnedBottom: true,
        items: [
          {
            key: "settings-organization",
            label: "Organization",
            to: "/settings/organization",
            icon: "pi pi-fw pi-building",
            permission: "settings.organization.view",
          },
          {
            key: "settings-users",
            label: "Users",
            to: "/settings/users",
            icon: "pi pi-fw pi-users",
            permission: "users.view",
          },
          {
            key: "settings-roles",
            label: "Roles",
            to: "/settings/roles",
            icon: "pi pi-fw pi-id-card",
            permission: "roles.view",
          },
          {
            key: "settings-activity-log",
            label: "Activity log",
            to: "/settings/activity-log",
            icon: "pi pi-fw pi-history",
            permission: "activitylog.view",
          },
        ],
      },
    ],
  },
];

/** @typedef {{ key?: string, permission?: string, items?: [], to?: string, path?: string }} NavItem */

/**
 * @param {NavItem[]|undefined} items
 * @param {string[]} perms
 */
function filterMenuItems(items, perms) {
  if (!items?.length) return [];
  /** @type {NavItem[]} */
  const result = [];
  for (const item of items) {
    if (item.permission && !perms.includes(item.permission)) continue;
    const next = { ...item };
    if (item.items?.length) {
      next.items = filterMenuItems(item.items, perms);
      if (!next.to && !next.path && !(next.items && next.items.length)) continue;
    }
    result.push(next);
  }
  return result;
}

const menu = computed(() => {
  const perms =
    Array.isArray(userRef.value?.permissions) && userRef.value?.permissions
      ? userRef.value.permissions
      : [];
  const root = STATIC_MENU[0];
  return [{ ...root, items: filterMenuItems(root.items, perms) }];
});

const loaded = ref(true);

export function useNavigation() {
  async function fetchNavigation() {
    loaded.value = true;
  }

  function resetNavigation() {
    loaded.value = false;
  }

  return {
    menu,
    loaded,
    fetchNavigation,
    resetNavigation,
  };
}
