<template>


    <li>
        <div class="node" :class="{ selected: isSelected }" @click="handleClick"
            :style="{ paddingLeft: hasChildren ? `${level * 15 + 10}px` : `${level * 20 + 10}px` }">
            <i v-if="hasChildren" :class="isOpen ? 'far fa-minus-square' : 'far fa-plus-square'"></i>
            {{ node.label }} ({{ node.quantity }})
        </div>
        <transition name="slide">
            <ul v-show="isOpen" v-if="hasChildren">
                <tree-node v-for="child in node.children" :key="child.id" :node="child" :level="level + 1"
                    :selected-node="selectedNode" @select-node="handleSelectNode" />
            </ul>
        </transition>
    </li>
</template>

<script>
export default {
    name: 'TreeNode',
    components: {
        TreeNode: () => import('./LocationTreeNode.vue')
    },
    props: {
        node: {
            type: Object,
            required: true
        },
        level: {
            type: Number,
            required: true
        },
        selectedNode: {
            type: Object,
            default: null
        }
    },
    data() {
        return {
            isOpen: false
        };
    },
    computed: {
        hasChildren() {
            return this.node.children && this.node.children.length > 0;
        },
        isSelected() {
            return this.selectedNode && this.selectedNode.id === this.node.id;
        }
    },
    methods: {
        toggle() {
            if (this.hasChildren) {
                this.isOpen = !this.isOpen;
            }
        },
        handleClick() {
            this.$emit('select-node', this.node);
            this.toggle();
        },
        handleSelectNode(node) {
            this.$emit('select-node', node);
        }
    }
};
</script>

<style scoped>
div {
    cursor: pointer;
}

li {
    font-size: .83rem;
    padding: 0px;
    border: 1px solid #deebfd;
    border-bottom-width: 0;
    border-left-width: 0;
    border-right-width: 0;
}

.node {
    cursor: pointer;
    position: relative;
    padding: 8px;
}

.node.selected {
    background-color: #f5f5f5;
    border-right: 6px solid #ffcb05;
    font-weight: bold;
}

.node:hover {
    background-color: #f5f5f5;
}

.node::before {
    content: '';
    position: absolute;
    left: -10px;
    top: 0;
    bottom: 0;
    /* border-left: 1px solid #ccc; */
}

.node::after {
    content: '';
    position: absolute;
    left: -10px;
    top: 50%;
    width: 10px;
    /* border-top: 1px solid #ccc; */
}



li:hover {
    /* background-color: beige; */
}

/* Transition styles */
.slide-enter-active,
.slide-leave-active {
    transition: all 0.5s ease;
}

.slide-enter-from,
.slide-leave-to {
    height: 0;
    opacity: 0;
    overflow: hidden;
}
</style>