<script lang="ts">
    import { onMount } from 'svelte';
    import { pb, currentUser } from '$lib/pocketbase';
    import Counters from '$lib/components/counters.svelte';

    type Action = {
        type: string;
        timestamp: string;
    };

    let actions: Action[] = [];

    onMount(async () => {
        await fetchActions();
    });

    async function recordAction(actionType: string) {
        const action = { // No longer specifying a timestamp here
            type: actionType,
            timestamp: new Date().toISOString()
        };

        // Send action to PocketBase
        await pb.collection('actions').create(action);

        // Refresh actions list
        await fetchActions();
    }

    async function fetchActions() {
        // Fetch actions for the current day from PocketBase
        const today = new Date().toISOString().split('T')[0];
        const result = await pb.collection('actions').getList<Action>(1, 50, {
            filter: `timestamp >= '${today}'`,
            sort: 'timestamp'
        });

        // Assuming the items are in the 'items' property of the result
        actions = result.items;
    }

    $: isLastActionAsleep = actions.length > 0 && actions[actions.length - 1].type === 'asleep';
    $: isLastActionAwake = actions.length > 0 && actions[actions.length - 1].type === 'awake';
    $: isLastActionDiaper = actions.length > 0 && actions[actions.length - 1].type === 'diaper';
</script>

{#if $currentUser}
        <aside>
            {#if isLastActionAsleep}
                <button class="button--awake" on:click={() => recordAction('awake')}>Awake</button>
            {:else}
                {#if !isLastActionAwake}
                    <button class="button--awake" on:click={() => recordAction('awake')}>Awake</button>
                {/if}
                <button class="button--asleep" on:click={() => recordAction('asleep')}>Asleep</button>
                <button class="button--food" on:click={() => recordAction('food')}>Food</button>
                <button class="button--diaper" on:click={() => recordAction('diaper')}>Diaper</button>
                {#if isLastActionDiaper}
                    <button class="button--poop" on:click={() => recordAction('poop')}>Poop</button>
                {/if}
            {/if}
        </aside>

        <section>
            <h2>Today</h2>
            <div class="container">
                <div class="row">
                    <ul class="column">
                        {#each actions as action}
                        <li><span class="badge badge--{action.type}">{action.type}</span> at {new Date(action.timestamp).toLocaleTimeString('en-NL', { hour: '2-digit', minute: '2-digit' })}</li>
                        {/each}
                    </ul>
                    <Counters {actions} />
                </div>
            </div>
        </section>
{/if}