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

    <!-- FOREGROUND (texts) -->
    <section v-for="parent in parents" :key="parent.id" class="split-screen">
      <text-card :id="parent.id" @open="openText" @close="closeText" />
      <div>
        <text-card
          v-for="id in parent.children" :key="id"
          :id="id"
          @close="closeText(parent.id, $event)"
        />
      </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: {
    parents () {
      return this.texts.map(text => {
        const [id, ...children] = text
        return { id, children }
      })
    }
  },

  methods: {
    openText (id, childId) {
      const parent = this.parents.find(p => p.id === id)
      if (parent && (childId === undefined || parent.children.includes(childId))) return

      if (!parent) {
        this.parents.push({ id, children: childId ? [childId] : [] })
      } else if (childId) {
        parent.children.push(childId)
      }
      this.updateQuery(this.parents)
    },

    closeText (id, childId) {
      const parent = this.parents.find(p => p.id === id)
      if (!childId) {
        this.updateQuery(this.parents.filter(p => p !== parent))
      } else {
        parent.children = parent.children.filter(childId_ => childId_ !== childId)
        this.updateQuery(this.parents)
      }
    },

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

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