import type { Metadata } from "next";
import { cache } from "react";
import { notFound } from "next/navigation";

import { getDictionary, hasLocale } from "@/app/[lang]/dictionaries";
import { DocsNav } from "@/components/docs/docs-nav";
import { DocsPager } from "@/components/docs/docs-pager";
import { DocsTopBar } from "@/components/docs/docs-top-bar";
import { Prose } from "@/components/docs/prose";
import { Logo } from "@/components/shared/logo";
import { siteUrl } from "@/lib/env";
import { getDocsFlatLinks, getDocsNavigation } from "@/lib/docs/navigation";
import { buildDocsSearchIndex } from "@/lib/docs/search-index";
import { localizedAlternates } from "@/lib/seo/alternates";

/**
 * Memoized docs search index. `buildDocsSearchIndex` reads the docs MDX files
 * from disk; wrapping it in React `cache()` collapses repeated calls (and the
 * extra FS reads on hot reload) within a render pass to a single read.
 */
const getDocsSearchIndex = cache(buildDocsSearchIndex);

/** Default OpenGraph/Twitter share image for docs pages. */
const DEFAULT_OG_IMAGE = `${siteUrl}/home/dashboard-overview.webp`;

/**
 * Full docs page `Metadata` from a content-driven `{ title, description }`
 * (exported by each page's MDX). Centralizes the canonical/hreflang alternates
 * plus the OpenGraph + Twitter blocks so every doc shares a rich preview
 * (title, description, default image) when linked on social platforms.
 */
export function buildDocsMetadata(
  meta: Metadata,
  path: string,
  lang: string,
): Metadata {
  const { canonical, languages } = localizedAlternates(path, lang);
  const title = meta.title ?? undefined;
  const description = meta.description ?? undefined;
  return {
    ...meta,
    alternates: { canonical, languages },
    openGraph: {
      type: "article",
      title,
      description,
      url: canonical,
      locale: lang === "fr" ? "fr_FR" : "en_US",
      images: [{ url: DEFAULT_OG_IMAGE }],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [DEFAULT_OG_IMAGE],
    },
  };
}

export default async function DocsLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ lang: string }>;
}) {
  const { lang } = await params;
  if (!hasLocale(lang)) notFound();

  const dict = await getDictionary(lang);
  const groups = getDocsNavigation(dict);
  const flatLinks = getDocsFlatLinks(dict);
  // Only surface the active locale's docs in search.
  const searchRecords = getDocsSearchIndex().filter((r) => r.lang === lang);
  const t = dict.docs;

  return (
    <div className="lg:ml-72 xl:ml-80">
      {/* Fixed sidebar (desktop) */}
      <div className="border-hairline hidden lg:fixed lg:inset-y-0 lg:left-0 lg:z-40 lg:flex lg:w-72 lg:flex-col lg:overflow-y-auto lg:border-r lg:px-6 lg:pt-6 lg:pb-8 xl:w-80">
        <Logo lang={lang} />
        <DocsNav lang={lang} groups={groups} className="mt-10" />
      </div>

      {/* Top bar with search */}
      <DocsTopBar
        lang={lang}
        records={searchRecords}
        groups={groups}
        labels={{
          home: t.topbar.home,
          pricing: t.topbar.pricing,
          signin: t.topbar.signin,
          openMenu: t.topbar.openMenu,
          closeMenu: t.topbar.closeMenu,
        }}
      />

      {/* Content */}
      <main
        id="main-content"
        className="mx-auto flex min-h-svh w-full max-w-5xl flex-col px-4 pt-10 pb-16 sm:px-6 lg:px-12 lg:pt-12"
      >
        <Prose as="article">{children}</Prose>
        <DocsPager
          lang={lang}
          links={flatLinks}
          labels={{ previous: t.pager.previous, next: t.pager.next }}
        />
      </main>
    </div>
  );
}
