<script>
  import Icon from "$/client/components/Icon.svelte";
  import { onMount } from "svelte";
  import api from "$/client/api.js";
  import { log } from "$/client/logging.js";

  let all_icons = [];
  let inactive = false;
  let icons = [];
  export let size=48;
  let search = "";
  export let labels=true;
  export let tight=false;
  let message = "";

  const search_icons = (pattern) => {
    icons = all_icons.filter(i => i.includes(pattern));
  }

  $: search_icons(search);

  const gen_code = (name) => {
    let results = `<Icon name="${name}" size="${size}" />`;

    navigator.clipboard.writeText(results).then(() => {
      message = `${name} copied to clipboard.`;
    }, () => {
      message = `${name} copy FAILED.`;
    });
  }

  onMount(async () => {
    const [status, data] = await api.get("/icons/index.json");

    if(status === 200) {
      icons = data;
      all_icons = icons;
    } else {
      log.error("Invalid response", status, data);
    }
  });
</script>

<style>
  icons {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-template-rows: auto;
    row-gap: 1rem;
  }

  icons.tight {
    grid-template-columns: repeat(10, 1fr);
  }

  icons icon {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  search-bar {
    display: flex;
    justify-content: space-evenly;
    flex-wrap: nowrap;
  }

  search-bar input#size {
    width: 6ch;
  }

  search-bar input#search {
    min-width: 30ch;
    max-wdith: 30ch;
    width: 30ch;
  }

  search-bar span {
    padding-right: 1rem;
  }

  @media only screen and (max-width: 900px) {
    icons {
      grid-template-columns: repeat(4, 1fr);
    }
  }

  @media only screen and (max-width: 600px) {
    icons {
      grid-template-columns: repeat(3, 1fr);
    }
  }

</style>

<search-bar>
  <span on:click={ () => inactive = !inactive }><Icon name={ inactive ? 'eye' : 'eye-off'} size="24" /></span>
  <input bind:value={ search } id="search" > <Icon name="x" size="24" /> <input bind:value={ size } id="size" >
  <span>{ message }</span>
</search-bar>

<icons class:tight={ tight }>
{#each icons as name}
  <icon on:click={ () => gen_code(name) }>
  <Icon name={ name } size={ size } inactive={inactive}/>
  {#if labels}
    <span>{ name }</span>
  {/if}
  </icon>
{:else}
  <h1>No Icons</h1>
{/each}
</icons>
