import type { Metadata } from "next";
import { blogAuthor, blogPosts, wordCount, type BlogPost } from "@/content/blog-posts";
import { channels, team } from "./channels";
import { allowIndexing, siteName, siteUrl, supportEmail } from "./site";

export const absoluteUrl = (path: string) => `${siteUrl}${path === "/" ? "" : path}`;

/** Google cuts titles off at about 60 characters. Longer ones drop the " · Advertising.net" suffix instead. */
const TITLE_LIMIT = 60;

/** The 1200×630 share card from app/opengraph-image.tsx; blog posts have their own beside each post. */
export const defaultShareImage = "/opengraph-image";
export const shareImageSize = { width: 1200, height: 630 };

/**
 * Route metadata with a canonical URL plus matching Open Graph and Twitter cards.
 * The canonical is the bare path, so query-state variants (/contact?channel=…) consolidate to it.
 * `published` (YYYY-MM-DD) marks the page as an article.
 */
export function pageMeta({
  title,
  description,
  path,
  noindex,
  image = defaultShareImage,
  imageAlt = siteName,
  published,
}: {
  title?: string;
  description: string;
  path: string;
  noindex?: boolean;
  image?: string;
  imageAlt?: string;
  published?: string;
}): Metadata {
  const suffixed = title ? `${title} · ${siteName}` : `The AI Advertising Network · ${siteName}`;
  const fullTitle = title && suffixed.length > TITLE_LIMIT ? title : suffixed;
  const images = [{ url: image, ...shareImageSize, alt: imageAlt }];
  return {
    ...(title ? { title: fullTitle === title ? { absolute: title } : title } : {}),
    // Staging never follows links either, so a private page can't loosen the site-wide rule there.
    ...(noindex ? { robots: { index: false, follow: allowIndexing } } : {}),
    description,
    alternates: { canonical: path },
    openGraph: {
      siteName,
      locale: "en_US",
      url: path,
      title: fullTitle,
      description,
      images,
      ...(published
        ? { type: "article" as const, publishedTime: `${published}T00:00:00Z`, authors: [blogAuthor] }
        : { type: "website" as const }),
    },
    twitter: { card: "summary_large_image", title: fullTitle, description, images },
  };
}

type RouteEntry = { path: string; name: string; parent?: string; lastModified?: string };

/** Canonical, indexable routes. Feeds sitemap.xml and breadcrumb structured data. */
export const routes: RouteEntry[] = [
  { path: "/", name: "Home" },
  { path: "/solutions", name: "Channels" },
  ...channels.map((c) => ({ path: c.href, name: c.name, parent: "/solutions" })),
  { path: "/ai-approach", name: "Our AI Approach" },
  { path: "/how-it-works", name: "How It Works" },
  { path: "/team", name: "Our Team" },
  ...team.map((r) => ({ path: `/team/${r.slug}`, name: r.name, parent: "/team" })),
  { path: "/about", name: "Why Advertising.net" },
  { path: "/industries", name: "Industries" },
  { path: "/results", name: "Results" },
  { path: "/agencies", name: "For agencies" },
  { path: "/blog", name: "Blog" },
  ...blogPosts.map((p) => ({ path: `/blog/${p.slug}`, name: p.title, parent: "/blog", lastModified: p.date })),
  { path: "/contact", name: "Talk to Sales" },
  { path: "/support", name: "Support" },
  { path: "/signup", name: "Sign up to advertise" },
  { path: "/login", name: "Log in" },
  { path: "/forgot-password", name: "Reset your password" },
  { path: "/privacy", name: "Privacy Policy" },
  { path: "/ad-policies", name: "Ad Policies" },
  { path: "/terms", name: "Terms of Use" },
];

const routeByPath = Object.fromEntries(routes.map((r) => [r.path, r]));

function trail(path: string): RouteEntry[] {
  const out: RouteEntry[] = [];
  for (let r: RouteEntry | undefined = routeByPath[path]; r; r = r.parent ? routeByPath[r.parent] : undefined) out.unshift(r);
  return path === "/" ? out : [routeByPath["/"], ...out];
}

/** The visible breadcrumb items for a path: same trail as breadcrumbLd. */
export function crumbTrail(path: string) {
  return trail(path).map((r) => ({ name: r.name, href: r.path }));
}

/** Raster logo: the PNG made for email, since Google's logo guidelines list raster formats. */
const logoLd = { "@type": "ImageObject", url: `${siteUrl}/assets/images/email/logo.png`, width: 800, height: 118 };

