<template>
  <q-expansion-item
    v-if="hasChildren"
    v-model="expanded"
    dense
    expand-separator
    header-class="account-tree-row"
    :style="{ '--account-depth': depth }"
  >
    <template #header>
      <q-item-section class="account-code">{{ node.code }}</q-item-section>
      <q-item-section class="account-name text-weight-medium">
        {{ node.description }}
      </q-item-section>
      <q-item-section class="account-type">{{ node.chart_type }}</q-item-section>
    </template>

    <FinancialPlanAccountTreeNode
      v-for="child in node.children"
      :key="child.id"
      :node="child"
      :depth="depth + 1"
      :force-expanded="forceExpanded"
    />
  </q-expansion-item>

  <q-item
    v-else
    dense
    class="account-tree-row account-tree-leaf"
    :style="{ '--account-depth': depth }"
  >
    <q-item-section class="account-code">{{ node.code }}</q-item-section>
    <q-item-section class="account-name">{{ node.description }}</q-item-section>
    <q-item-section class="account-type">{{ node.chart_type }}</q-item-section>
  </q-item>
</template>

<script setup>
import { computed, ref, watch } from "vue";

defineOptions({ name: "FinancialPlanAccountTreeNode" });

const props = defineProps({
  node: { type: Object, required: true },
  depth: { type: Number, default: 0 },
  forceExpanded: { type: Boolean, default: false },
});

const hasChildren = computed(() => props.node.children?.length > 0);
const expanded = ref(props.depth === 0);

watch(
  () => props.forceExpanded,
  (value) => {
    if (value) expanded.value = true;
  },
  { immediate: true },
);
</script>

<style scoped>
:deep(.account-tree-row) {
  min-height: 48px;
  padding-left: calc(16px + (var(--account-depth) * 28px));
  border-bottom: 1px solid #dedede;
}

:deep(.account-tree-leaf) {
  padding-right: 56px;
}

:deep(.account-code) {
  flex: 0 0 18%;
  min-width: 80px;
}

:deep(.account-name) {
  flex: 1 1 auto;
  min-width: 0;
}

:deep(.account-type) {
  flex: 0 0 18%;
  min-width: 90px;
  align-items: flex-start;
}

@media (max-width: 599px) {
  :deep(.account-tree-row) {
    padding-left: calc(8px + (var(--account-depth) * 16px));
  }

  :deep(.account-code),
  :deep(.account-type) {
    flex-basis: 25%;
    min-width: 64px;
  }
}
</style>
