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

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

	onMount(async () => {
		actions = await fetchAllActions();
	});

	async function fetchAllActions() {
		// Fetch all actions. Adjust as needed for date range or pagination
		const result = await pb.collection('actions').getList(1, 1000);
		return result.items;
	}

    let actions: Action[] = [];
  
    // Function to get the day of the week from a date string
    const getDayOfWeek = (dateString: string) => {
      return new Date(dateString).getDay();
    };
  
    // Function to get the hour of the day from a date string
    const getHourOfDay = (dateString: string) => {
      return new Date(dateString).getHours();
    };
  
    // Days of the week for headers
    const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  
    // Generate hours for the grid
    const hours = Array.from({ length: 24 }, (_, i) => i);

    // Function to format hour in HH:mm format
    const formatHour = (hour: number) => {
      return `${hour.toString().padStart(2, '0')}:00`;
    };
  </script>
  
  <style>
    .calendar {
      display: grid;
      grid-template-columns: 60px repeat(7, 1fr); /* Adjusted for hour column */
      text-align: center;
    }
    .day-header, .hour-label {
      font-weight: bold;
      border: 1px solid #ccc;
    }
    .hour {
      border: 1px solid #ccc;
      height: 60px;
    }
    .event {
      background-color: lightblue;
      border-radius: 4px;
      padding: 2px;
      text-align: left;
    }

    .event--food {
      background-color: lightgreen;
    }
    .event--poop {
      background-color: burlywood;
    }
    .event--asleep {
      background-color: lightblue;
    }
   .event--awake {
      background-color: gold;
    }
    .event--diaper {
      background-color: lightpink;
    }
  </style>
  
  <div class="calendar">
    <!-- Empty cell for top-left corner -->
    <div></div>
    
    <!-- Day Headers -->
    {#each daysOfWeek as day}
      <div class="day-header">{day}</div>
    {/each}
  
    <!-- Hour Labels and Calendar Grid -->
    {#each hours as hour}
      <div class="hour-label">{formatHour(hour)}</div> <!-- Hour label -->
      {#each daysOfWeek as _, dayIndex}
        <div class="hour">
          {#each actions as action}
            {#if getDayOfWeek(action.created) === dayIndex && getHourOfDay(action.created) === hour}
              <div class="event event--{action.type}">{action.type}</div>
            {/if}
          {/each}
        </div>
      {/each}
    {/each}
  </div>
  