<script>
    import { invoke } from '@tauri-apps/api/core';
    import { emit } from '@tauri-apps/api/event';
    import { onMount, createEventDispatcher } from 'svelte';

    import { appState } from '../lib/state.js';
    import { navigate } from '../lib/routing.js';
    import { getRootCause } from '../lib/errors.js';

    import ErrorAlert from '../ui/ErrorAlert.svelte';
    import Link from '../ui/Link.svelte';
    import PassphraseInput from '../ui/PassphraseInput.svelte';
    import ResetPassphrase from './passphrase/ResetPassphrase.svelte';
    import Spinner from '../ui/Spinner.svelte';
    import vaultDoorSvg from '../assets/vault_door.svg?raw';


    const dispatch = createEventDispatcher();

    let alert;
    let passphrase = '';
    
    let saving = false;
    async function unlock() {
        saving = true;
        try {
            await alert.run(async () => invoke('unlock', {passphrase}));
            $appState.sessionStatus = 'unlocked';
            emit('unlocked');
            dispatch('unlocked');
        }
        finally {
            saving = false;
        }

    }
</script>


<div class="fixed top-0 w-full p-2 text-center">
    <h1 class="text-3xl font-bold">Creddy is locked</h1>
</div>

<form action="#" on:submit|preventDefault="{unlock}" class="form-control space-y-4 max-w-sm m-auto p-4 h-screen justify-center">
    <div class="mx-auto">
        {@html vaultDoorSvg}
    </div>

    <label class="space-y-4">
        <h2 class="font-bold text-xl text-center">Please enter your passphrase</h2>

        <ErrorAlert bind:this="{alert}" />

        <!-- svelte-ignore a11y-autofocus -->
        <PassphraseInput autofocus="true" bind:value={passphrase} placeholder="correct horse battery staple" />
    </label>

    <button type="submit" class="btn btn-primary">
        {#if saving}
            <Spinner class="w-5 h-5" thickness="12"/>
        {:else}
            Submit
        {/if}
    </button>

    <ResetPassphrase />
</form>
