---
import interWoff2 from '@fontsource-variable/inter/files/inter-latin-wght-normal.woff2?url';
import alegreyaWoff2 from '@fontsource-variable/alegreya/files/alegreya-latin-wght-normal.woff2?url';
import siteConfig from '../data/site-config';
import '../styles/global.css';

export type Props = {
    title?: string;
    description?: string;
    image?: { src: string; alt?: string };
    pageType?: 'website' | 'article';
};

const { description = '', image = siteConfig.image, pageType = 'website' } = Astro.props;
const title = [Astro.props.title, siteConfig.title].filter(Boolean).join(' | ');
const resolvedImage = image?.src
    ? {
          src: new URL(image.src, Astro.site).toString(),
          alt: image.alt
      }
    : undefined;
const canonicalURL = new URL(Astro.request.url, Astro.site);

/**
 * Enforce some standard canonical URL formatting across the site.
 */
function formatCanonicalURL(url: string | URL) {
    const path = url.toString();
    const hasQueryParams = path.includes('?');
    // If there are query params, make sure the URL has no trailing slash
    if (hasQueryParams) {
        path.replace(/\/?$/, '');
    }
    // otherwise, canonical URL always has a trailing slash
    return path.replace(/\/?$/, hasQueryParams ? '' : '/');
}
---

<!-- High Priority Global Metadata -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>{title}</title>
<meta name="generator" content={Astro.generator} />

<!-- Fonts -->
<link rel="preload" as="font" type="font/woff2" href={interWoff2} crossorigin="anonymous" />
<link rel="preload" as="font" type="font/woff2" href={alegreyaWoff2} crossorigin="anonymous" />

<!-- Low Priority Global Metadata -->
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="sitemap" href="/sitemap-index.xml" />
<link rel="alternate" type="application/rss+xml" href="/rss.xml" title="RSS" />

<!-- Page Metadata -->
<link rel="canonical" href={formatCanonicalURL(canonicalURL)} />
<meta name="description" content={description} />

<!-- Open Graph / Facebook -->
<meta property="og:type" content={pageType} />
<meta property="og:url" content={formatCanonicalURL(canonicalURL)} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
{resolvedImage?.src && <meta property="og:image" content={resolvedImage.src} />}
{resolvedImage?.alt && <meta property="og:image:alt" content={resolvedImage.alt} />}

<!-- X/Twitter -->
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:url" content={formatCanonicalURL(canonicalURL)} />
<meta property="twitter:title" content={title} />
<meta property="twitter:description" content={description} />
{resolvedImage?.src && <meta property="twitter:image" content={resolvedImage.src} />}
{resolvedImage?.alt && <meta name="twitter:image:alt" content={resolvedImage?.alt} />}
