---
// Import the global.css file here so that it is included on
// all pages through the use of the <BaseHead /> component.
import '../styles/global.css';
import atkinsonRegular from '../assets/theme/fonts/atkinson-regular.woff?url';
import atkinsonBold from '../assets/theme/fonts/atkinson-bold.woff?url';
import type { ImageMetadata } from 'astro';
import FallbackImage from '../assets/theme/social/anglefeint-og.jpg';
import { THEME_CONFIG } from '@anglefeint/user-config';
import { publicDir } from 'virtual:anglefeint-social';
import { resolveSocialImage } from '../social/resolve.mjs';
import { buildHeadLocaleState, buildJsonLdSchemas } from '../utils/head';
import { SITE_AUTHOR, SITE_TITLE, SITE_URL } from '@anglefeint/site-config/site';
import { localePath, getLocaleHreflang, type Locale } from '@anglefeint/site-i18n/config';
import { THEME } from '@anglefeint/site-config/theme';

interface Props {
  title: string;
  description: string;
  image?: ImageMetadata | { src: string; width?: number; height?: number };
  imageAlt?: string;
  pageType?: 'website' | 'article';
  publishedTime?: Date;
  modifiedTime?: Date;
  author?: string;
  tags?: string[];
  schema?: Record<string, unknown> | Record<string, unknown>[];
  noindex?: boolean;
  includeAlternateLinks?: boolean;
  localeHrefs?: Partial<Record<Locale, string>>;
  seoLocaleHrefs?: Partial<Record<Locale, string>>;
}

const siteURL = Astro.site ?? new URL(SITE_URL);
const canonicalURL = new URL(Astro.url.pathname, siteURL);

const {
  title,
  description,
  image: pageImage,
  imageAlt = title,
  pageType = 'website',
  publishedTime,
  modifiedTime,
  author = SITE_AUTHOR,
  tags,
  schema,
  noindex = false,
  includeAlternateLinks = true,
  localeHrefs,
  seoLocaleHrefs,
} = Astro.props;

// Page/article images retain priority; only missing images use the site/theme fallback.
const image =
  pageImage ??
  (await resolveSocialImage({
    override: THEME_CONFIG.site.ogImage?.trim(),
    enabled: false,
    fallback: FallbackImage,
    data: { title },
    publicDir,
    base: import.meta.env.BASE_URL,
  }));
const imageURL = new URL(image.src, siteURL).toString();
const robotsContent = noindex ? 'noindex, nofollow' : 'index, follow, max-image-preview:large';
const isArticle = pageType === 'article';
const { currentLocale, alternatePaths, xDefaultHref, ogLocale, ogLocaleAlternates } =
  buildHeadLocaleState(Astro.url.pathname, siteURL, localeHrefs, seoLocaleHrefs);
const rssURL = new URL(`/${currentLocale}/rss.xml`, siteURL);
const articleModifiedISO = (modifiedTime ?? publishedTime)?.toISOString();
const jsonLdSchemas = buildJsonLdSchemas({
  siteTitle: SITE_TITLE,
  inLanguage: getLocaleHreflang(currentLocale as Locale),
  siteAuthor: SITE_AUTHOR,
  siteURL,
  title,
  description,
  imageURL,
  canonicalURL,
  isArticle,
  author,
  authorURL:
    isArticle && THEME.ABOUT_PAGE_ENABLED && author === SITE_AUTHOR
      ? new URL(localePath(currentLocale as Locale, '/about/'), siteURL).toString()
      : undefined,
  publishedTime,
  modifiedTime,
  tags,
  schema,
});
const serializeJsonLd = (value: unknown) => JSON.stringify(value).replace(/</g, '\\u003c');
---

<!-- Global Metadata -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" href="/favicon.ico" />
<link rel="sitemap" href="/sitemap-index.xml" />
<link rel="alternate" type="application/rss+xml" title={SITE_TITLE} href={rssURL} />
<meta name="generator" content={Astro.generator} />
<meta name="robots" content={robotsContent} />
<meta name="author" content={author} />

<!-- Font preloads -->
<link rel="preload" href={atkinsonRegular} as="font" type="font/woff" crossorigin />
<link rel="preload" href={atkinsonBold} as="font" type="font/woff" crossorigin />

<!-- Canonical URL -->
<link rel="canonical" href={canonicalURL} />
{
  includeAlternateLinks &&
    alternatePaths.map((alternate) => (
      <link rel="alternate" hreflang={alternate.hreflang} href={alternate.href} />
    ))
}
{
  includeAlternateLinks && xDefaultHref && (
    <link rel="alternate" hreflang="x-default" href={xDefaultHref} />
  )
}

<!-- Primary Meta Tags -->
<title>{title}</title>
<meta name="title" content={title} />
<meta name="description" content={description} />
{tags && tags.length > 0 && <meta name="keywords" content={tags.join(', ')} />}

<!-- Open Graph / Facebook -->
<meta property="og:type" content={isArticle ? 'article' : 'website'} />
<meta property="og:url" content={canonicalURL} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={imageURL} />
<meta property="og:image:alt" content={imageAlt} />
{
  typeof image?.width === 'number' && (
    <meta property="og:image:width" content={String(image.width)} />
  )
}
{
  typeof image?.height === 'number' && (
    <meta property="og:image:height" content={String(image.height)} />
  )
}
{ogLocale && <meta property="og:locale" content={ogLocale} />}
{
  includeAlternateLinks &&
    ogLocaleAlternates.map((loc) => <meta property="og:locale:alternate" content={loc} />)
}
{
  isArticle && publishedTime && (
    <meta property="article:published_time" content={publishedTime.toISOString()} />
  )
}
{
  isArticle && articleModifiedISO && (
    <meta property="article:modified_time" content={articleModifiedISO} />
  )
}
{isArticle && <meta property="article:author" content={author} />}

<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:url" content={canonicalURL} />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={imageURL} />
<meta name="twitter:image:alt" content={imageAlt} />

{
  jsonLdSchemas.map((schemaItem) => (
    <script is:inline type="application/ld+json" set:html={serializeJsonLd(schemaItem)} />
  ))
}
