import type { Metadata } from "next";
import type { Locale, SiteSettings } from "@/types/content";
import { localizedPath } from "@/lib/routing";

export const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "https://www.akarya.id";

type SeoInput = {
  locale: Locale;
  settings: SiteSettings;
  title?: string;
  description?: string;
  path?: string;
  image?: string;
};

export function createMetadata({ locale, settings, title, description, path = "/", image }: SeoInput): Metadata {
  const canonical = `${siteUrl}${localizedPath(path, locale)}`;
  const enPath = `${siteUrl}${localizedPath(path, "en")}`;
  const idPath = `${siteUrl}${localizedPath(path, "id")}`;
  const finalTitle = title ?? settings.defaultSeoTitle[locale];
  const finalDescription = description ?? settings.defaultSeoDescription[locale];

  return {
    title: finalTitle,
    description: finalDescription,
    alternates: {
      canonical,
      languages: {
        en: enPath,
        id: idPath,
        "x-default": enPath
      }
    },
    openGraph: {
      type: "website",
      url: canonical,
      siteName: settings.siteName,
      title: finalTitle,
      description: finalDescription,
      locale: locale === "id" ? "id_ID" : "en_US",
      images: image ? [{ url: image, alt: finalTitle }] : undefined
    },
    twitter: {
      card: "summary_large_image",
      title: finalTitle,
      description: finalDescription,
      images: image ? [image] : undefined
    }
  };
}

export function organizationJsonLd(locale: Locale, settings: SiteSettings) {
  return {
    "@context": "https://schema.org",
    "@type": ["Organization", "LocalBusiness"],
    name: "PT Akarya Solusi Kreatif",
    alternateName: "Akarya",
    url: siteUrl,
    email: settings.contactEmail,
    telephone: settings.phoneNumber,
    address: {
      "@type": "PostalAddress",
      streetAddress: settings.headOfficeAddress,
      addressLocality: "Yogyakarta",
      addressRegion: "Daerah Istimewa Yogyakarta",
      postalCode: "55153",
      addressCountry: "ID"
    },
    description: settings.siteDescription[locale],
    sameAs: [`https://www.instagram.com/${settings.socialHandle.replace("@", "")}`]
  };
}

export function websiteJsonLd(locale: Locale, settings: SiteSettings) {
  return {
    "@context": "https://schema.org",
    "@type": "WebSite",
    name: settings.siteName,
    url: siteUrl,
    inLanguage: locale === "id" ? "id-ID" : "en-US",
    description: settings.siteDescription[locale]
  };
}

export function breadcrumbJsonLd(items: Array<{ name: string; url: string }>) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items.map((item, index) => ({
      "@type": "ListItem",
      position: index + 1,
      name: item.name,
      item: item.url
    }))
  };
}
