<script>
  import { Button, Offcanvas, Icon } from 'sveltestrap';
  import FilterItem from './FilterItem.svelte';
  import { writable } from 'svelte/store';

  export let calendarTree = [];
  export let selected = null;
  export let initial = [];

  let open = false;
  let icon;
  let generalToggle = writable(true);
  const toggle = () => (open = !open);

  let subSelections = Array.from({ length: Object.keys(calendarTree).length }, _ => []);
  $: selected = subSelections.flat();

  generalToggle.subscribe(v => (icon = v ? 'toggle-on' : 'toggle-off'));
</script>

<Button on:click={toggle} class="mb-3 col-6 mx-auto">
  <span class="me-2">Sélection des calendriers</span>
  <Icon name="chevron-double-right" />
</Button>

<Offcanvas
  isOpen={open}
  {toggle}
  scroll
  placement="start"
  header="Sélection des calendriers"
>
  <span class="fs-5 toggle" on:click={() => ($generalToggle = !$generalToggle)}>
    <Icon name={icon} />
    <span class="ms-2">Tous les calendriers</span>
  </span>
  <hr class="my-3" />

  {#each Object.entries(calendarTree) as [toplevel, subtrees], i}
    <FilterItem
      item={toplevel}
      children={subtrees}
      bind:selected={subSelections[i]}
      generalToggle={$generalToggle}
      {initial}
    />
  {/each}
</Offcanvas>

<style>
  .toggle {
    display: block;
    cursor: pointer;
    width: 100%;
    text-align: center;
  }
</style>
