<script>
  import TailwindStyles from "./TailwindStyles.svelte";
  import Router from "svelte-spa-router";
  import { replace } from "svelte-spa-router";
  import { wrap } from "svelte-spa-router/wrap";
  import { addMessages, init, getLocaleFromNavigator } from "svelte-i18n";
  import en from "./locales/en.json";
  import de from "./locales/de.json";
  addMessages("en", en);
  addMessages("de", de);
  init({
    fallbackLocale: "en",
    initialLocale: getLocaleFromNavigator(),
  });
  //
  import Login from "./components/Login.svelte";
  import Dashboard from "./components/Dashboard.svelte";
  import NotFound from "./components/NotFound.svelte";
  import store from "./store.js";
  import ForgotPassword from "./components/ForgotPassword.svelte";
  import About from "./components/About.svelte";
  store.init();
  //
  const checkAuth = (detail) => {
    if (!$store.isLoggedIn) {
      console.log("not authed");
      replace("/login/");
      return false;
    }
    return true;
  };
  const routes = {
    "/about": About,
    "/login": Login,
    "/forgot_password": ForgotPassword,
    "/dashboard": wrap({ component: Dashboard, conditions: [checkAuth] }),
    "/": wrap({ component: Dashboard, conditions: [checkAuth] }),
    // Using named parameters, with last being optional
    // "/author/:first/:last?": Author,

    // Wildcard parameter
    // "/book/*": Book,

    // Catch-all
    // This is optional, but if present it must be the last
    "*": NotFound,
  };
  //
  if ("serviceWorker" in navigator) {
    window.addEventListener("load", () => {
      navigator.serviceWorker.register("/sw.js").then(
        (registration) => {
          console.log(`sw successful with scope: ${registration.scope}`);
        },
        (err) => {
          console.log(`sw failed: ${err}`);
        }
      );
    });
  }
</script>

<Router {routes} />
