<template>
  <div class="h-100 position-relative">
    <!-- BACKGROUND (mode) -->
    <component :is="mode" />

    <!-- FOREGROUND (texts) -->
    <section v-for="group in groups" :key="group.id" class="split-screen">
      <text-card :id="group.id" @open="openText(group, $event)" @close="closeText(group)" />
      <div>
        <text-card
          v-for="id in group.prod" :key="id"
          :id="id"
          @close="closeText(group, id)"
        />
      </div>
    </section>
  </div>
</template>

<script>
import { CardList, CardMap, TreeMap } from './library'
import TextCard from '@/components/text/TextCard'


export default {
  name: 'Library',

  components: {
    CardList,
    CardMap,
    TreeMap,
    TextCard
  },

  props: {
    mode: { type: String, required: true },
    texts: { type: Array, required: true }
  },

  computed: {
    groups () {
      return this.texts.map(text => {
        const [id, ...prod] = text
        return { id, prod }
      })
    }
  },

  methods: {
    openText (group, id) {
      if (group.prod.includes(id)) return
      group.prod.push(id)
      this.updateQuery(this.groups)
    },

    closeText (group, id) {
      if (!id) {
        this.updateQuery(this.groups.filter(grp => grp !== group))
      } else {
        group.prod = group.prod.filter(id_ => id_ !== id)
        this.updateQuery(this.groups)
      }
    },

    updateQuery (groups) {
      // Update the route's query (will not reload the page) and let vue determine what changed.
      this.$router.push({
        query: {
          mode: this.mode,
          texts: groups.map(grp => [grp.id, ...grp.prod])
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
