import type { Metadata } from "next";

import { defaultLocale, locales, type Locale } from "@/lib/i18n";
import { localizedAlternates } from "@/lib/seo/alternates";
import { routeIndexable, routeLocales } from "@/lib/seo/locale-availability";

/** Site name, reused for OpenGraph `siteName` and Twitter card title fallback. */
export const SITE_NAME = "SEO Insight";

/**
 * Default social share image. Resolved against `metadataBase` (set in the root
 * layout), so a site-relative path is fine. 1200×630 is the standard OG/Twitter
 * `summary_large_image` size. Reused for OpenGraph and Twitter so the two agree.
 */
export const DEFAULT_OG_IMAGE = {
  url: "/home/dashboard-overview.webp",
  width: 1200,
  height: 630,
  alt: "SEO Insight — SEO platform for keywords, backlinks and content",
} as const;

/**
 * Centralized, translated SEO metadata for the non-blog pages.
 *
 * One place to edit titles/descriptions/keywords per locale. `buildPageMetadata`
 * turns an entry into a full Next `Metadata` object — title, description,
 * keywords, OpenGraph, and canonical + `hreflang` alternates (so every page
 * matches the sitemap). Wire it from a page's `generateMetadata`:
 *
 *   export async function generateMetadata({ params }: PageProps<"/[lang]/pricing">) {
 *     const { lang } = await params;
 *     return buildPageMetadata("/pricing", lang);
 *   }
 *
 * Blog posts/categories and docs carry their own (content-driven) metadata.
 * Keys are locale-less paths under `/[lang]` (`""` is the home page).
 */
type PageSeo = {
  title: string;
  description: string;
  keywords?: string[];
};

type LocalizedPageSeo = Record<Locale, PageSeo>;

