{% extends "base.html" %}

<!-- Header is now overridden via partials/header.html -->
{% block header %}
  {% include "partials/header.html" %}
{% endblock %}

<!-- SEO Meta Tags -->
{% block extrahead %}
{{ super() }}
{% include "partials/seo.html" %}
<script>
  (function () {
    var KEY = "ekgf-theme";

    function getCookie(name) {
      var m = document.cookie.match(
        new RegExp("(^|;\\s*)" + name + "=([^;]*)"),
      );
      return m ? decodeURIComponent(m[2]) : "";
    }

    function setCookie(name, value) {
      var host = window.location.hostname || "";
      var domain = host.endsWith(".ekgf.org") ? "; domain=.ekgf.org" : "";
      document.cookie =
        name +
        "=" +
        encodeURIComponent(value) +
        "; path=/; max-age=31536000; samesite=lax" +
        domain;
    }

    function applyPaletteFromCookie() {
      if (typeof __md_get !== "function" || typeof __md_set !== "function")
        return;

      var t = getCookie(KEY);
      if (t !== "dark" && t !== "light") return;

      var desired = t === "dark" ? "slate" : "default";
      var palette = __md_get("__palette");

      if (!palette || typeof palette !== "object") {
        __md_set("__palette", { color: { scheme: desired } });
        return;
      }

      if (!palette.color || typeof palette.color !== "object") {
        palette.color = {};
      }

      if (palette.color.scheme === desired) return;

      palette.color.scheme = desired;
      __md_set("__palette", palette);
    }

    function syncCookieFromPalette() {
      if (typeof __md_get !== "function") return;
      var palette = __md_get("__palette");
      if (palette && palette.color && typeof palette.color === "object") {
        var scheme = palette.color.scheme;
        if (scheme === "slate") setCookie(KEY, "dark");
        if (scheme === "default") setCookie(KEY, "light");
      }
    }

    // Run early so Material can pick up the palette
    applyPaletteFromCookie();

    document.addEventListener("DOMContentLoaded", function () {
      // Ensure cookie exists even if user never toggles
      syncCookieFromPalette();

      var ref = document.querySelector("[data-md-component=palette]");
      if (ref) {
        ref.addEventListener("change", function () {
          syncCookieFromPalette();
        });
      }

      // Theme toggle is now directly included in tabs.html, no JS relocation needed

      // Sync tabs search input with Material's search system
      (function syncTabsSearch() {
        function setupSearchSync() {
          var tabsSearchInput = document.querySelector(".ekgf-header-search__input");
          var materialSearchInput = document.querySelector(".md-header .md-search__input");
          var searchCheckbox = document.querySelector("#__search");
          
          if (!tabsSearchInput || !materialSearchInput) return;
          
          // Focus sync: ensure search overlay logic is initialized
          tabsSearchInput.addEventListener("focus", function() {
            if (searchCheckbox && !searchCheckbox.checked && tabsSearchInput.value.length > 0) {
              searchCheckbox.checked = true;
              searchCheckbox.dispatchEvent(new Event("change"));
            }
          });

          // Sync tabs search input with Material's search
          tabsSearchInput.addEventListener("input", function (e) {
            var value = e.target.value;
            materialSearchInput.value = value;
            
            // Trigger input event on Material's input
            if (materialSearchInput.dispatchEvent) {
              materialSearchInput.dispatchEvent(
                new Event("input", { bubbles: true })
              );
            }

            // Open/close search overlay based on input length
            if (searchCheckbox) {
              if (value.length > 0 && !searchCheckbox.checked) {
                searchCheckbox.checked = true;
                searchCheckbox.dispatchEvent(new Event("change"));
              } else if (value.length === 0 && searchCheckbox.checked) {
                searchCheckbox.checked = false;
                searchCheckbox.dispatchEvent(new Event("change"));
              }
            }
          });

          // Sync back from Material search (e.g. if cleared via 'X' button)
          materialSearchInput.addEventListener("input", function () {
            if (tabsSearchInput.value !== materialSearchInput.value) {
              tabsSearchInput.value = materialSearchInput.value;
            }
          });
          
          // Handle Escape key to close search
          tabsSearchInput.addEventListener("keydown", function(e) {
            if (e.key === "Escape" && searchCheckbox) {
              searchCheckbox.checked = false;
              searchCheckbox.dispatchEvent(new Event("change"));
              tabsSearchInput.blur();
            }
          });
        }
        
        setupSearchSync();
        setTimeout(setupSearchSync, 100);
        setTimeout(setupSearchSync, 500);
      })();

      // Logo and OMG logo are now rendered via template override (partials/header.html), no JS needed

      // Move the repository widget from header to footer
      (function ensureFooterRepo() {
        var footerInner = document.querySelector(".md-footer-meta__inner");
        if (!footerInner) return;
        if (footerInner.querySelector(".ekgf-footer-repo")) return;

        var headerSource = document.querySelector(".md-header__source");
        if (!headerSource) return;

        // Find the anchor tag inside the header source
        var headerSourceLink = headerSource.querySelector("a.md-source");
        if (!headerSourceLink) return;

        // Create a simple wrapper div
        var wrapper = document.createElement("div");
        wrapper.classList.add("ekgf-footer-repo");

        // Create a new anchor tag that matches the header exactly
        var footerLink = document.createElement("a");
        footerLink.href = headerSourceLink.href;
        footerLink.title = headerSourceLink.title || "Go to repository";
        footerLink.classList.add("md-source");
        footerLink.setAttribute("data-md-component", "source");
        footerLink.textContent = headerSourceLink.textContent.trim();

        wrapper.appendChild(footerLink);

        var social = footerInner.querySelector(".md-social");
        if (social) {
          footerInner.insertBefore(wrapper, social);
        } else {
          footerInner.appendChild(wrapper);
        }
      })();
    });
  })();
