<template>
  <li v-if="!isCycle" class="area-tree-node" :class="{ 'is-open': isOpen, 'is-leaf': isLeaf }">
    <article class="area-tree-card" @click="goToDetail">
      <button
        class="tree-toggle"
        :class="{ 'text-primary': !isLeaf, 'text-muted': isLeaf }"
        type="button"
        :disabled="isLeaf"
        :aria-expanded="isOpen"
        @click.stop="toggle"
      >
        {{ isLeaf ? "·" : isOpen ? "−" : "+" }}
      </button>

      <div class="area-tree-info">
        <h2>{{ area.display_name }}</h2>
        <p class="text-muted">
          <GnBadge variant="secondary">{{ area.type }}</GnBadge>
          <code>{{ area.alias }}</code>
        </p>
      </div>

      <div class="area-tree-actions">
        <AreaFavoriteButton :area-id="area.id" />
      </div>
    </article>

    <ul v-if="area.children?.length && isOpen" class="area-tree-children">
      <AreaTreeNode
        v-for="child in area.children"
        :key="child.id"
        :area="child"
        :ancestors="nextAncestors"
      />
    </ul>
  </li>
  <li v-else class="area-tree-node">
    <article class="area-tree-card area-tree-cycle text-danger">
      Cycle skipped for area ID {{ area.id }}
    </article>
  </li>
</template>

<script setup>
import { computed } from "vue";
import { useRouter } from "vue-router";
import { GnBadge } from "gnexus-ui-kit/vue";
import { useAreasStore } from "../../../stores/areas";
import AreaFavoriteButton from "./AreaFavoriteButton.vue";

const props = defineProps({
  area: {
    type: Object,
    required: true,
  },
  ancestors: {
    type: Array,
    default: () => [],
  },
});

const router = useRouter();
const areasStore = useAreasStore();

const isOpen = computed(() => areasStore.isNodeExpanded(props.area.id));
const isLeaf = computed(() => !props.area.children?.length);
const isCycle = computed(() => props.ancestors.includes(String(props.area.id)));
const nextAncestors = computed(() => [...props.ancestors, String(props.area.id)]);

function toggle() {
  areasStore.toggleNode(props.area.id);
}

function goToDetail() {
  router.push({ name: "area-detail", params: { id: String(props.area.id) } });
}
</script>
