---
import { getCollection } from "astro:content";
import { ui } from "../../i18n/ui";
import SidebarComponent from "./Sidebar";
import { LATEST_VERSION } from "../../config/versions";

const version = Astro.params.version || LATEST_VERSION.id;
const locale = Astro.params.locale;

const allDocs = await getCollection("docs");
// Filter docs by version and locale: docs are organized as version/locale/...
const docs = allDocs.filter((doc) => {
  const parts = doc.id.split("/");
  return parts[0] === version && parts[1] === locale;
});

interface TreeNode {
  name: string;
  type: "file" | "folder";
  children: TreeNode[];
  doc?: any;
  path: string[];
  id: string;
}

function buildTree(docs: any[]): TreeNode[] {
  const root: TreeNode[] = [];

  docs.forEach((doc) => {
    // doc.id is now version/locale/...path, so skip first 2 parts (version and locale)
    const pathParts = doc.id.split("/").slice(2);
    let currentLevel = root;

    pathParts.forEach((part: string, index: number) => {
      const isFile = index === pathParts.length - 1;
      const existing = currentLevel.find((node) => node.name === part);

      if (existing) {
        if (isFile) {
          existing.doc = doc;
        }
        currentLevel = existing.children;
      } else {
        const newNode: TreeNode = {
          name: part,
          type: isFile ? "file" : "folder",
          children: [],
          path: pathParts.slice(0, index + 1),
          id: pathParts.slice(0, index + 1).join("/"),
          ...(isFile && { doc }),
        };
        currentLevel.push(newNode);
        currentLevel = newNode.children;
      }
    });
  });

  // Sort the tree for consistent ordering
  const sortTree = (nodes: TreeNode[]): TreeNode[] => {
    const sorted = nodes.sort((a, b) => {
      // First sort by type: files before folders
      if (a.type !== b.type) {
        return a.type === "file" ? -1 : 1;
      }

      // For files only - custom ordering
      if (a.type === "file" && b.type === "file") {
        // Get parent folder to determine which order to use
        const parentPath = a.path[a.path.length - 2];

        // Custom order for decocms top-level pages
        if (parentPath === "studio") {
          // NOTE: doc IDs do not include ".mdx" (e.g. "overview", not "overview.mdx")
          // Order follows: Quickstart → Overview → Core Concepts → Working with MCP → Monitoring → User Management → Reference

          // Version-aware ordering
          const studioFolderOrder =
            version === LATEST_VERSION.id
              ? [
                  // Latest version structure
                  "overview",
                  "quickstart",
                  "concepts",
                  "architecture",
                  "agents",
                  "connections",
                  "automations",
                  "monitoring",
                  "ai-providers",
                  "buckets",
                  "library",
                  "digital-experience",
                  "agentic-cms",
                  "store",
                  "api-keys",
                  "secrets",
                  "user-management",
                  "api-reference",
                ]
              : [
                  // Previous version structure
                  "overview",
                  "quickstart",
                  "concepts",
                  "connect-clients",
                  "authentication",
                  "authorization-and-roles",
                  "mcp-servers",
                  "mcp-gateways",
                  "api-keys",
                  "monitoring",
                  "api-reference",
                ];

          const aIndex = studioFolderOrder.indexOf(a.name);
          const bIndex = studioFolderOrder.indexOf(b.name);
          if (aIndex !== -1 && bIndex !== -1) {
            return aIndex - bIndex;
          }
          if (aIndex !== -1) return -1;
          if (bIndex !== -1) return 1;
        }

        // Custom order for decopilot subfolder
        if (parentPath === "decopilot") {
          const decopilotOrder = ["overview", "context-and-tasks", "tools"];
          const aIndex = decopilotOrder.indexOf(a.name);
          const bIndex = decopilotOrder.indexOf(b.name);
          if (aIndex !== -1 && bIndex !== -1) {
            return aIndex - bIndex;
          }
          if (aIndex !== -1) return -1;
          if (bIndex !== -1) return 1;
        }

        // Custom order for no-code-guides files
        if (parentPath === "no-code-guides") {
          const noCodeOrder = ["creating-tools", "creating-agents"];
          const aIndex = noCodeOrder.indexOf(a.name);
          const bIndex = noCodeOrder.indexOf(b.name);
          if (aIndex !== -1 && bIndex !== -1) {
            return aIndex - bIndex;
          }
          if (aIndex !== -1) return -1;
          if (bIndex !== -1) return 1;
        }

        // Custom order for full-code-guides files
        if (parentPath === "full-code-guides") {
          const fullCodeOrder = [
            "project-structure",
            "building-tools",
            "building-views",
            "resources",
            "deployment",
          ];
          const aIndex = fullCodeOrder.indexOf(a.name);
          const bIndex = fullCodeOrder.indexOf(b.name);
          if (aIndex !== -1 && bIndex !== -1) {
            return aIndex - bIndex;
          }
          if (aIndex !== -1) return -1;
          if (bIndex !== -1) return 1;
        }

        // Custom order for self-hosting section
        if (parentPath === "self-hosting") {
          const selfHostingOrder = ["quickstart", "authentication"];
          const aIndex = selfHostingOrder.indexOf(a.name);
          const bIndex = selfHostingOrder.indexOf(b.name);
          if (aIndex !== -1 && bIndex !== -1) {
            return aIndex - bIndex;
          }
          if (aIndex !== -1) return -1;
          if (bIndex !== -1) return 1;
        }

        // Custom order for api-reference section
        if (parentPath === "api-reference") {
          const apiRefOrder = [
            "connection-proxy",
            "external-agent-integration",
          ];
          const aIndex = apiRefOrder.indexOf(a.name);
          const bIndex = apiRefOrder.indexOf(b.name);
          if (aIndex !== -1 && bIndex !== -1) {
            return aIndex - bIndex;
          }
          if (aIndex !== -1) return -1;
          if (bIndex !== -1) return 1;
        }

        // Custom order for deploy docs (now under self-hosting)
        const rootPath = a.path[0];
        if (rootPath === "studio" && parentPath === "deploy") {
          // Version-aware deploy file names
          const deployOrder =
            version === LATEST_VERSION.id
              ? ["docker-compose", "kubernetes"]
              : ["local-docker-compose", "kubernetes-helm-chart"];
          const aIndex = deployOrder.indexOf(a.name);
          const bIndex = deployOrder.indexOf(b.name);
          if (aIndex !== -1 && bIndex !== -1) {
            return aIndex - bIndex;
          }
          if (aIndex !== -1) return -1;
          if (bIndex !== -1) return 1;
        }
      }

      // For folders - custom ordering
      if (a.type === "folder" && b.type === "folder") {
        const folderOrder: Record<string, number> = {
          // Order follows improved information architecture
          studio: 0, // decocms docs (main product)
          "getting-started": 1, // Getting Started (after intro)
          decopilot: 3, // Decopilot (elevated section within studio)
          "self-hosting": 4, // Self-hosting section
          deploy: 5, // Deploy section (under self-hosting)
          "no-code-guides": 6, // Legacy admin guides
          "full-code-guides": 7, // Legacy admin guides
        };

        const aOrder = folderOrder[a.name] ?? Number.POSITIVE_INFINITY;
        const bOrder = folderOrder[b.name] ?? Number.POSITIVE_INFINITY;
        if (aOrder !== bOrder) return aOrder - bOrder;
      }

      // Default alphabetical
      return a.name.localeCompare(b.name);
    });

    return sorted.map((node) => ({
      ...node,
      children: sortTree(node.children),
    }));
  };

  return sortTree(root);
}

