<script>
    import { onMount } from "svelte";
    import { querystring, location, pop, replace } from "svelte-spa-router";
    import { Container, Row, Col, ButtonToolbar, Button } from "sveltestrap";

    import helpers from "@/libs/helpers/index.js";
    import { storeConfig, storeLang, storePages, storeLocalesViews } from "@/stores/config.store";

    $: isReady = localesView;

    // let query;
    // Update URL when query is modified
    $: {
        // replace([$location, query].join("?"));
        // console.log("page 1", $querystring);
        // replace(query ? [$location, query].join("?") : $location);
    }

    const view = "page";
    $: localesView = $storeLocalesViews[view];
    onMount(() => {
        console.log("page", $querystring);

        // query = helpers.checkQueryParams($querystring, { lang: $storeLang });
        // query = helpers.checkQueryParams($querystring);

        const file = $storeConfig.views[view].locales[$storeLang];
        storeLocalesViews.setLocalesView(view, file);

        loadPage();
    });

    let content = "Paramètre 'page' non définie";
    function loadPage() {
        const page = helpers.getUrlParameter($querystring, "page", false);
        const file = $storePages[page];
        if (file) {
            helpers.getFile(file).then((response) => {
                content = helpers.toHtml(response.data);
            });
        }
    }

    function cancel() {
        // query = helpers.updateQueryString($querystring, "page", false);
        pop();
    }
</script>

{#if isReady}
    <Container class="mt-3">
        <Row class="">
            <Col>
                {@html content}
            </Col>
        </Row>
        <Row>
            <Col>
                <ButtonToolbar class="float-end mt-3">
                    <Button outline color="dark" class="me-3" on:click={cancel}>Fermer</Button>
                </ButtonToolbar>
            </Col>
        </Row>
    </Container>
{/if}
