(function () {
  const SSE_PORT = 8765;
  const RECONNECT_DELAY = 5000; // milliseconds

  let eventSource = null;
  let reconnectTimer = null;

  function reloadStylesheets() {
    // Force reload all stylesheets
    const links = document.querySelectorAll('link[rel="stylesheet"]');
    links.forEach(link => {
      const href = link.href.split('?')[0];
      link.href = href + '?t=' + new Date().getTime();
    });
  }

  function connect() {
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }

    if (eventSource) {
      eventSource.close();
    }

    const url = `${window.location.protocol}//${window.location.hostname}:${SSE_PORT}/events`;
    eventSource = new EventSource(url);

    eventSource.onmessage = function (event) {
      try {
        const data = JSON.parse(event.data);
        if (data.type === "reload") {
          console.log("Repository updated, reloading page...");
          
          // First reload stylesheets
          reloadStylesheets();
          
          // Then hard reload the page after a brief delay
          setTimeout(() => {
            window.location.reload(true);
          }, 100);
        }
      } catch (e) {
        console.error("Error parsing SSE message:", e);
      }
    };

    eventSource.onerror = function (error) {
      console.log("SSE connection error, will reconnect...");
      eventSource.close();
      // Attempt to reconnect
      reconnectTimer = setTimeout(connect, RECONNECT_DELAY);
    };

    eventSource.onopen = function () {
      console.log("Connected to auto-refresh service");
    };
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", connect);
  } else {
    connect();
  }

  window.addEventListener("beforeunload", function () {
    if (eventSource) {
      eventSource.close();
    }
  });
})();