window.ModuleLoader = (function () {
  let currentModuleName = null;
  let currentModuleCssId = null;

  function removeCurrentModuleCss() {
    if (!currentModuleCssId) return;

    const existing = document.getElementById(currentModuleCssId);
    if (existing) existing.remove();

    currentModuleCssId = null;
  }

  function ensureModuleCss(moduleName) {
    removeCurrentModuleCss();

    const cssId = `module-css-${moduleName}`;
    const href = `/static/css/pages/${moduleName}.css`;

    const link = document.createElement("link");
    link.id = cssId;
    link.rel = "stylesheet";
    link.href = href;

    document.head.appendChild(link);
    currentModuleCssId = cssId;
  }

  async function loadModule(moduleName, options = {}) {
    const root = document.getElementById("module-root");
    if (!root) return;

    try {
      root.innerHTML = ``;

      ensureModuleCss(moduleName);

      const response = await fetch(`/modules/${moduleName}`);
      if (!response.ok) {
        throw new Error(`${moduleName} modülü bulunamadı`);
      }

      const html = await response.text();
      root.innerHTML = html;
      currentModuleName = moduleName;

      // DOM'un tamamen işlenmesi için iki frame bekle
      await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));

      if (typeof window.initModule === "function") {
        window.initModule(moduleName, options);
      }
    } catch (error) {
      root.innerHTML = `
        <div class="module-error">
          <strong>Modül yüklenemedi</strong>
          <div>${escapeHtml(error.message)}</div>
        </div>
      `;
    }
  }

  function getCurrentModule() {
    return currentModuleName;
  }

  function escapeHtml(value) {
    return String(value || "")
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#39;");
  }

  return {
    loadModule,
    getCurrentModule
  };
})();