<script lang="ts">
    import {locals} from "../ts/stores.js";
    import BaseLayout from "./layouts/BaseLayout.svelte";
    import Message from "./components/Message.svelte";
    import WebsocketClient from "../ts/WebsocketClient.js";
    import {Time} from "../../common/Time.js";
    import {onMount} from "svelte";

    const validUntil = parseFloat($locals.validUntil as string);

    function isValid() {
        return new Date().getTime() < validUntil;
    }

    let countdown;
    let validUntilDate = new Date(validUntil);
    $: countdown = $locals.isPreRender ? '...' : Time.humanizeTimeTo(validUntilDate);

    onMount(() => {
        const interval = setInterval(() => {
            validUntilDate = new Date(validUntil);
        }, 1000);

        if (isValid()) {
            const webSocket = new WebsocketClient($locals.websocketUrl as string, (websocket, e) => {
                if (e.data === 'refresh') {
                    window.location.reload();
                }
            });

            webSocket.run();
        }

        return () => {
            clearInterval(interval);
        };
    });
</script>

<BaseLayout h1="Authentication lobby" title="{$locals.app.name} authentication lobby">
    <div class="container">
        <div class="panel">
            <Message type="success" sticky
                          content={`We sent a link to ${$locals.email}. To authenticate, open it from any device.`}/>
            <Message type="info" discreet sticky raw
                          content={`This link will be valid for ${countdown} and can only be used once.`}/>

            <p class="center">Waiting for you to open the link...</p>
        </div>
    </div>
</BaseLayout>
