// #region PageContracts [C:2] [TYPE Interface]
// @BRIEF Contract implemented by all Svelte route pages — defines page-level behavior and routing structure.
// #endregion PageContracts

// #region NavigationContracts [C:2] [TYPE Interface]  
// @BRIEF Contract for navigation structure — sidebar sections, route categories, and menu item hierarchy.
// #endregion NavigationContracts

// #region SidebarNavigation:Module [TYPE Function]
// @SEMANTICS: navigation, sidebar, rbac, menu, filtering
// @PURPOSE: Build sidebar navigation sections and categories filtered by user permissions and feature flags.
// @LAYER UI
// @RELATION DEPENDS_ON -> [PermissionsModule]
// @RELATION BINDS_TO -> [Sidebar]
// @INVARIANT: Admin role can access all categories and subitems through permission utility.

import { hasPermission } from "$lib/auth/permissions.js";

interface NavItem {
  label: string;
  path: string;
  requiredPermission?: string;
  requiredAction?: string;
  requiredFeature?: string;
}

interface Category {
  id: string;
  label: string;
  icon: string;
  tone: string;
  path: string;
  requiredPermission?: string;
  requiredAction?: string;
  requiredFeature?: string;
  subItems: NavItem[];
}

interface Section {
  id: string;
  label: string;
  categories: Category[];
}

interface I18nNavState {
  nav?: Record<string, string>;
  [key: string]: unknown;
}

interface UserRole {
    name?: string;
    permissions?: unknown[];
}

interface User {
    roles?: UserRole[];
}

// #region isItemAllowed:Function [TYPE Function]
// @PURPOSE: Check whether a single menu node can be shown for a given user.
// @PRE: item can contain optional requiredPermission/requiredAction.
// @POST: Returns true when no permission is required or permission check passes.
function isItemAllowed(user: User | null | undefined, item: { requiredPermission?: string; requiredAction?: string }): boolean {
  if (!item?.requiredPermission) return true;
  return hasPermission(
    user,
    item.requiredPermission,
    item.requiredAction || "READ",
  );
}
// #endregion isItemAllowed:Function

// #region isFeatureEnabled:Function [TYPE Function]
function isFeatureEnabled(item: { requiredFeature?: string }, features: Record<string, boolean | undefined>): boolean {
  if (!item?.requiredFeature) return true;
  return features[item.requiredFeature] !== false;
}
// #endregion isFeatureEnabled:Function

