import { SiteFooter } from "@/components/site-footer";
import { assertIsPathLocale, defaultLocale, type Locale } from "@/lib/locale";
import { renderFeatures } from "@/lib/remark/remark-features";
import { t } from "@/locales";
import type { Metadata } from "next";
import * as fs from "node:fs";
import { cache, type ReactNode } from "react";
import { cachedDecideLocale } from "@/lib/server-locale";

const cachedRenderFeatures = cache(async (lang: Locale | undefined) => {
  const markdown = await fs.promises.readFile(
    `src/components/pages/get-more-credits/${lang ?? defaultLocale}.md`,
    "utf8"
  );
  return renderFeatures(markdown);
});

export default async function GetMoreCreditsPage(props: {
  params: Promise<{ lang?: string }>;
}) {
  const { lang } = await props.params;
  assertIsPathLocale(lang);

  const locale = await cachedDecideLocale(lang);

  const { result } = await cachedRenderFeatures(lang);

  return (
    <>
      <main className="max-w-(--breakpoint-lg) mx-auto p-4 py-16 [&>h1]:font-bold [&>h1]:text-3xl">
        {result.heading}
        <section className="my-4 space-y-4 text-muted-foreground">
          {result.body}
        </section>
        <section className="my-16">
          <ul className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-8">
            {result.features.map((feature, index) => (
              <OptionCard key={index} title={feature.title}>
                {feature.content}
              </OptionCard>
            ))}
          </ul>
        </section>
      </main>
      <SiteFooter locale={locale} />
    </>
  );
}

export async function generateMetadata(props: {
  params: Promise<{ lang?: string }>;
}): Promise<Metadata> {
  const { lang } = await props.params;
  assertIsPathLocale(lang);

  const { title } = await cachedRenderFeatures(lang);

  return {
    title: `${title} | ${t(lang ?? defaultLocale, "home.seo.title")}`,
  };
}

export { generateStaticParams } from "@/components/pages/localed-pages";

function OptionCard({
  title,
  children,
}: {
  title: ReactNode;
  children?: ReactNode;
}) {
  return (
    <li className="transition-colors hover:bg-accent rounded-lg p-6 space-y-2 [&_ul]:list-disc [&_ul]:pl-4 [&_a]:underline [&>h2]:font-semibold [&>h2]:text-lg text-sm">
      {title}
      {children}
    </li>
  );
}