function prefixNode(node: TreeNode, prefix: string[]): TreeNode {
  const newPath = [...prefix, ...node.path];
  return {
    ...node,
    path: newPath,
    id: newPath.join("/"),
    children: node.children.map((child) => prefixNode(child, prefix)),
  };
}

function groupLegacyAdminSections(
  nodes: TreeNode[],
  isLatest: boolean,
): TreeNode[] {
  const legacyRootName = "admin-decocms-com";
  const legacyFolderNames = [
    "no-code-guides",
    "full-code-guides",
    "getting-started",
  ];

  const files = nodes.filter((n) => n.type === "file");
  const folders = nodes.filter((n) => n.type === "folder");

  const studioFolder = folders.find((f) => f.name === "studio");
  const mcpStudio = folders.find((f) => f.name === "mcp-studio");

  // For the latest version, exclude legacy admin folders entirely
  const legacyChildren = isLatest
    ? []
    : folders.filter((f) => legacyFolderNames.includes(f.name));

  const legacyFolder: TreeNode | null =
    legacyChildren.length > 0
      ? {
          name: legacyRootName,
          type: "folder",
          children: legacyChildren.map((child) =>
            prefixNode(child, [legacyRootName]),
          ),
          path: [legacyRootName],
          id: legacyRootName,
        }
      : null;

  // For v0 (deco.chat), show legacy content directly without the wrapper folder
  if (!isLatest) {
    return legacyChildren;
  }

  // Flatten studio folder - bring its children to the top level
  const next: TreeNode[] = [];

  // Add any top-level files first (e.g. introduction.mdx)
  next.push(...files);

  // Add all studio children directly at top level (order controlled by studioFolderOrder array)
  if (studioFolder && studioFolder.children.length > 0) {
    next.push(...studioFolder.children);
  }

  // Add mcp-studio as its own top-level section
  if (mcpStudio) {
    next.push(mcpStudio);
  }

  return next;
}

const isLatest = version === LATEST_VERSION.id;
const tree = groupLegacyAdminSections(buildTree(docs), isLatest);

interface FlatNode {
  name: string;
  type: "file" | "folder";
  doc?: any;
  path: string[];
  depth: number;
  id: string;
  hasChildren: boolean;
}

function flattenTree(nodes: TreeNode[], depth = 0): FlatNode[] {
  const result: FlatNode[] = [];

  nodes.forEach((node) => {
    result.push({
      name: node.name,
      type: node.type,
      doc: node.doc,
      path: node.path,
      depth,
      id: node.id,
      hasChildren: node.children.length > 0,
    });

    if (node.children.length > 0) {
      result.push(...flattenTree(node.children, depth + 1));
    }
  });

  return result;
}

const flatTree = flattenTree(tree);
---

<SidebarComponent
  client:load
  tree={flatTree}
  locale={locale || "en"}
  translations={ui[locale as keyof typeof ui] || ui.en}
  currentVersion={version}
/>
