import type { Metadata } from "next";
import { cache } from "react";
import { createCanonicalUrl } from "./seo";
import { getSiteInfo } from "./data";
import type { LanguageCode } from "@/types/language";
import { SUPPORTED_LANGUAGES } from "@/types/language";

export const BASE_URL = "https://www.betranked.com";

interface MetadataArgs {
  readonly title: string;
  readonly description: string;
  readonly path?: string;
  readonly keywords?: readonly string[];
  /**
   * If true, prevents indexing (for pages with sensitive parameters)
   * Defaults to false - pages are indexable by default
   */
  readonly noindex?: boolean;
  /**
   * Language code for metadata localization
   */
  readonly language?: LanguageCode;
}

const defaultKeywordsByLang: Record<LanguageCode, readonly string[]> = {
  en: [
    "online casino bonus",
    "best betting sites",
    "welcome bonus casino uk",
    "casino affiliate",
    "betting offers",
  ],
  pt: [
    "bónus de casino online",
    "melhores sites de apostas",
    "bónus de boas-vindas casino uk",
    "afiliado de casino",
    "ofertas de apostas",
  ],
  dk: [
    "online casino bonus",
    "bedste betting sider",
    "velkomstbonus casino dk",
    "casino affiliate",
    "betting tilbud",
  ],
  fr: [
    "bonus de casino en ligne",
    "meilleurs sites de paris",
    "bonus de bienvenue casino uk",
    "affilié de casino",
    "offres de paris",
  ],
  nl: [
    "online casino bonus",
    "beste goksites",
    "welkomstbonus casino uk",
    "casino affiliate",
    "gokaanbiedingen",
  ],
  sv: [
    "online casino bonus",
    "bästa spelsidor",
    "välkomstbonus casino uk",
    "casino affiliate",
    "spelerbjudanden",
  ],
  es: [
    "bonus de casino en línea",
    "mejores sitios de apuestas",
    "bonus de bienvenida casino uk",
    "afiliado de casino",
    "ofertas de apuestas",
  ],
} as const;

const localeMap: Record<LanguageCode, string> = {
  en: "en_GB",
  pt: "pt_PT",
  dk: "da_DK",
  fr: "fr_FR",
  nl: "nl_NL",
  sv: "sv_SE",
  es: "es_AR",
} as const;

/**
 * Creates metadata with caching for siteInfo
 * Uses React cache to avoid multiple reads per request
 * Supports multi-language with hreflang tags for SEO
 */
export const createMetadata = cache(({
  title,
  description,
  path = "/",
  keywords,
  noindex = false,
  language = "pt",
}: MetadataArgs): Metadata => {
  // Read siteInfo at runtime (cached per request)
  const siteInfo = getSiteInfo();
  
  // Always strip sensitive params from canonical and Open Graph URLs
  const canonicalUrl = createCanonicalUrl(path, BASE_URL);
  const ogUrl = createCanonicalUrl(path, BASE_URL);

  // Use language-specific keywords or default
  const finalKeywords = keywords || defaultKeywordsByLang[language];
  const locale = localeMap[language];

  // Generate hreflang alternates for all supported languages
  // Each language points to the same canonical URL (single dynamic architecture)
  const languages: Record<string, string> = {};
  SUPPORTED_LANGUAGES.forEach((lang) => {
    languages[lang] = canonicalUrl;
  });

  const alternates: Metadata["alternates"] = {
    canonical: canonicalUrl,
    languages,
  };

  return {
    title,
    description,
    alternates,
    keywords: [...finalKeywords],
    openGraph: {
      title,
      description,
      url: ogUrl, // Clean URL without sensitive params
      siteName: siteInfo.siteName,
      images: [
        {
          url: new URL(siteInfo.siteLogo, BASE_URL).toString(),
          width: 320,
          height: 320,
          alt: `${siteInfo.siteName} logo`,
        },
      ],
      locale,
      type: "website",
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [new URL(siteInfo.siteLogo, BASE_URL).toString()],
    },
    robots: {
      index: !noindex,
      follow: !noindex,
      googleBot: {
        index: !noindex,
        follow: !noindex,
        "max-video-preview": -1,
        "max-image-preview": "large",
        "max-snippet": -1,
      },
    },
  };
});