const PAGES: Record<string, LocalizedPageSeo> = {
  "": {
    en: {
      title: "SEO Insight | SEO Platform for Keywords, Backlinks and Content",
      description:
        "The all-in-one SEO platform: track keywords, audit backlinks, and ship optimized content. A built-in MCP server lets AI agents work directly with your SEO data.",
      keywords: [
        "SEO platform",
        "keyword tracking",
        "backlink audit",
        "content optimization",
        "SEO MCP server",
      ],
    },
    fr: {
      title: "SEO Insight | Plateforme SEO mots-clés, backlinks et contenu",
      description:
        "La plateforme SEO tout-en-un : suivez vos mots-clés, auditez vos backlinks et publiez du contenu optimisé. Un serveur MCP intégré connecte vos agents IA à vos données SEO.",
      keywords: [
        "plateforme SEO",
        "suivi de mots-clés",
        "audit de backlinks",
        "optimisation de contenu",
        "serveur MCP SEO",
      ],
    },
  },
  "/pricing": {
    en: {
      title: "Pricing | SEO Insight",
      description:
        "Simple, transparent SEO pricing. Start free and scale as you grow. Keyword tracking, backlink audits, content briefs and the SEO Insight MCP server included.",
      keywords: ["SEO pricing", "SEO plans", "SEO tool pricing"],
    },
    fr: {
      title: "Tarifs | SEO Insight",
      description:
        "Une tarification SEO simple et transparente. Commencez gratuitement et évoluez à votre rythme. Suivi de mots-clés, audits de backlinks, briefs de contenu et serveur MCP inclus.",
      keywords: ["tarifs SEO", "abonnement SEO", "prix outil SEO"],
    },
  },
  "/services": {
    en: {
      title: "SEO Services | SEO Insight",
      description:
        "Hands-on SEO services: technical SEO, CMS and WordPress optimization, and code-level performance. Expert delivery backed by the SEO Insight platform.",
      keywords: [
        "SEO services",
        "technical SEO",
        "WordPress SEO",
        "CMS optimization",
      ],
    },
    fr: {
      title: "Services SEO | SEO Insight",
      description:
        "Des services SEO concrets : SEO technique, optimisation CMS et WordPress, performance au niveau du code. Une expertise adossée à la plateforme SEO Insight.",
      keywords: [
        "services SEO",
        "SEO technique",
        "SEO WordPress",
        "optimisation CMS",
      ],
    },
  },
  "/services/cms-optimization": {
    en: {
      title: "CMS SEO Optimization | SEO Insight",
      description:
        "Make any CMS fast and search-ready. We optimize templates, metadata, structured data and Core Web Vitals so your content ranks and converts.",
      keywords: ["CMS SEO", "CMS optimization", "structured data", "Core Web Vitals"],
    },
    fr: {
      title: "Optimisation SEO CMS | SEO Insight",
      description:
        "Rendez n'importe quel CMS rapide et prêt pour le référencement. Templates, métadonnées, données structurées et Core Web Vitals optimisés pour mieux ranker et convertir.",
      keywords: [
        "SEO CMS",
        "optimisation CMS",
        "données structurées",
        "Core Web Vitals",
      ],
    },
  },
  "/services/seo-code-optimization": {
    en: {
      title: "SEO Code Optimization | SEO Insight",
      description:
        "Code-level SEO and performance: Core Web Vitals, rendering, crawlability and clean markup. Faster pages that search engines and users both love.",
      keywords: [
        "SEO code optimization",
        "Core Web Vitals",
        "page speed",
        "crawlability",
      ],
    },
    fr: {
      title: "Optimisation SEO du code | SEO Insight",
      description:
        "SEO et performance au niveau du code : Core Web Vitals, rendu, crawlabilité et balisage propre. Des pages plus rapides, appréciées des moteurs comme des utilisateurs.",
      keywords: [
        "optimisation SEO du code",
        "Core Web Vitals",
        "vitesse de page",
        "crawlabilité",
      ],
    },
  },
  "/services/wordpress-management": {
    en: {
      title: "WordPress Management | SEO Insight",
      description:
        "Managed WordPress care: updates, security, backups and performance, all tuned for SEO. Keep your site fast, safe and ranking without the maintenance burden.",
      keywords: [
        "WordPress management",
        "managed WordPress",
        "WordPress maintenance",
        "WordPress performance",
      ],
    },
    fr: {
      title: "Gestion WordPress | SEO Insight",
      description:
        "Maintenance WordPress gérée : mises à jour, sécurité, sauvegardes et performance, optimisées pour le SEO. Un site rapide, sûr et bien classé, sans la charge technique.",
      keywords: [
        "gestion WordPress",
        "maintenance WordPress",
        "WordPress infogéré",
        "performance WordPress",
      ],
    },
  },
  "/services/wordpress-seo": {
    en: {
      title: "WordPress SEO | SEO Insight",
      description:
        "WordPress SEO done right: technical fixes, on-page optimization, schema and Core Web Vitals. Turn your WordPress site into a reliable traffic channel.",
      keywords: [
        "WordPress SEO",
        "on-page SEO",
        "schema markup",
        "WordPress optimization",
      ],
    },
    fr: {
      title: "SEO WordPress | SEO Insight",
      description:
        "Le SEO WordPress fait correctement : corrections techniques, optimisation on-page, schema et Core Web Vitals. Transformez votre site WordPress en canal de trafic fiable.",
      keywords: [
        "SEO WordPress",
        "SEO on-page",
        "schema",
        "optimisation WordPress",
      ],
    },
  },
  "/about": {
    en: {
      title: "About | SEO Insight",
      description:
        "SEO Insight is built by SBInnovate Ltd to make technical SEO measurable and actionable, pairing a powerful platform with hands-on expert services.",
      keywords: ["about SEO Insight", "SBInnovate", "SEO company"],
    },
    fr: {
      title: "À propos | SEO Insight",
      description:
        "SEO Insight est développé par SBInnovate Ltd pour rendre le SEO technique mesurable et actionnable, en associant une plateforme puissante à des services experts.",
      keywords: ["à propos SEO Insight", "SBInnovate", "agence SEO"],
    },
  },
  "/contact": {
    en: {
      title: "Contact | SEO Insight",
      description:
        "Talk to the SEO Insight team about the platform, services or a partnership. We reply fast and speak both engineering and SEO.",
      keywords: ["contact SEO Insight", "SEO support", "SEO consultation"],
    },
    fr: {
      title: "Contact | SEO Insight",
      description:
        "Échangez avec l'équipe SEO Insight au sujet de la plateforme, des services ou d'un partenariat. Réponse rapide, dans un langage à la fois technique et SEO.",
      keywords: ["contact SEO Insight", "support SEO", "consultation SEO"],
    },
  },
};

/**
 * Full `Metadata` for a non-blog page: translated title/description/keywords,
 * OpenGraph, and canonical + `hreflang` alternates. Returns `{}` for unknown
 * paths so the page falls back to the layout's default metadata.
 */
export function buildPageMetadata(path: string, lang: string): Metadata {
  const locale: Locale = (locales as readonly string[]).includes(lang)
    ? (lang as Locale)
    : defaultLocale;
  const seo = PAGES[path]?.[locale];
  if (!seo) return {};

  const { canonical, languages } = localizedAlternates(
    path,
    locale,
    routeLocales(path),
  );

  return {
    title: seo.title,
    description: seo.description,
    keywords: seo.keywords,
    alternates: { canonical, languages },
    // Non-indexable routes (e.g. thin stubs) stay crawlable so links are still
    // followed, but are kept out of the index. Driven by the route registry.
    ...(!routeIndexable(path)
      ? { robots: { index: false, follow: true } }
      : {}),
    openGraph: {
      type: "website",
      siteName: SITE_NAME,
      title: seo.title,
      description: seo.description,
      url: canonical,
      locale: locale === "fr" ? "fr_FR" : "en_US",
      images: [DEFAULT_OG_IMAGE],
    },
    // Mirror OpenGraph so the Twitter card stays consistent (FS-M1).
    twitter: {
      card: "summary_large_image",
      site: "@seoinsight",
      title: seo.title,
      description: seo.description,
      images: [DEFAULT_OG_IMAGE.url],
    },
  };
}