// #region buildSidebarSections:Function [TYPE Function]
// @PURPOSE: Build translated sidebar sections with categories, filtered by RBAC permissions and feature flags.
// @PRE: i18nState provides nav labels; user can be null; features default to {} (all enabled).
// @POST: Returns only sections/categories/subitems available for provided user and enabled features.
export function buildSidebarSections(i18nState: I18nNavState, user: User | null | undefined, features: Record<string, boolean | undefined> = {}): Section[] {
  const nav = i18nState?.nav || {};

  // ── Section 1: Resources ─────────────────────────────────
  const resources: Section = {
    id: "resources",
    label: nav.section_resources,
    categories: [
      {
        id: "dashboards",
        label: nav.dashboards,
        icon: "dashboard",
        tone: "from-sky-100 to-sky-200 text-sky-700 ring-sky-200",
        path: "/dashboards",
        requiredPermission: "plugin:migration",
        requiredAction: "READ",
        subItems: [
          { label: nav.overview, path: "/dashboards", requiredPermission: "plugin:migration", requiredAction: "READ" },
          { label: nav.health_center, path: "/dashboards/health", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "health_monitor" },
        ],
      },
      {
        id: "datasets",
        label: nav.datasets,
        icon: "database",
        tone: "from-emerald-100 to-emerald-200 text-emerald-700 ring-emerald-200",
        path: "/datasets",
        requiredPermission: "plugin:migration",
        requiredAction: "READ",
        subItems: [
          { label: nav.all_datasets, path: "/datasets", requiredPermission: "plugin:migration", requiredAction: "READ" },
          { label: nav.dataset_review_workspace, path: "/datasets/review", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "dataset_review" },
        ],
      },
      {
        id: "migration",
        label: nav.migration,
        icon: "layers",
        tone: "from-orange-100 to-orange-200 text-orange-700 ring-orange-200",
        path: "/migration",
        requiredPermission: "plugin:migration",
        requiredAction: "READ",
        subItems: [
          { label: nav.migration_overview || "Overview", path: "/migration", requiredPermission: "plugin:migration", requiredAction: "READ" },
          { label: nav.migration_mappings || "Mappings", path: "/migration/mappings", requiredPermission: "plugin:migration", requiredAction: "READ" },
        ],
      },
    ],
  };

  // ── Section 2: Operations ────────────────────────────────
  const operations: Section = {
    id: "operations",
    label: nav.section_operations,
    categories: [
      {
        id: "git",
        label: nav.git,
        icon: "activity",
        tone: "from-purple-100 to-purple-200 text-purple-700 ring-purple-200",
        path: "/git",
        subItems: [
          { label: nav.git_repo_status || "Repository Status", path: "/git" },
        ],
      },
      {
        id: "translation",
        label: nav.translation,
        icon: "translate",
        tone: "from-cyan-100 to-teal-100 text-teal-700 ring-teal-200",
        path: "/translate",
        requiredPermission: "translate.job",
        requiredAction: "VIEW",
        subItems: [
          { label: nav.translation_jobs, path: "/translate", requiredPermission: "translate.job", requiredAction: "VIEW" },
          { label: nav.translation_dictionaries, path: "/translate/dictionaries", requiredPermission: "translate.dictionary", requiredAction: "VIEW" },
          { label: nav.translation_history, path: "/translate/history", requiredPermission: "translate.job", requiredAction: "VIEW" },
        ],
      },
      {
        id: "validation",
        label: nav.validation,
        icon: "activity",
        tone: "from-amber-100 to-yellow-100 text-amber-700 ring-amber-200",
        path: "/validation-tasks",
        requiredPermission: "validation.task",
        requiredAction: "VIEW",
        subItems: [
          { label: nav.validation_tasks, path: "/validation-tasks", requiredPermission: "validation.task", requiredAction: "VIEW" },
          { label: nav.validation_history, path: "/validation-tasks/history", requiredPermission: "validation.run", requiredAction: "VIEW" },
        ],
      },
      {
        id: "reports",
        label: nav.reports,
        icon: "reports",
        tone: "from-violet-100 to-fuchsia-100 text-violet-700 ring-violet-200",
        path: "/reports",
        requiredPermission: "tasks",
        requiredAction: "READ",
        subItems: [
          { label: nav.all_reports || "All Reports", path: "/reports", requiredPermission: "tasks", requiredAction: "READ" },
        ],
      },
    ],
  };

  // ── Section 3: System ────────────────────────────────────
  const system: Section = {
    id: "system",
    label: nav.section_system,
    categories: [
      {
        id: "tools",
        label: nav.tools,
        icon: "list",
        tone: "from-slate-100 to-slate-200 text-slate-700 ring-slate-200",
        path: "/tools/mapper",
        subItems: [
          { label: nav.tools_mapper, path: "/tools/mapper" },
          { label: nav.tools_debug, path: "/tools/debug" },
          { label: nav.tools_storage, path: "/tools/storage" },
          { label: nav.tools_backups, path: "/tools/backups" },
        ],
      },
      {
        id: "storage",
        label: nav.storage,
        icon: "storage",
        tone: "from-amber-100 to-amber-200 text-amber-800 ring-amber-200",
        path: "/storage",
        requiredPermission: "plugin:storage",
        requiredAction: "READ",
        subItems: [
          { label: nav.repositories, path: "/storage/repos", requiredPermission: "plugin:storage", requiredAction: "READ" },
        ],
      },
      {
        id: "admin",
        label: nav.admin,
        icon: "admin",
        tone: "from-rose-100 to-rose-200 text-rose-700 ring-rose-200",
        path: "/admin/users",
        subItems: [
          { label: nav.admin_users, path: "/admin/users", requiredPermission: "admin:users", requiredAction: "READ" },
          { label: nav.admin_roles, path: "/admin/roles", requiredPermission: "admin:roles", requiredAction: "READ" },
          { label: nav.admin_settings, path: "/admin/settings", requiredPermission: "admin:settings", requiredAction: "READ" },
          { label: nav.admin_llm, path: "/admin/settings/llm", requiredPermission: "admin:settings", requiredAction: "READ" },
        ],
      },
      {
        id: "maintenance",
        label: nav.maintenance || "Maintenance",
        icon: "activity",
        tone: "from-orange-100 to-orange-200 text-orange-700 ring-orange-200",
        path: "/maintenance",
        requiredPermission: "maintenance:write",
        requiredAction: "READ",
        subItems: [
          { label: nav.maintenance || "Maintenance", path: "/maintenance", requiredPermission: "maintenance:write", requiredAction: "READ" },
        ],
      },
    ],
  };

  const allSections = [resources, operations, system];

  // Filter by permissions and features
  return allSections
    .map((section) => ({
      ...section,
      categories: section.categories
        .map((category) => {
          const visibleSubItems = (category.subItems || []).filter(
            (sub) => isItemAllowed(user, sub) && isFeatureEnabled(sub, features),
          );
          return { ...category, subItems: visibleSubItems };
        })
        .filter((category) => {
          if (!isItemAllowed(user, category)) return false;
          return Array.isArray(category.subItems) && category.subItems.length > 0;
        }),
    }))
    .filter((section) => section.categories.length > 0);
}
// #endregion buildSidebarSections:Function

// ── Legacy adapter for backward compatibility ──────────────
// @DEPRECATED Use buildSidebarSections instead. Returns flat category list for old consumers.
export function buildSidebarCategories(i18nState: I18nNavState, user: User | null | undefined, features: Record<string, boolean | undefined> = {}): Category[] {
  const sections = buildSidebarSections(i18nState, user, features);
  return sections.flatMap((s) => s.categories);
}
// #endregion SidebarNavigation:Module
