<!-- App.svelte -->
<script>

    import { Router, Route } from "svelte-routing";
    import { onMount } from 'svelte';

    // Admin Layout
    import Admin from "./layouts/Admin.svelte";

    // Auth Layout
    import Auth from "./layouts/Auth.svelte";
    import { getCookie } from "components/Utils/CookieHandler.js";

    // No Layout Pages
    import Index from "./views/Index.svelte";
    import Landing from "./views/Landing.svelte";
    import Profile from "./views/Profile.svelte";
    import Login from "views/auth/Login.svelte";

    let isAuthenticated = false;

    async function validate_me() {
        const rawResponse = await fetch("https://wg.nnag.me/api2/wgCheckAuth", {
            "credentials": "include",
            "headers": {
                "Authorization": "Token " + getCookie('Token'),
                "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
                "Upgrade-Insecure-Requests": "1",
                "Sec-Fetch-Dest": "document",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "none",
                "Sec-Fetch-User": "?1"
            },
            "method": "GET",
            "mode": "cors"
        });

        const retVal = await rawResponse.json();
        isAuthenticated = retVal.Auth;
        console.log(retVal.Auth);
    }

    // validate_me().then( authVal.Auth => { isAuthenticated; });

    // let isAuthenticated = validate_me();

    export let url = "";

    validate_me();

</script>

<Router url="{url}">
  <!-- admin layout -->
    {#if isAuthenticated == true}
        <Route path="admin/*admin" component="{Admin}" />
        <!-- auth layout -->
        <!-- no layout pages -->
        <Route path="landing" component="{Landing}" />
        <Route path="profile" component="{Profile}" />
        <Route path="/" component="{Admin}" />
    {:else}
        <Route path="*" component="{Auth}" />
    {/if}
</Router>
