<script lang="ts">
  import '../app.css';
  import '$lib/iconify-offline';
  import { page } from '$app/stores';
  import Header from '$lib/components/Header.svelte';
  import HeaderOverlay from '$lib/components/HeaderOverlay.svelte';
  import Footer from '$lib/components/Footer.svelte';
  import TopBanner from '$lib/components/TopBanner.svelte';
  import TranslationProvider from '$lib/components/TranslationProvider.svelte';
  import Breadcrumbs from '$lib/ui/Breadcrumbs.svelte';
  import type { LayoutData } from './$types';
  import { ensureTransformedImage } from '$lib/rusty-image';
  import { DEFAULT_SOCIAL_IMAGE_URL, SOCIAL_IMAGE_TRANSFORM } from '$lib/constants';

  let { data, children }: { data: LayoutData; children: import('svelte').Snippet } = $props();

  // Per-page SEO data from $page.data
  const pageData = $derived($page.data as {
    seoTitle?: string;
    seoDescription?: string;
    socialImage?: string;
    breadcrumbItems?: { href?: string; label: string }[];
    topBanner?: { banner: unknown; resolvedImages: string[]; headline?: string; subheadline?: string } | null;
  });

  const baseUrl = $derived(data.siteBaseUrl ?? '');
  const canonical = $derived(`${baseUrl}${$page.url.pathname}`);

  function applyTemplate(tpl: string | null | undefined, value: string): string {
    if (!tpl) return value;
    return tpl.replace(/\$1/g, value);
  }

  const rawSeoTitle = $derived(pageData?.seoTitle ?? data.siteName);
  const rawSeoDescription = $derived(pageData?.seoDescription ?? '');
  const seoTitle = $derived(applyTemplate(data.seoTitleTemplate, rawSeoTitle));
  const seoDescription = $derived(applyTemplate(data.seoDescriptionTemplate, rawSeoDescription));

  const socialImageUrl = $derived.by(() => {
    const raw = pageData?.socialImage ?? data.logoSocialImage ?? data.logoUrl ?? DEFAULT_SOCIAL_IMAGE_URL;
    if (!raw) return '';
    if (raw.startsWith('//')) return `https:${raw}`;
    if (raw.startsWith('http://') || raw.startsWith('https://')) return raw;
    if (raw.startsWith('/')) return `${baseUrl}${raw}`;
    return raw;
  });

  const breadcrumbItems = $derived(pageData?.breadcrumbItems ?? []);
  const topBannerData = $derived(pageData?.topBanner ?? null);

  const jsonLdScript = $derived(
    `<script type="application/ld+json">${JSON.stringify({
      '@context': 'https://schema.org',
      '@type': 'WebSite',
      name: data.siteName,
      url: baseUrl,
      inLanguage: 'de-DE',
    })}<\/script>`,
  );

  const formbricksAppUrl = String(import.meta.env.PUBLIC_FORMBRICKS_APP_URL ?? '').replace(/\/$/, '');
  const formbricksEnvId = String(import.meta.env.PUBLIC_FORMBRICKS_ENVIRONMENT_ID ?? '').trim();
  const formbricksScript =
    formbricksAppUrl && formbricksEnvId
      ? `<script>(function(){var appUrl=${JSON.stringify(formbricksAppUrl)};var environmentId=${JSON.stringify(formbricksEnvId)};if(!appUrl||!environmentId)return;var t=document.createElement('script');t.type='text/javascript';t.async=true;t.src=appUrl+'/js/formbricks.umd.cjs';var e=document.getElementsByTagName('script')[0];if(e&&e.parentNode)e.parentNode.insertBefore(t,e);setTimeout(function(){if(window.formbricks&&typeof window.formbricks.setup==='function'){window.formbricks.setup({environmentId:environmentId,appUrl:appUrl});}},500);})();<\/script>`
      : '';
</script>

