<script>
    import { onMount } from "svelte";
    import Router from "svelte-spa-router";
    import { location, querystring, replace } from "svelte-spa-router";
    import routes from "@/routes/app.js";
    import { storeConfig, storeLang, storeLocales, storePages } from "@/stores/config.store";
    import { user } from "@/stores/app.store";

    import helpers from "@/libs/helpers";

    import Header from "@/pages/Header.svelte";
    import Footer from "@/pages/Footer.svelte";

    export let lang;
    export let config;

    $: isReady = $storeConfig && $storeLang && $storeLocales && $storePages;

    function redirect() {
        const url = window.location.href.split("?");
        const paramRedirect = helpers.getUrlParameter(url[1], "redirect", false);
        if (paramRedirect) {
            window.location.replace(url[0] + "#/" + paramRedirect);
        }
    }

    onMount(() => {
        redirect();
        // TODO: Manage lang variable. Priority is: 1. storeLang / 2. paramLang / 3. browserLang
        const paramLang = helpers.getUrlParameter($querystring, "lang", false);

        if (!$storeLang) {
            const currentLang = paramLang || lang;
            storeLang.setLang(currentLang);
        }
        // if (!paramLang || $storeLang != paramLang) {
        //     const query = helpers.checkQueryParams($querystring, {
        //         lang: $storeLang,
        //     });
        //     replace([$location, query].join("?"));
        // }
        storeConfig.setConfig(config);

        fetch($storeConfig.api.me)
            .then(function (response) {
                return response.json();
            })
            .then(function (json) {
                // console.log(json);
                $user = json;
            })
            .catch((err) => console.error(err));
    });
</script>

{#if isReady}
    {#if $storeConfig.app.displayHeader}
        <Header />
    {/if}
    <Router {routes} />
    {#if $storeConfig.app.displayFooter}
        <Footer />
    {/if}
{/if}

<style>
</style>
