import moduleFactory, {
  destroyModulesWithin,
  initModulesWithin,
} from "../../scripts/lib/moduleFactory";
import Megamenu from "./Megamenu.static";
import "./styles/style.scss";

// Module configuration for Megamenu
export const customMegamenuModuleSelectorPairs = [
  {
    Module: Megamenu,
    name: "Megamenu",
    selector: "[data-megamenu]",
  },
];

// Global interface for standalone Megamenu
declare global {
  interface Window {
    ODSMegamenu: {
      Megamenu: typeof Megamenu;
      instances: Megamenu[];
      init: () => void;
      destroy: () => void;
      initModulesWithin: (container: any) => {};
      destroyModulesWithin: (
        container: any,
        removeOrphanedNodes?: boolean | undefined,
      ) => {};
    };
  }
}

// Initialize the global ODSMegamenu object
window.ODSMegamenu = window.ODSMegamenu || {
  Megamenu,
  instances: [],
  init: () => {
    // Initialize all Megamenu instances on the page
    window.ODSMegamenu.instances = moduleFactory(Megamenu, "[data-megamenu]");
  },
  destroy: () => {
    // Destroy all instances
    window.ODSMegamenu.instances.forEach((instance) => {
      if (instance && typeof instance.destroy === "function") {
        instance.destroy();
      }
    });
    window.ODSMegamenu.instances = [];
  },
  initModulesWithin,
  destroyModulesWithin,
};

// Auto-initialize when DOM is ready
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", () => {
    window.ODSMegamenu.init();
  });
} else {
  // DOM is already ready
  window.ODSMegamenu.init();
}

// Export for potential manual usage
export { Megamenu };
export default Megamenu;
