//@ts-check
import { fetchText } from "../utils/fetchText.mjs";
import { getElementByCSSSelector } from "../utils/getElementByCSSSelector.mjs";
import { onDocumentKeyUp } from "../utils/onDocumentKey.mjs";
import { parseFileList } from "../tickle/parseFileList.mjs";
import { createMenuEntriesFromFileList } from "../tickle/createMenuEntriesFromFileList.mjs";
import { sortFileListLines } from "../tickle/sortFileListLines.mjs";
import { mode } from "../tickle/mode.mjs";
import { bootstrapRouter } from "../tickle/bootstrapRouter.mjs";

export const bootstrap = async () => {
  const [Body, Source] = [
    "main",
    "#Source",
  ].map(getElementByCSSSelector);

  const lines = await fetchText("files.txt");
  const links = parseFileList(lines);
  const firstHref = links[0].href;
  sortFileListLines(links);
  Body.appendChild(createMenuEntriesFromFileList(links));
  
  bootstrapRouter(firstHref, (content, raw) => {
    Body.innerHTML = "";
    Source.innerHTML = raw;
    Body.appendChild(content);
  });

  onDocumentKeyUp("?", mode.sourceEnabled.toggle);
};

export default bootstrap;

if (!new URL(import.meta.url).searchParams.has("load")) {
  bootstrap();
}
