//@ts-check

import { changeTitle } from "../utils/changeTitle.mjs";
import { getCurrentHashUrl } from "../utils/getCurrentHashUrl.mjs";
import { fetchMarkdown } from "../utils/fetchMarkdown.mjs";
import { rewriteLocalUrls } from "../utils/rewriteLocalUrls.mjs";
import { hasNoHashUrl } from "../utils/getCurrentHashUrl.mjs";
import { mode } from "./mode.mjs";

/**
 * Sets up a listener for hashchange events.
 * Loads the provided default Href if none is set by the user
 * @param {string} defaultHref
 * @param {(content: DocumentFragment, raw: string) => void} onPageLoaded
 */
export const bootstrapRouter = async (defaultHref, onPageLoaded) => {
  /**
   * Listens to hashchange event, and attempts to read the url.
   * @param {HashChangeEvent} [_evt]
   */
  const onHashChange = async (_evt) => {
    const { path } = getCurrentHashUrl();
    if (!path) {
      return false;
    }
    mode.loading.on();
    const { title, raw, content } = await fetchMarkdown(path);
    changeTitle(title);
    rewriteLocalUrls(content);
    onPageLoaded(content, raw);
    mode.loading.off();
  };

  window.addEventListener("hashchange", onHashChange);

  const load = () => {
    if (hasNoHashUrl()) {
      window.location.hash = `#${defaultHref}`;
    } else {
      onHashChange();
    }
  };

  return load
};
