<script lang="ts">
  import { onMount } from "svelte";
  import Header from "$lib/components/Header.svelte";
  import Footer from "$lib/components/Footer.svelte";
  import favicon from "$lib/assets/favicon.svg";
  import "$lib/styles/global.css";

  let { children } = $props();

  onMount(() => {
    const loadAnalytics = () => {
      if (document.querySelector('script[data-goatcounter-script="true"]'))
        return;

      const script = document.createElement("script");
      script.src = "https://stats.wsap.dev/count.js";
      script.async = true;
      script.defer = true;
      script.setAttribute("data-goatcounter", "https://stats.wsap.dev/count");
      script.setAttribute("data-goatcounter-script", "true");
      document.head.appendChild(script);
    };

    const runDeferredAnalytics = () => {
      const idleWindow = window as Window & {
        requestIdleCallback?: (
          callback: IdleRequestCallback,
          options?: IdleRequestOptions,
        ) => number;
      };

      if (typeof idleWindow.requestIdleCallback === "function") {
        idleWindow.requestIdleCallback(loadAnalytics, { timeout: 3000 });
        return;
      }
      window.setTimeout(loadAnalytics, 1500);
    };

    if (document.readyState === "complete") {
      runDeferredAnalytics();
      return;
    }

    window.addEventListener("load", runDeferredAnalytics, { once: true });
    return () => window.removeEventListener("load", runDeferredAnalytics);
  });
</script>

<svelte:head>
  <link rel="icon" href={favicon} />
  <meta name="color-scheme" content="light dark" />
</svelte:head>

<Header title="Berke Güzel" description="Super. Bad. Code." />

<main class="container">
  {@render children()}
</main>

<Footer />
