---
import "../styles/global.css";
import logo from "../../pic/智引未来GEO_透明背景_矢量版.svg";
import favicon from "../../pic/智引未来GEO_原始版本_渐变背景.png";
import { getImage } from "astro:assets";
import { site } from "../data/site";
import ContactDialog from "../components/ContactDialog.astro";

interface Props {
  title: string;
  description?: string;
  keywords?: string | readonly string[];
  image?: string;
  imageAlt?: string;
  ogType?: "website" | "article";
  noindex?: boolean;
  publishedTime?: string;
  modifiedTime?: string;
  articleSection?: string;
  articleAuthor?: string;
  jsonLd?: Record<string, unknown> | Record<string, unknown>[];
}

const {
  title,
  description = site.seo.description,
  keywords = site.seo.keywords,
  image = "/og-cover.svg",
  imageAlt = site.seo.imageAlt,
  ogType = "website",
  noindex = false,
  publishedTime,
  modifiedTime,
  articleSection,
  articleAuthor,
  jsonLd = [],
} = Astro.props;
const cleanMeta = (value: string) => value.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
const metaTitle = cleanMeta(title);
const metaDescription = cleanMeta(description);
const metaKeywords = (typeof keywords === "string" ? keywords.split(",") : keywords)
  .map((keyword) => cleanMeta(keyword))
  .filter(Boolean)
  .join(",");
const optimizedLogo = await getImage({ src: logo, width: 420, format: "png" });
const optimizedFavicon = await getImage({ src: favicon, width: 128, height: 128, format: "png" });
const canonical = new URL(Astro.url.pathname, Astro.site).href;
const ogImage = new URL(image, Astro.site).href;
const organizationLd = {
  "@context": "https://schema.org",
  "@type": ["ProfessionalService", "Organization"],
  "@id": new URL("/#organization", Astro.site).href,
  name: site.brand.name,
  alternateName: [site.brand.englishName],
  legalName: site.brand.legalName,
  url: new URL("/", Astro.site).href,
  logo: new URL(optimizedLogo.src, Astro.site).href,
  slogan: site.brand.tagline,
  description: site.home.subhead,
  telephone: site.contact.phone,
  email: site.contact.email,
  address: {
    "@type": "PostalAddress",
    streetAddress: site.contact.address,
    addressLocality: site.contact.locality,
    addressRegion: site.contact.region,
    addressCountry: "CN",
  },
};
const websiteLd = {
  "@context": "https://schema.org",
  "@type": "WebSite",
  "@id": new URL("/#website", Astro.site).href,
  url: new URL("/", Astro.site).href,
  name: site.brand.name,
  alternateName: site.brand.englishName,
  inLanguage: "zh-CN",
  publisher: { "@id": new URL("/#organization", Astro.site).href },
};
const webPageLd = {
  "@context": "https://schema.org",
  "@type": "WebPage",
  "@id": `${canonical}#webpage`,
  url: canonical,
  name: metaTitle,
  description: metaDescription,
  inLanguage: "zh-CN",
  isPartOf: { "@id": new URL("/#website", Astro.site).href },
  about: { "@id": new URL("/#organization", Astro.site).href },
  primaryImageOfPage: { "@type": "ImageObject", url: ogImage, caption: imageAlt },
};
const pageLd = Array.isArray(jsonLd) ? jsonLd : [jsonLd];
const allLd = [organizationLd, websiteLd, webPageLd, ...pageLd.filter((item) => Object.keys(item).length > 0)];
const serializedLd = JSON.stringify(allLd).replace(/</g, "\\u003c");
---
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#FFFFFF" />
    <meta name="color-scheme" content="light" />
    <title>{metaTitle}</title>
    <meta name="description" content={metaDescription} />
    <meta name="keywords" content={metaKeywords} />
    <meta name="robots" content={noindex ? "noindex,nofollow" : "index,follow,max-image-preview:large,max-snippet:-1,max-video-preview:-1"} />
    <link rel="canonical" href={canonical} />
    <link rel="icon" href={optimizedFavicon.src} type="image/png" sizes="128x128" />
    <link rel="apple-touch-icon" href={optimizedFavicon.src} />
    <link rel="manifest" href="/site.webmanifest" />
    <link rel="alternate" hreflang="zh-CN" href={canonical} />
    <link rel="alternate" hreflang="x-default" href={canonical} />
    <meta property="og:type" content={ogType} />
    <meta property="og:title" content={metaTitle} />
    <meta property="og:description" content={metaDescription} />
    <meta property="og:url" content={canonical} />
    <meta property="og:image" content={ogImage} />
    <meta property="og:image:alt" content={imageAlt} />
    <meta property="og:site_name" content={site.brand.name} />
    <meta property="og:locale" content="zh_CN" />
    {publishedTime && <meta property="article:published_time" content={publishedTime} />}
    {modifiedTime && <meta property="article:modified_time" content={modifiedTime} />}
    {articleSection && <meta property="article:section" content={articleSection} />}
    {articleAuthor && <meta property="article:author" content={articleAuthor} />}
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content={metaTitle} />
    <meta name="twitter:description" content={metaDescription} />
    <meta name="twitter:image" content={ogImage} />
    <script type="application/ld+json" set:html={serializedLd} is:inline></script>
  </head>
  <body>
    <a class="skip-link" href="#main-content">跳到主要内容</a>
    <slot />
    <ContactDialog />
    <script is:inline>
      const header = document.querySelector('[data-header]');
      const syncHeader = () => header?.classList.toggle('is-scrolled', window.scrollY > 12);
      addEventListener('scroll', syncHeader, { passive: true }); syncHeader();
      const observer = 'IntersectionObserver' in window ? new IntersectionObserver((entries) => entries.forEach((entry) => {
        if (entry.isIntersecting) { entry.target.classList.add('is-visible'); observer.unobserve(entry.target); }
      }), { threshold: 0.08 }) : null;
      document.querySelectorAll('[data-reveal]').forEach((el) => observer ? observer.observe(el) : el.classList.add('is-visible'));
      document.querySelectorAll('[data-mobile-nav] a').forEach((link) => link.addEventListener('click', () => link.closest('details')?.removeAttribute('open')));

      const contactDialog = document.querySelector('[data-contact-dialog]');
      const isMobileDevice = () => matchMedia('(max-width: 760px), (hover: none) and (pointer: coarse)').matches;
      document.addEventListener('click', (event) => {
        const trigger = event.target.closest('[data-open-contact]');
        const phoneLink = event.target.closest('a[href^="tel:"]');
        if (!contactDialog || (!trigger && (!phoneLink || isMobileDevice()))) return;
        event.preventDefault();
        contactDialog.showModal();
      });
      contactDialog?.querySelector('[data-contact-dialog-close]')?.addEventListener('click', () => contactDialog.close());
      contactDialog?.addEventListener('click', (event) => { if (event.target === contactDialog) contactDialog.close(); });
    </script>
  </body>
</html>
