---
import type { ComponentProps } from "astro/types"

import Canonical from "./Canonical.astro"
import Description from "./Description.astro"
import Favicon from "./Favicon.astro"
import Keywords from "./Keywords.astro"
import LanguageAlternates from "./LanguageAlternates.astro"
import OpenGraph from "./OpenGraph.astro"
import type { OpenGraphImage } from "./OpenGraph.astro"
import Robots from "./Robots.astro"
import Schema from "./Schema.astro"
import Title from "./Title.astro"
import Twitter from "./Twitter.astro"

export type Props = {
  title: string
  titleTemplate?: `${string}%s${string}`
  description?: string | false
  canonical?: string | false
  keywords?: string[] | false
  charset?: string
  viewport?: string
  image?: OpenGraphImage | false
  robots?: ComponentProps<typeof Robots> | false
  openGraph?: ComponentProps<typeof OpenGraph> | false
  twitter?: ComponentProps<typeof Twitter> | false
  favicon?: ComponentProps<typeof Favicon> | false
  schema?: ComponentProps<typeof Schema> | false
  languageAlternates?: ComponentProps<typeof LanguageAlternates>["alternates"] | false
}

const {
  title,
  titleTemplate,
  description,
  canonical,
  keywords,
  charset = "UTF-8",
  viewport = "width=device-width, initial-scale=1.0",
  image,
  robots,
  openGraph,
  twitter,
  favicon,
  schema,
  languageAlternates,
} = Astro.props

const enabled = <T,>(value: T | false | undefined): value is T => {
  return value !== false && value !== undefined
}

const og =
  openGraph !== false
    ? {
        title,
        description: enabled(description) ? description : undefined,
        image: enabled(image) ? image : undefined,
        url: enabled(canonical) ? canonical : undefined,
        ...openGraph,
      }
    : false

const tw =
  twitter !== false
    ? {
        title,
        description: enabled(description) ? description : undefined,
        image: enabled(image) ? image : undefined,
        url: enabled(canonical) ? canonical : undefined,
        ...twitter,
      }
    : false
---

<head>
  <slot name="top" />

  <meta charset={charset} />
  <meta name="viewport" content={viewport} />

  <Title value={title} template={titleTemplate} />

  {enabled(description) && <Description value={description} />}
  {enabled(canonical) && <Canonical value={canonical} />}
  {enabled(keywords) && <Keywords value={keywords} />}
  {enabled(robots) && <Robots {...robots} />}
  {enabled(og) && <OpenGraph {...og} />}
  {enabled(tw) && <Twitter {...tw} />}
  {enabled(favicon) && <Favicon {...favicon} />}
  {enabled(schema) && <Schema {...schema} />}
  {enabled(languageAlternates) && <LanguageAlternates alternates={languageAlternates} />}

  <slot />
</head>
