import { Component, c, FunctionalComponent } from "atomico";

export function getPathname(): string {
  // eslint-disable-next-line no-restricted-globals
  return location.pathname;
}

export function getComponentOrDefine(name: string, comp: FunctionalComponent) {
  if (!customElements.get(name)) { customElements.define(name, c(comp)); }
  // customElement(name, comp as Component); }
  return customElements.get(name);
}

export function redirect(pathname: string): void {
  if (!pathname.startsWith("http")) {
    if (pathname === getPathname()) return;
    // eslint-disable-next-line no-restricted-globals
    history.pushState({}, "history", pathname);
    window.dispatchEvent(new PopStateEvent("popstate"));
    window.location.reload();
  } else {
    window.open(pathname);
  }
}

export function subscribe(handler: () => void): () => void {
  window.addEventListener("popstate", handler);
  return () => window.removeEventListener("popstate", handler);
}
