(() => {
  const registry = new Map();
  let currentId = null;

  async function destroyCurrent(ctx) {
    if (!currentId) return;
    const handlers = registry.get(currentId);
    if (handlers && typeof handlers.destroy === 'function') {
      await handlers.destroy(ctx || {});
    }
  }

  async function initPage(id, ctx) {
    currentId = id || null;
    if (!currentId) return;
    const handlers = registry.get(currentId);
    if (handlers && typeof handlers.init === 'function') {
      await handlers.init(ctx || {});
    }
  }

  function register(id, handlers) {
    if (!id) return;
    registry.set(id, handlers || {});
  }

  function getCurrent() {
    return currentId;
  }

  window.PageRegistry = {
    register,
    destroyCurrent,
    initPage,
    getCurrent
  };
})();
