<script lang="ts">
  import Card from './Card.svelte';
  import CardInput from './CardInput.svelte';

  import LZString from 'lz-string';

  const MAX_CARDS = 9;
  let cards = [];
  let mhp = {
    name: "Minor healing potion",
    type: "Item 1",
    tags: ["Consumable", "Healing", "Magical", "Necromancy", "Positive", "Potion"],
    attributes: `<p><b>Usage</b> Held in 1 hand; <b>Bulk</b> L</p>
	      <p><b>Activate (A)</b> Interact</p>`,
    description: `<p>A healing potion is a vial of a ruby-red liquid that imparts a tingling sensation as the drinker’s wounds heal rapidly. When you drink a healing potion, you regain 2d8+5 Hit Points.</p>`
  };

  if (window.location.hash !== "") {
    cards = JSON.parse(LZString.decompressFromEncodedURIComponent(window.location.hash.substring(1)));
  } else {
    cards = [{id: 0, ...mhp}];
  }
  
  function get_idx_by_id(id) {
    for(let idx = 0; idx < cards.length; idx++) {
      if(id === cards[idx].id) {
	return idx
      }
    }
  }

  //let card_selected = 0;
  //$: selected_card = cards[card_selected];

  let selector = cards[0].id;
  //$: selector = cards[card_selected].id;
  $: selected_card = cards.filter(x => x.id === selector)[0];
  $: selected_idx = get_idx_by_id(selector);

  $: window.location.hash = LZString.compressToEncodedURIComponent(JSON.stringify(cards));

  function change_tags(e) {
    selected_card.tags = e.detail.tags.split(',').map(x => x.replace(/\s+/g, '')).filter(x => x != '');
    cards[selected_idx] = selected_card;
  }
  
  function add_card() {
    if (cards.length < MAX_CARDS) {
      cards = [...cards, {id: cards[cards.length-1].id+1, ...mhp}];
      selector = cards[cards.length-1].id;
    }
  }

  function remove_card() {
    console.log(cards);
    console.log(selected_idx);
    if (cards.length > 1) { // remove only if there is more than 1 card
      cards = cards.filter(x => x.id != selector);
      if (selected_idx >= cards.length) {
	selector = cards[cards.length-1].id;
      } else {
	selector = cards[selected_idx].id;
      }
    }
  }
</script>

<main>
  <section class="controls">
    <h1>PF2e card generator</h1>
    <CardInput bind:name={selected_card.name} bind:type={selected_card.type} tags={selected_card.tags} bind:attributes={selected_card.attributes} bind:description={selected_card.description} on:change_tags={change_tags} on:add_card={add_card} on:remove_card={remove_card}/>
  </section>
  <section class="cards">
    {#each cards as card, idx (card.id)}
      <div class="card">
	<Card {...card}/>
	<input class="card-selector" type="radio" bind:group={selector} value={card.id}/>
      </div>
    {/each}
  </section>
</main>

<style>
  @media print {
    @page {
      margin: 0;
    }
    .controls {
      display: none;
    }
    .card-selector {
      display: none;
    }
  }
  .cards {
    display: flex;
    flex-wrap: wrap;
  }
  h1 {
    text-transform: uppercase;
    font-size: 4em;
    font-weight: 100;
  }

</style>
