---
import BaseHead from "../components/ui/BaseHead.astro";
import Footer from "../components/ui/Footer.astro";
import Sidebar from "../components/ui/Sidebar.astro";
import TableOfContents from "../components/ui/TableOfContents.astro";
import { Icon } from "../components/atoms/Icon";
import { LanguageSelector } from "../components/ui/LanguageSelector";
import { ProductSwitcher } from "../components/ui/ProductSwitcher";
import { ThemeToggle } from "../components/ui/ThemeToggle";
import { getCollection } from "astro:content";
import { siteConfig } from "../config/site";
import { LATEST_VERSION } from "../config/versions";
import "../styles/global.css";
import { ClientRouter } from "astro:transitions";
const { title, doc } = Astro.props;

// Get current path for breadcrumbs
const currentPath = Astro.url.pathname;
const pathSegments = currentPath.split("/").filter((segment) => segment !== "");
// Use Astro.params.locale when available (versioned routes: /[version]/[locale]/...)
// fallback to pathSegments[0] for legacy routes (/[locale]/...)
const locale = (Astro.params.locale as string) || pathSegments[0] || "en";
const version = (Astro.params.version as string) || LATEST_VERSION.id;
const localeIndex = pathSegments.indexOf(locale);
const pagePath =
  localeIndex >= 0
    ? pathSegments.slice(localeIndex + 1)
    : pathSegments.slice(1);

// Get all docs to determine folder vs file
const allDocs = await getCollection("docs");
const docs = allDocs.filter((doc) => doc.id.split("/")[0] === locale);

// Build tree to determine folder vs file
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: any) => {
    const pathParts = doc.id.split("/").slice(1);
    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;
      }
    });
  });

  return root;
}

const tree = buildTree(docs);

// Helper function to find node in tree
function findNode(path: string[]): TreeNode | null {
  let currentLevel = tree;

  for (const segment of path) {
    const node = currentLevel.find((n) => n.name === segment);
    if (!node) return null;
    currentLevel = node.children;
  }

  return currentLevel.length > 0 ? currentLevel[0] : null;
}

// Build breadcrumb items (only page-specific, no Home/Documentation)
const breadcrumbItems: Array<{
  name: string;
  href?: string;
  isFolder: boolean;
}> = [];

if (pagePath.length > 0) {
  let currentHref = `/${locale}`;
  pagePath.forEach((segment, index) => {
    currentHref += `/${segment}`;
    const name =
      segment.charAt(0).toUpperCase() + segment.slice(1).replace(/-/g, " ");

    // Determine if this is a folder by checking if there are children
    const pathSoFar = pagePath.slice(0, index + 1);
    const node = findNode(pathSoFar);
    const isFolder = index < pagePath.length - 1; // If not the last segment, it's a folder

    breadcrumbItems.push({
      name,
      href: isFolder ? undefined : currentHref, // Only files have href
      isFolder,
    });
  });
}

// Generate GitHub edit URL
const editUrl = doc
  ? `${siteConfig.githubRepo}/edit/${siteConfig.githubBranch}/apps/docs/client/src/content/${doc.id}.mdx`
  : null;
---

