<script>
import { onMount } from 'svelte';
import { listen } from '@tauri-apps/api/event';
import { invoke } from '@tauri-apps/api/core';
import { getVersion } from '@tauri-apps/api/app';

import { appState, acceptRequest, cleanupRequest } from './lib/state.js';
import { views, currentView, navigate } from './lib/routing.js';

import Approve from './views/Approve.svelte';
import CreatePassphrase from './views/CreatePassphrase.svelte';
import Unlock from './views/Unlock.svelte';

// set up app state
invoke('get_config').then(config => $appState.config = config);
invoke('get_session_status').then(status => $appState.sessionStatus = status);
getVersion().then(version => $appState.appVersion = version);
invoke('get_setup_errors')
    .then(errs => {
        $appState.setupErrors = errs.map(e => ({msg: e, show: true}));
    });


// set up event handlers
listen('credential-request', (tauriEvent) => {
    $appState.pendingRequests.put(tauriEvent.payload);
});

listen('request-cancelled', (tauriEvent) => {
    const id = tauriEvent.payload;
    if (id === $appState.currentRequest?.id) {
        cleanupRequest();
    }
    else {
        const found = $appState.pendingRequests.find_remove(r => r.id === id);
    }
});

listen('locked', () => {
    $appState.sessionStatus = 'locked';
});


// set up navigation
$views = import.meta.glob('./views/*.svelte', {eager: true});
navigate('Home');


// ready to rock and roll
acceptRequest();
</script>


<svelte:window 
    on:click={() => invoke('signal_activity')}
    on:keydown={() => invoke('signal_activity')}
/>


{#if $appState.sessionStatus === 'empty'}
    <!-- Empty state (no passphrase) takes precedence over everything -->
    <CreatePassphrase />
{:else if $appState.currentRequest !== null}
    <!-- if a request is pending, show approval flow (will include unlock if necessary) -->
    <Approve />
{:else if $appState.sessionStatus === 'locked'}
    <!-- if session is locked and no request is pending, show unlock screen -->
    <Unlock />
{:else}
    <!-- normal operation -->
    <svelte:component this="{$currentView}" />
{/if}
