---
import yaml from "js-yaml";
import fs from "fs";

const { seo } = Astro.props;

// Load global SEO config
const globalSeo = yaml.load(
  fs.readFileSync("./src/content/seo/home.yaml", "utf8")
);

const { site, company } = globalSeo;

const {
  title = site.name,
  description = site.description,
  url = "/",
  image = site.logo,
  keywords = [],
  schema = {}
} = seo ?? {};

const canonical = site.url + url;

/* PREPARE JSON-LD AS SAFE STRINGS */

const schemaWebsite = JSON.stringify({
  "@context": "https://schema.org",
  "@type": "WebSite",
  "url": site.url,
  "name": site.name,
  "potentialAction": {
    "@type": "SearchAction",
    "target": site.url + "/wyszukiwarka?query={search_term_string}",
    "query-input": "required name=search_term_string"
  }
});

const schemaLocalBusiness = JSON.stringify({
  "@context": "https://schema.org",
  "@type": "LocalBusiness",
  "name": company.name,
  "image": site.url + company.logo,
  "telephone": company.phone,
  "email": company.email,
  "address": {
    "@type": "PostalAddress",
    "streetAddress": company.street,
    "addressLocality": company.city,
    "postalCode": company.postal,
    "addressCountry": company.country
  },
  "geo": {
    "@type": "GeoCoordinates",
    "latitude": company.lat,
    "longitude": company.lon
  },
  "url": site.url
});

/* Extra schema if passed from page */
const schemaExtra = Object.keys(schema).length > 0
  ? JSON.stringify(schema)
  : null;
---
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <title>{title}</title>
  <meta name="description" content={description} />

  {keywords.length > 0 && (
    <meta name="keywords" content={keywords.join(", ")} />
  )}

  <link rel="canonical" href={canonical} />

  <!-- OG -->
  <meta property="og:type" content="website" />
  <meta property="og:title" content={title} />
  <meta property="og:description" content={description} />
  <meta property="og:url" content={canonical} />
  <meta property="og:site_name" content={site.name} />
  <meta property="og:image" content={image} />

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

  <!-- JSON-LD (Website) -->
  <script type="application/ld+json">{schemaWebsite}</script>

  <!-- JSON-LD (LocalBusiness) -->
  <script type="application/ld+json">{schemaLocalBusiness}</script>

  <!-- Optional per-page schema -->
  {schemaExtra && (
    <script type="application/ld+json">{schemaExtra}</script>
  )}

  <slot />
</head>
