<template>
  <div class="accordion">
    <v-expander
      v-for="(item, i) of defaultSlots"
      :key="'expander-' + i"
      :ref="(el: any) => refs[i] = el"
      button-classes="btn btn-outline-secondary w-100"
      @expanded="onExpanded(i)"
    >
      <template #header>{{ getHeader(item, i) }}</template>
      <v-nodes :vnodes="item" />
    </v-expander>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, useSlots } from 'vue';
import VExpander from './expander.vue';
import VNodes from './v-nodes';

const refs = ref<{ [key: number]: { expand: () => void; collapse: () => void; } }>({});
const slots: any = useSlots();
const defaultSlots = computed(() => slots.default?.call(this) || []);
const getHeader = (obj: any, ix: number) => {
  const defaultHeader = 'Item ' + (ix + 1).toString();
  const props: any = obj?.props || { ['data-header']: defaultHeader };
  return props['data-header'] || defaultHeader;
};
const onExpanded = (ix: number) => {
  for (const key in refs.value) {
    if (Number(key) !== ix) {
      refs.value[key].collapse();
    }
  }
};
</script>

<style lang="scss">
.accordion {
  .expander:not(:first-child) {
    border-top-left-radius: 0;
    border-top-right-radius: 0;
    border-top-width: 0;
  }
  .expander:not(:last-child) {
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
  }
}
</style>
