/**
 * Site Tag — Schema Injection Module
 * ───────────────────────────────────
 * Fetches auto-inject schemas from the meSEO API and injects
 * <script type="application/ld+json"> into <head> if not already present.
 */

(function () {
  "use strict";

  function initSchemaInjection(cfg) {
    if (!cfg || !cfg.endpoint) return;

    var hostname = window.location.hostname.replace(/^www\./, "");
    var pathname = window.location.pathname || "/";
    var url = cfg.endpoint + "/api/site-tag/schema?domain=" + encodeURIComponent(hostname) + "&page=" + encodeURIComponent(pathname);

    // Collect existing schema types on the page
    var existingTypes = {};
    var existing = document.querySelectorAll('script[type="application/ld+json"]');
    for (var i = 0; i < existing.length; i++) {
      try {
        var parsed = JSON.parse(existing[i].textContent || "");
        if (parsed["@type"]) existingTypes[parsed["@type"]] = true;
        if (Array.isArray(parsed["@graph"])) {
          parsed["@graph"].forEach(function (item) {
            if (item["@type"]) existingTypes[item["@type"]] = true;
          });
        }
      } catch (e) { /* skip invalid */ }
    }

    // Fetch schemas from API
    fetch(url)
      .then(function (res) { return res.ok ? res.json() : { schemas: [] }; })
      .then(function (data) {
        if (!data.schemas || !data.schemas.length) return;
        data.schemas.forEach(function (schema) {
          // Skip if this @type already exists on the page
          if (schema["@type"] && existingTypes[schema["@type"]]) return;

          var script = document.createElement("script");
          script.type = "application/ld+json";
          script.textContent = JSON.stringify(schema);
          document.head.appendChild(script);
        });
      })
      .catch(function () { /* non-critical */ });
  }

  // Expose for the loader
  window.meSEOSchemaInject = { init: initSchemaInjection };
})();