<html lang="en" data-theme="light">
  <head>
    <ClientRouter />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200"
      rel="stylesheet"
    />
    <BaseHead title={title} description={doc?.data?.description} />

    <!-- Prevent flash of unstyled content -->
    <style>
      /* Prevent flash by setting default theme immediately */
      html {
        color-scheme: light;
      }
      html[data-theme="dark"] {
        color-scheme: dark;
      }
    </style>

    <!-- Theme initialization script -->
    <script is:inline>
      (function () {
        // Get saved theme from localStorage or default to auto
        const savedTheme = localStorage.getItem("theme") || "auto";

        function applyTheme(theme) {
          const html = document.documentElement;

          if (theme === "auto") {
            // Use system preference
            const prefersDark = window.matchMedia(
              "(prefers-color-scheme: dark)"
            ).matches;
            html.setAttribute("data-theme", prefersDark ? "dark" : "light");
          } else {
            html.setAttribute("data-theme", theme);
          }
        }

        // Apply theme immediately
        applyTheme(savedTheme);

        // Preserve theme across client-side navigations: copy current data-theme
        // to the incoming document before Astro swaps the DOM, preventing a flash
        // caused by the new page's hardcoded data-theme="light" on <html>.
        document.addEventListener("astro:before-swap", function (e) {
          const currentTheme = document.documentElement.getAttribute("data-theme");
          if (currentTheme) {
            e.newDocument.documentElement.setAttribute("data-theme", currentTheme);
          }
        });

        // Listen for system theme changes if using auto
        if (savedTheme === "auto") {
          window
            .matchMedia("(prefers-color-scheme: dark)")
            .addEventListener("change", function (e) {
              applyTheme("auto");
            });
        }
      })();
    </script>

    <!-- Mobile menu script -->
    <script>
      // Mobile menu functionality
      function toggleMobileMenu() {
        const sidebar = document.getElementById("sidebar");
        const overlay = document.getElementById("mobile-overlay");

        if (!sidebar || !overlay) return;

        if (sidebar.classList.contains("hidden")) {
          sidebar.classList.remove("hidden");
          overlay.classList.remove("hidden");
        } else {
          closeMobileMenu();
        }
      }

      function closeMobileMenu() {
        const sidebar = document.getElementById("sidebar");
        const overlay = document.getElementById("mobile-overlay");

        if (!sidebar || !overlay) return;

        sidebar.classList.add("hidden");
        overlay.classList.add("hidden");
      }

      // Register once - persists across navigations, doesn't depend on DOM elements
      document.addEventListener("keydown", function (e) {
        if (e.key === "Escape") {
          closeMobileMenu();
        }
      });

      // Add event listeners when DOM is ready
      document.addEventListener("astro:page-load", function () {
        const menuButton = document.getElementById("mobile-menu-button");
        const overlay = document.getElementById("mobile-overlay");

        if (menuButton) {
          menuButton.addEventListener("click", toggleMobileMenu);
        }

        if (overlay) {
          overlay.addEventListener("click", closeMobileMenu);
        }

        // Folder click functionality for breadcrumbs
        const folderButtons = document.querySelectorAll("[data-folder-click]");
        folderButtons.forEach((button) => {
          button.addEventListener("click", function () {
            // On mobile, open the sidebar
            if (window.innerWidth < 1024) {
              // lg breakpoint
              toggleMobileMenu();
            }
            // On desktop, the sidebar is always visible, so just focus it
            // You could add additional desktop behavior here if needed
          });
        });
      });
    </script>
  </head>
  <body class="bg-app-background text-foreground">
    <div class="flex h-screen overflow-hidden">
      <!-- Mobile overlay -->
      <div
        id="mobile-overlay"
        class="fixed inset-0 bg-black/50 z-40 hidden lg:hidden"
      >
      </div>

      <!-- Sidebar - hidden on mobile by default -->
      <div
        id="sidebar"
        class="fixed lg:relative lg:block hidden z-50 lg:z-auto h-full"
      >
        <Sidebar />
      </div>

      <!-- Main content -->
      <div class="flex-1 overflow-y-auto overflow-x-hidden scrollbar-hide">
        <!-- Mobile header - fixed -->
        <div
          class="lg:hidden fixed top-0 left-0 right-0 z-30 bg-app-background"
        >
          <div class="flex items-center justify-between p-4">
            <div class="flex items-center gap-3">
              <button
                id="mobile-menu-button"
                class="p-2 hover:bg-muted rounded-lg transition-colors"
              >
                <Icon name="Menu" size={24} />
              </button>
              <ProductSwitcher client:load />
            </div>
            <div class="flex items-center gap-2">
              <LanguageSelector client:load locale={locale} className="w-32" />
              <ThemeToggle client:load />
            </div>
          </div>

          <!-- Breadcrumbs in mobile header -->
          <div class="px-4 py-3 border-b border-t border-border">
            <nav class="flex items-center gap-2 text-sm text-muted-foreground">
              {
                breadcrumbItems.map((item, index) => (
                  <>
                    {index > 0 && <span>/</span>}
                    {index === breadcrumbItems.length - 1 ? (
                      <span class="text-foreground">{item.name}</span>
                    ) : item.isFolder ? (
                      <button
                        class="hover:text-foreground transition-colors cursor-pointer"
                        data-folder-click
                      >
                        {item.name}
                      </button>
                    ) : (
                      <a
                        href={item.href}
                        class="hover:text-foreground transition-colors"
                      >
                        {item.name}
                      </a>
                    )}
                  </>
                ))
              }
            </nav>
          </div>
        </div>

        <!-- Content with mobile top padding -->
        <div
          class="flex min-h-full py-8 lg:py-16 px-4 lg:px-8 gap-x-8 lg:pt-16"
        >
          <article class="flex-1 max-w-none min-w-0">
            <slot />

            {/* Edit button */}
            {
              editUrl && (
                <div class="mt-12 pt-8 border-t border-border">
                  <div class="flex items-center justify-between">
                    <p class="text-sm text-muted-foreground">
                      Found an error or want to improve this page?
                    </p>
                    <a
                      href={editUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors border border-border rounded-lg hover:bg-muted hover:border-foreground/20"
                    >
                      <Icon name="Pencil" size={16} />
                      Edit this page
                    </a>
                  </div>
                </div>
              )
            }
          </article>
          <div class="hidden xl:block w-80 shrink-0">
            <div class="sticky top-1">
              <TableOfContents />
            </div>
          </div>
        </div>
      </div>
    </div>

  </body>
</html>
