/**
 * @file preload-links.js
 * @description HTMX extension to extract <link rel="preload"> from preloaded HTML responses.
 * @generated By opencode (AI Agent)
 * @model gemini-3-flash-preview
 * @date Thu Mar 19 2026
 */
(function () {
  // Save the original XHR methods
  const originalOpen = XMLHttpRequest.prototype.open;
  const originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
  const originalSend = XMLHttpRequest.prototype.send;

  // We need to track which XHRs are preloads
  XMLHttpRequest.prototype.open = function () {
    this._isHtmxPreload = false;
    return originalOpen.apply(this, arguments);
  };

  XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
    if (header.toLowerCase() === "hx-preloaded" && value === "true") {
      this._isHtmxPreload = true;
    }
    return originalSetRequestHeader.apply(this, arguments);
  };

  XMLHttpRequest.prototype.send = function () {
    if (this._isHtmxPreload) {
      this.addEventListener("load", function () {
        // Parse the response text as HTML
        const parser = new DOMParser();
        const doc = parser.parseFromString(this.responseText, "text/html");

        // Find all preload links
        const links = doc.querySelectorAll('link[rel="preload"]');

        links.forEach((link) => {
          const href = link.getAttribute("href");
          // Only inject if the current document doesn't already have it
          if (
            href &&
            !document.querySelector(`link[rel="preload"][href="${href}"]`)
          ) {
            const newLink = document.createElement("link");
            newLink.rel = "preload";
            newLink.href = href;

            // Copy relevant attributes
            ["as", "type", "media", "fetchpriority", "crossorigin"].forEach(
              (attr) => {
                const val = link.getAttribute(attr);
                if (val) newLink.setAttribute(attr, val);
              },
            );

            document.head.appendChild(newLink);
          }
        });
      });
    }
    return originalSend.apply(this, arguments);
  };
})();