</script>
{% endblock %}

<!-- Override tabs to include search box (now handled in partials/tabs.html) -->
{% block tabs %}
  {{ super() }}
{% endblock %}

<!-- Footer is overridden via partials/footer.html -->
{% block footer %}
  {% include "partials/footer.html" %}
{% endblock %}

<!-- Content -->
{% block content %}
{% if page.meta.generated == True %}
{% set _ = page.__setattr__('edit_url', '') %}
{% endif %}
{{ super() }}

{% if page.meta.authors %}
<small>
  {% for author in page.meta.authors %}
    {% if loop.first %}
      Author:
    {% endif %}
    <a href="https://maturity.ekgf.org/other/author/{{ author.lower().split(' ') | join('-') }}/">{{ author }}</a>{%- if not loop.last -%},{%- endif -%}
  {% endfor %}
</small>
{% endif %}

{% if config.extra.giscus and config.extra.giscus.repo_id %}
<!-- Giscus - generated by https://giscus.app -->
<h2 id="__comments">{{ lang.t("meta.comments") }}</h2>
<script
        src="https://giscus.app/client.js"
        data-repo="{{ config.repo_name }}"
        data-repo-id="{{ config.extra.giscus.repo_id }}"
        data-category="{{ config.extra.giscus.category.name }}"
        data-category-id="{{ config.extra.giscus.category.id }}"
        data-mapping="title"
        data-reactions-enabled="1"
        data-emit-metadata="0"
        data-input-position="bottom"
        data-theme="light"
        data-lang="en"
        crossorigin="anonymous"
        async
>
</script>

<!-- Reload on palette change -->
<script>
    var palette = __md_get("__palette")
    if (palette && typeof palette.color === "object")
        if (palette.color.scheme === "slate") {
            var giscus = document.querySelector("script[src*=giscus]")
            giscus.setAttribute("data-theme", "dark")
        }

    /* Register event handlers after documented loaded */
    document.addEventListener("DOMContentLoaded", function() {
        var ref = document.querySelector("[data-md-component=palette]")
        ref.addEventListener("change", function() {
            var palette = __md_get("__palette")
            if (palette && typeof palette.color === "object") {
                var theme = palette.color.scheme === "slate" ? "dark" : "light"

                /* Instruct Giscus to change theme */
                var frame = document.querySelector(".giscus-frame")
                frame.contentWindow.postMessage(
                    { giscus: { setConfig: { theme } } },
                    "https://giscus.app"
                )
            }
        })
    })
</script>
{% endif %}
{% endblock %}
