import { hydrate } from "svelte";
import Ligabereiche from "./pages/Ligabereiche.svelte";
import LigaTabelle from "./pages/LigaTabelle.svelte";
import { configuration, type ViewTypes } from "./stores/configuration";

function mountComponent() {
  const target = document.getElementById("mount-formationen");
  if (target) {
    configuration.sparte = target.getAttribute("data-sparte") || "stdlat";
    configuration.baseUri =
      target.getAttribute("data-base-uri") || "https://ev.tanzsport-portal.de";
    configuration.view = (target.getAttribute("data-view") ||
      "archiv") as ViewTypes;

    const lastUrlSegment =
      window.location.pathname
        .split("/")
        .filter((segment) => segment.length > 0)
        .pop() || "";

    const idRegex = /^([0-9a-z]{1,4})\-.+$/;
    const idMatch = lastUrlSegment.match(idRegex);
    if (idMatch) {
      const id = parseInt(idMatch[1], 36);
      if (!isNaN(id)) {
        const isTurnier = id % 2 === 1;
        const realId = id >> 1;

        hydrate(LigaTabelle, {
          target,
          props: {
            selection: {
              turnier: isTurnier ? realId : undefined,
              riege: !isTurnier ? realId : undefined,
            },
          },
        });
        return true;
      }
    }

    hydrate(Ligabereiche, {
      target,
    });
    return true;
  }

  return false;
}

if (!mountComponent()) {
  const observer = new MutationObserver(() => {
    if (mountComponent()) observer.disconnect();
  });

  observer.observe(document, {
    attributes: false,
    childList: true,
    characterData: false,
    subtree: true,
  });
}
