<script>
  export let collection = {items: []};
  export let narrow = false;
  export let selected = "";

  let categories = [];
  $: {
    categories.splice(0);

    for (const item of collection.items) {
      let category = categories.find(c => c.name === item.metadata.category);
      if (category == null) {
        category = {name: item.metadata.category, list: []}
        categories.push(category);
      }

      category.list.push({id: item.name, label: item.metadata.name, color: item.metadata.color || "#ffffff"});
    }

    categories.sort((a,b) => {
      if (a.list.length !== b.list.length) {
        return b.list.length - a.list.length;
      } else {
        return b.name.localeCompare(a.name);
      }
    });
    for (const category of categories) {
      category.list.sort((a,b) => a.id.localeCompare(b.id));
    }
  }
</script>

<div class="layout">
  <div class="page" class:narrow>
    <slot></slot>
  </div>
  <div class="menu">
    <h1>
      <a class:selected={selected === "INDEX"} href="/">n.vmaple.dev</a>
    </h1>
    {#each categories as category (category.name)}
      <h2>{category.name}</h2>
      {#each category.list as item (item.id)}
        <span style="--color: {item.color}">
          <a class:selected={selected === item.id} href="/{item.id}">{item.label}</a>
        </span>
      {/each}
    {/each}
  </div>
</div>

<style>
  div.menu {
    position: fixed;
    left: 0;
    top: 0;
    height: 100%;
    overflow-y: auto;
    box-sizing: border-box;
    padding: 0em;
    background: #222;
    border: 1px solid #000;
    width: 12em;
  }

  div.menu h1 {
    font-size: 1.5em;
    text-align: center;
    padding: 0.5em 0 0 0;
  }
  div.menu h1 a {
    line-height: 1.5em;
  }

  div.menu h2 {
    font-size: 1.15em;
    color: #555;
    padding: 0.5em 1ch 0 1ch;
    margin: 0;
  }

  div.menu a {
    display: block;
    padding: 0.125em 2ch;
    line-height: 1.5em;
    text-decoration: none;
    font-size: 0.9em;
    color: #aaa;
  }
  div.menu a.selected {
    background: #2a2a2a;
    color: var(--color);
    padding-left: 2.5ch;
  }
  div.menu a:hover {
    background: #191919;
  }

  div.layout {
    padding-left: 12em;
  }

  div.page {
    width: 120ch;
    max-width: 90%;
    box-sizing: border-box;
    margin: 2em auto;
		background: #222;
		border: 1px solid #000;
		border-radius: 1em;
		padding: 1em;
		text-align: center;
	}
  div.page.narrow {
    width: 75ch;
  }

  @media screen and (max-width: 720px) {
    div.layout {
      padding-left: 0;
    }

    div.menu {
      position: initial;
      width: 32ch;
      max-width: 90%;
      margin: 2em auto;
      background: #222;
      border: 1px solid #000;
      border-radius: 1em;
      padding: 1em;
      text-align: center;
    }

    div.menu a.selected {
      padding-left: 2ch;
      font-weight: 600;
    }
  }

</style>