const appId = "taskapp";
const appName = "Task App Dev";
const appElementId = `pui-app-container-${appId}`;
const pipelinePath = "/pipeline";
const pipelineLinkText = "Pipeline";
const getWindow = () => {
  try {
    window.parent.document;
    return window.parent;
  } catch (err) {
    return window;
  }
};
let host = null;
let parentHistory = null;
let logger = null;
const browserWindow = getWindow();
browserWindow.__TEST__ = browserWindow.__TEST__ ?? {
  logs: []
};
window.emui = window.emui || { uuid: crypto.randomUUID() };
window.emui.app = {
  uuid: window.emui.uuid,
  init: async (options) => {
    browserWindow.__TEST__.logs.push(`${appId} initializing`);
    host = options.host;
    parentHistory = options.history;
    logger = options.logger;
  },
  mount: async () => {
    browserWindow.__TEST__.logs.push(`${appId} mounting`);
    const appContainer = document.getElementById(appElementId);
    if (appContainer) {
      const mainElement = document.createElement("main");
      appContainer.appendChild(mainElement);
      const pageHeaderEle = document.createElement("h1");
      pageHeaderEle.textContent = appName;
      mainElement.appendChild(pageHeaderEle);
      const contentEle = document.createElement("p");
      contentEle.textContent = "Go to ";
      mainElement.appendChild(contentEle);
      const linkEle = document.createElement("a");
      linkEle.href = "#";
      linkEle.onclick = () => {
        parentHistory?.push?.(pipelinePath);
      };
      linkEle.textContent = pipelineLinkText;
      contentEle.appendChild(linkEle);
      browserWindow.__TEST__.logs.push(`${appId} mounted`);
    } else {
      throw new Error(
        `App container element with id ${appElementId} not found`
      );
    }
  },
  unmount: () => {
    browserWindow.__TEST__.logs.push(`${appId} unmounting`);
    const appContainer = document.getElementById(appElementId);
    if (appContainer) {
      appContainer.removeChild(appContainer.getElementsByTagName("main")[0]);
    }
    browserWindow.__TEST__.logs.push(`${appId} unmounted`);
    return Promise.resolve();
  }
};
browserWindow.emui?.registerApp?.({ appId, app: window.emui.app });
