﻿import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { loadDictionary } from "@allai/i18n/server";
import { locales, resolveLocale } from "@/config/i18n";
import { BlogPage } from "@/features/marketing/BlogPage";
import { getBlogPosts } from "@/features/marketing/blogData";
import { absoluteUrl, buildCanonical, buildLocaleAlternates, buildOpenGraph, buildTwitterCard } from "@/seo/seoUtils";

const PATH = "/blog" as const;

type PageProps = {
  params: { locale: string };
};

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const locale = resolveLocale(params.locale);

  if (!locales.includes(locale)) {
    return {
      title: "AllAI blog"
    };
  }

  const dictionary = await loadDictionary(locale);
  const title =
    locale === "ru"
      ? `Блог | ${dictionary.common.brandLong ?? dictionary.common.brandShort}`
      : locale === "es"
        ? `Blog | ${dictionary.common.brandLong ?? dictionary.common.brandShort}`
        : locale === "pt"
          ? `Blog | ${dictionary.common.brandLong ?? dictionary.common.brandShort}`
          : `Blog | ${dictionary.common.brandLong ?? dictionary.common.brandShort}`;
  const description =
    locale === "ru"
      ? "Кейсы, инструкции и разборы по AI-процессам в AllAI Studio для креативных команд."
      : locale === "es"
        ? "Ideas, guías y casos sobre producción creativa con IA usando AllAI Studio."
        : locale === "pt"
          ? "Ideias, guias e casos sobre produção criativa com IA usando o AllAI Studio."
          : "Insights, playbooks, and case studies on running AI-first creative production with AllAI Studio.";

  return {
    title,
    description,
    alternates: {
      canonical: buildCanonical(locale, PATH),
      languages: buildLocaleAlternates(PATH)
    },
    openGraph: buildOpenGraph({
      locale,
      title,
      description,
      path: PATH
    }),
    twitter: buildTwitterCard({
      title,
      description
    })
  };
}

export default async function BlogRoute({ params }: PageProps) {
  const locale = resolveLocale(params.locale);

  if (!locales.includes(locale)) {
    notFound();
  }

  const dictionary = await loadDictionary(locale);
  const canonical = buildCanonical(locale, PATH);
  const publisher = {
    "@type": "Organization",
    name: dictionary.common.brandLong ?? dictionary.common.brandShort,
    logo: {
      "@type": "ImageObject",
      url: absoluteUrl("/favicon.ico")
    }
  };

  const structuredData = {
    "@context": "https://schema.org",
    "@type": "Blog",
    name:
      locale === "ru"
        ? `${dictionary.common.brandLong ?? dictionary.common.brandShort} аналитика`
        : locale === "es"
          ? `${dictionary.common.brandLong ?? dictionary.common.brandShort} ideas`
          : locale === "pt"
            ? `${dictionary.common.brandLong ?? dictionary.common.brandShort} ideias`
            : `${dictionary.common.brandLong ?? dictionary.common.brandShort} insights`,
    description:
      locale === "ru"
        ? "Экспертные комментарии и практические туториалы для команд, внедряющих генеративные AI-процессы в AllAI Studio."
        : locale === "es"
          ? "Comentarios expertos y tutoriales para equipos creativos que adoptan flujos de IA generativa con AllAI Studio."
          : locale === "pt"
            ? "Comentários de especialistas e tutoriais para equipes criativas que adotam fluxos de IA generativa com o AllAI Studio."
            : "Expert commentary and tutorials for creative teams adopting generative AI workflows with AllAI Studio.",
    url: canonical,
    inLanguage: locale,
    publisher,
    blogPost: getBlogPosts(locale).map((post) => ({
      "@type": "BlogPosting",
      headline: post.title,
      description: post.excerpt,
      url: buildCanonical(locale, `${PATH}/${post.slug}`),
      datePublished: post.publishedAt,
      dateModified: post.publishedAt,
      author: publisher,
      publisher
    }))
  };

  return (
    <>
      <script
        type="application/ld+json"
        suppressHydrationWarning
        dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
      />
      <BlogPage locale={locale} />
    </>
  );
}
