<script lang="ts">
  import data from '$lib/menus.json';
  import Fuse from 'fuse.js';

  interface MenuItem {
    description: string;
    vegan: boolean;
    day: string;
    date: string;
  }

  // Group menu items by date
  const groupedMenus: Record<string, Record<string, MenuItem[]>> = {};
  data.forEach((menu) => {
    if (!groupedMenus[menu.date]) {
      groupedMenus[menu.date] = {};
    }
    if (!groupedMenus[menu.date][menu.day]) {
      groupedMenus[menu.date][menu.day] = [];
    }
    groupedMenus[menu.date][menu.day].push(menu);
  });

  // Create a Fuse instance for fuzzy searching
  const fuse = new Fuse(data, {
    keys: ['description'],
    threshold: 0.4,
  });

  let searchQuery = '';
  let searchResults: MenuItem[] = [];

  function searchMenus() {
    const results = fuse.search(searchQuery).map((result) => result.item);
    searchResults = results.filter(
      (menu, index, self) =>
        index === self.findIndex((m) => m.description === menu.description),
    );
  }
</script>

<body>
  <main>
    <h2>Archives menus Dolma</h2>

    <div class="search-container">
      <input
        type="text"
        bind:value={searchQuery}
        on:input={searchMenus}
        placeholder="Chercher dans les menus"
      />
    </div>

    {#if searchResults.length > 0}
      <ul>
        {#each searchResults as menu}
          <li>{menu.description}</li>
        {/each}
      </ul>
    {:else}
      {#each Object.entries(groupedMenus) as [date, menusByDay]}
        <h2>{date}</h2>
        {#each Object.entries(menusByDay) as [day, menus]}
          <h3>{day}</h3>
          <ul>
            {#each menus as menu}
              <li>{menu.description}</li>
            {/each}
          </ul>
        {/each}
      {/each}
    {/if}
  </main>
</body>

<style>
  main {
    margin: 2em;
  }

  input[type='text'] {
    width: 80%;
    padding: 0.5em;
    font-size: 1em;
  }
</style>
