<script lang="ts">
    import { onMount } from 'svelte';
    import { pb, currentUser } from '$lib/pocketbase';
    import { user } from '$lib/userStore';

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

    let actions: Action[] = [];

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

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

        // 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: `created >= '${today}'`
        });

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

{#if $currentUser}
    <div>
        <button on:click={() => recordAction('awake')}>Awake</button>
        <button on:click={() => recordAction('asleep')}>Asleep</button>
        <button on:click={() => recordAction('food')}>Food</button>
        <button on:click={() => recordAction('diaper')}>Diaper</button>
        <button on:click={() => recordAction('poop')}>Poop</button>

        <h2>Today</h2>
        <ul>
            {#each actions as action}
            <li>{action.type} at {new Date(action.created).toLocaleTimeString('en-NL', { hour: '2-digit', minute: '2-digit' })}</li>
            {/each}
        </ul>
    </div>
{/if}