<svelte:head>
  <meta name="theme-color" content="#ffffff" />
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
  <link rel="alternate" type="application/rss+xml" title="Beiträge" href="/posts/rss.xml" />
  <link rel="sitemap" href="/sitemap.xml" />
  <link rel="icon" href="/favicons/favicon.ico" sizes="any" />
  <link rel="icon" type="image/png" sizes="16x16" href="/favicons/favicon-16x16.png" />
  <link rel="icon" type="image/png" sizes="32x32" href="/favicons/favicon-32x32.png" />
  <link rel="icon" type="image/png" sizes="96x96" href="/favicons/favicon-96x96.png" />
  <link rel="icon" type="image/png" sizes="192x192" href="/favicons/android-icon-192x192.png" />
  <link rel="apple-touch-icon" sizes="57x57" href="/favicons/apple-icon-57x57.png" />
  <link rel="apple-touch-icon" sizes="60x60" href="/favicons/apple-icon-60x60.png" />
  <link rel="apple-touch-icon" sizes="72x72" href="/favicons/apple-icon-72x72.png" />
  <link rel="apple-touch-icon" sizes="76x76" href="/favicons/apple-icon-76x76.png" />
  <link rel="apple-touch-icon" sizes="114x114" href="/favicons/apple-icon-114x114.png" />
  <link rel="apple-touch-icon" sizes="120x120" href="/favicons/apple-icon-120x120.png" />
  <link rel="apple-touch-icon" sizes="144x144" href="/favicons/apple-icon-144x144.png" />
  <link rel="apple-touch-icon" sizes="152x152" href="/favicons/apple-icon-152x152.png" />
  <link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-icon-180x180.png" />
  <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#2d7a45" />
  <meta name="msapplication-TileColor" content="#ffffff" />
  <meta name="msapplication-TileImage" content="/favicons/ms-icon-144x144.png" />
  <title>{seoTitle}</title>
  {#if seoDescription}
    <meta name="description" content={seoDescription} />
  {/if}
  <link rel="canonical" href={canonical} />
  <!-- Open Graph -->
  <meta property="og:type" content="website" />
  <meta property="og:url" content={canonical} />
  <meta property="og:title" content={seoTitle} />
  {#if seoDescription}
    <meta property="og:description" content={seoDescription} />
  {/if}
  {#if socialImageUrl}
    <meta property="og:image" content={socialImageUrl} />
    <meta property="og:image:width" content={String(SOCIAL_IMAGE_TRANSFORM.width)} />
    <meta property="og:image:height" content={String(SOCIAL_IMAGE_TRANSFORM.height)} />
  {/if}
  <meta property="og:locale" content="de_DE" />
  <meta property="og:site_name" content={data.siteName} />
  <!-- Twitter -->
  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:url" content={canonical} />
  <meta name="twitter:title" content={seoTitle} />
  {#if seoDescription}
    <meta name="twitter:description" content={seoDescription} />
  {/if}
  {#if socialImageUrl}
    <meta name="twitter:image" content={socialImageUrl} />
  {/if}
  <!-- JSON-LD WebSite -->
  {@html jsonLdScript}
  {#if import.meta.env.PUBLIC_UMAMI_SCRIPT_URL && import.meta.env.PUBLIC_UMAMI_WEBSITE_ID}
    <script
      defer
      src={import.meta.env.PUBLIC_UMAMI_SCRIPT_URL}
      data-website-id={import.meta.env.PUBLIC_UMAMI_WEBSITE_ID}
    ></script>
  {/if}
  {#if import.meta.env.PUBLIC_ANALYTICS_PM86_SITE_ID}
    <script
      defer
      src="https://analytics.pm86.de/api/script.js"
      data-site-id={import.meta.env.PUBLIC_ANALYTICS_PM86_SITE_ID}
    ></script>
  {/if}
  {#if formbricksScript}
    {@html formbricksScript}
  {/if}
</svelte:head>

<TranslationProvider translations={data.translations}>
  <div class="flex min-h-screen flex-col text-zinc-900">
    <Header
      links={data.headerLinks}
      socialLinks={data.socialLinks}
      logoUrl={data.logoUrl}
      logoSvgHtml={data.logoSvgHtml}
      translations={data.translations}
    />
    <HeaderOverlay />

    {#if topBannerData}
      <TopBanner
        banner={topBannerData.banner as import('$lib/cms').FullwidthBannerEntry | null}
        resolvedImages={topBannerData.resolvedImages}
        headline={topBannerData.headline}
        subheadline={topBannerData.subheadline}
      />
    {/if}

    <main class="flex-1 min-h-[60em]">
      <div class="container-custom pb-12">
        {#if breadcrumbItems.length > 0}
          <Breadcrumbs items={breadcrumbItems} />
        {/if}
        {@render children()}
      </div>
    </main>

    <Footer footer={data.footerData} translations={data.translations} />
  </div>
</TranslationProvider>