/** Publisher on pages without the Organization node, which only Home carries (SEO audit, 2026-11-12). */
const publisherLd = { "@type": "Organization", "@id": `${siteUrl}/#organization`, name: siteName, url: `${siteUrl}/`, logo: logoLd };

function organizationLd(description: string) {
  return {
    "@context": "https://schema.org",
    "@type": "Organization",
    "@id": `${siteUrl}/#organization`,
    name: siteName,
    url: `${siteUrl}/`,
    logo: logoLd,
    description,
    contactPoint: [{ "@type": "ContactPoint", contactType: "customer support", email: supportEmail, telephone: "+1-800-242-4866" }],
  };
}

export const websiteLd = {
  "@context": "https://schema.org",
  "@type": "WebSite",
  "@id": `${siteUrl}/#website`,
  name: siteName,
  url: `${siteUrl}/`,
  publisher: { "@id": `${siteUrl}/#organization` },
};

export function breadcrumbLd(path: string) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: trail(path).map((r, i) => ({
      "@type": "ListItem",
      position: i + 1,
      name: r.name,
      item: absoluteUrl(r.path),
    })),
  };
}

/** The blog index: the posts it lists, newest first. */
export function blogLd() {
  const posts = [...blogPosts].sort((a, b) => b.date.localeCompare(a.date));
  return {
    "@context": "https://schema.org",
    "@type": "Blog",
    "@id": `${absoluteUrl("/blog")}#blog`,
    name: `${siteName} Blog`,
    url: absoluteUrl("/blog"),
    publisher: publisherLd,
    blogPost: posts.map((p) => ({ "@type": "BlogPosting", headline: p.title, url: absoluteUrl(`/blog/${p.slug}`), datePublished: p.date })),
  };
}

/** One article, for article rich results. The image is the post's share card. */
export function blogPostingLd(post: BlogPost) {
  const url = absoluteUrl(`/blog/${post.slug}`);
  return {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    "@id": `${url}#article`,
    headline: post.title,
    description: post.excerpt,
    url,
    mainEntityOfPage: url,
    image: absoluteUrl(`/blog/${post.slug}/opengraph-image`),
    datePublished: post.date,
    dateModified: post.date,
    author: { "@type": "Organization", name: blogAuthor, url: `${siteUrl}/` },
    publisher: publisherLd,
    isPartOf: { "@id": `${absoluteUrl("/blog")}#blog` },
    wordCount: wordCount(post.body),
    keywords: post.keywords.join(", "),
  };
}

/** The questions and answers from a post's visible FAQ section. */
export function faqLd(post: BlogPost) {
  return {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    "@id": `${absoluteUrl(`/blog/${post.slug}`)}#faq`,
    mainEntity: post.faqs.map((f) => ({ "@type": "Question", name: f.question, acceptedAnswer: { "@type": "Answer", text: f.answer } })),
  };
}

export function JsonLd({ data }: { data: object }) {
  return (
    <script
      type="application/ld+json"
      // Escape "<" so content can never close the script element.
      dangerouslySetInnerHTML={{ __html: JSON.stringify(data).replace(/</g, "\\u003c") }}
    />
  );
}

/** WebPage from the page's own metadata, so its name and description match the <title> and meta description. */
function webPageLd(path: string, meta: Metadata) {
  const title = meta.openGraph?.title;
  return {
    "@context": "https://schema.org",
    "@type": "WebPage",
    "@id": `${absoluteUrl(path)}#webpage`,
    url: absoluteUrl(path),
    name: typeof title === "string" ? title : siteName,
    ...(meta.description ? { description: meta.description } : {}),
    isPartOf: { "@id": `${siteUrl}/#website` },
  };
}

/**
 * Per-page structured data (SEO audit, 2026-11-12): Organization and WebSite on Home only; WebPage plus
 * BreadcrumbList on every other page. Blog posts pass no `meta`: their BlogPosting replaces WebPage.
 */
export function PageJsonLd({ path, meta }: { path: string; meta?: Metadata }) {
  if (path === "/") {
    return (
      <>
        <JsonLd data={organizationLd(typeof meta?.description === "string" ? meta.description : "")} />
        <JsonLd data={websiteLd} />
      </>
    );
  }
  return (
    <>
      {meta ? <JsonLd data={webPageLd(path, meta)} /> : null}
      <JsonLd data={breadcrumbLd(path)} />
    </>
  );
}
