<template>
    <div class="tree-leaf">
        <div class="tree-leaf-content" :class="{ 'selected': isSelected }">

            <!-- Expand/Collapse Icon -->
            <div v-if="hasAvailableChildren" class="tree-expando" :class="{ 'expanded': expanded }"
                @click="toggleExpand">
                <i v-if="loadingChildren" class="fe fe-loader spin"></i>
                <template v-else>{{ expanded ? '-' : '+' }}</template>
            </div>
            <div v-else class="tree-expando hidden">+</div>

            <!-- Level Icon -->
            <i v-if="node.Level === 1" class="fe fe-map text-primary level-icon"></i>
            <i v-else-if="node.Level === 2" class="fe fe-navigation text-success level-icon"></i>
            <i v-else-if="node.Level === 3" class="fe fe-map-pin text-secondary level-icon"></i>

            <!-- Location Name -->
            <div class="tree-leaf-text" @click="hasAvailableChildren ? toggleExpand() : null">
                <span>{{ node.FullName || node.Name }}</span>
                <small v-if="node.Type" class="text-muted ms-1">({{ getTypeLabel(node.Type) }})</small>
                <span v-if="node.AvailableChildrenCount > 0" class="badge bg-info ms-1">
                    {{ node.AvailableChildrenCount }}
                </span>
            </div>

            <!-- Action Buttons -->
            <div class="tree-actions">
                <!-- Branch Actions (for nodes with children) -->
                <button v-if="hasAvailableChildren && side === 'available'" class="btn-tree btn-success"
                    @click.stop="$emit('select-branch', node)" title="Thêm tất cả phường/xã">
                    <i class="fe fe-plus"></i>
                </button>

                <button v-if="hasAvailableChildren && side === 'selected'" class="btn-tree btn-danger"
                    @click.stop="$emit('unselect-branch', node)" title="Bỏ tất cả phường/xã">
                    <i class="fe fe-minus"></i>
                </button>

                <!-- Single Actions (only for Level 3) -->
                <button v-if="node.Level === 3 && side === 'available'" class="btn-tree btn-primary"
                    @click.stop="$emit('select', node.Id)" title="Thêm phường/xã này">
                    <i class="fe fe-arrow-right"></i>
                </button>

                <button v-if="node.Level === 3 && side === 'selected' && isSelected" class="btn-tree btn-danger"
                    @click.stop="$emit('unselect', node.Id)" title="Bỏ phường/xã này">
                    <i class="fe fe-arrow-left"></i>
                </button>
            </div>
        </div>

        <!-- Children -->
        <div v-if="hasAvailableChildren && expanded" class="tree-child-leaves">
            <TreeNodeCoverage v-for="child in node.Children" :key="child.Id" :node="child" :selected-ids="selectedIds"
                :agency-id="agencyId" :side="side" @select="$emit('select', $event)"
                @unselect="$emit('unselect', $event)" @select-branch="$emit('select-branch', $event)"
                @unselect-branch="$emit('unselect-branch', $event)" @load-children="$emit('load-children', $event)" />
        </div>
    </div>
</template>

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

const props = defineProps({
    node: {
        type: Object,
        required: true
    },
    selectedIds: {
        type: Array,
        required: true
    },
    agencyId: {
        type: Number,
        required: true
    },
    side: {
        type: String,
        required: true
    }
});

const emit = defineEmits(['select', 'unselect', 'select-branch', 'unselect-branch', 'load-children']);

const expanded = ref(false);
const loadingChildren = ref(false);

const hasAvailableChildren = computed(() => {
    return props.node.AvailableChildrenCount > 0 || (props.node.Children && props.node.Children.length > 0);
});

const isSelected = computed(() => {
    return props.selectedIds.includes(props.node.Id);
});

// Auto expand selected tree nodes
if (props.side === 'selected' && props.node.Children && props.node.Children.length > 0) {
    expanded.value = true;
}

const getTypeLabel = (type) => {
    switch (type) {
        case 'Urban': return 'Nội thành';
        case 'SubUrban': return 'Ngoại thành';
        case 'NotServed': return 'Chưa phục vụ';
        default: return '';
    }
};

const toggleExpand = async () => {
    if (!hasAvailableChildren.value) return;

    if (!expanded.value && props.node.Children.length === 0) {
        // Need to load children
        loadingChildren.value = true;
        await emit('load-children', props.node);
        loadingChildren.value = false;
    }
    expanded.value = !expanded.value;
};
</script>

<style scoped>
.tree-leaf {
    position: relative;
}

.tree-leaf-content {
    display: flex;
    align-items: center;
    padding: 6px 8px;
    border-top: 1px solid #deebfd;
    transition: background-color 0.15s ease;
    cursor: pointer;
    min-height: 34px;
    font-size: 13px;
}

.tree-leaf-content:hover {
    background-color: #f5f5f5;
}

.tree-leaf-content.selected {
    background-color: #e7f3ff;
    border-right: 4px solid #007bff;
    font-weight: 600;
}

.tree-expando {
    width: 18px;
    height: 18px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-weight: bold;
    font-size: 14px;
    color: #6c757d;
    flex-shrink: 0;
    margin-right: 6px;
    user-select: none;
}

.tree-expando:hover {
    color: #007bff;
}

.tree-expando.hidden {
    visibility: hidden;
}

.tree-expando.expanded {
    color: #007bff;
}

.level-icon {
    font-size: 13px;
    margin-right: 6px;
    flex-shrink: 0;
}

.tree-leaf-text {
    flex: 1;
    line-height: 1.4;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 4px;
}

.tree-child-leaves {
    position: relative;
    padding-left: 20px;
}

.tree-child-leaves::before {
    content: '';
    position: absolute;
    left: 9px;
    top: 0;
    bottom: 0;
    width: 1px;
    background: #dee2e6;
}

.tree-actions {
    display: flex;
    gap: 4px;
    margin-left: auto;
    padding-left: 8px;
}

.btn-tree {
    padding: 1px 5px;
    font-size: 10px;
    border-radius: 3px;
    border: none;
    cursor: pointer;
    transition: all 0.15s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 18px;
    height: 18px;
    line-height: 1;
    color: white;
}

.btn-tree:hover {
    opacity: 0.85;
    transform: scale(1.1);
}

.btn-tree:active {
    transform: scale(0.95);
}

.btn-tree.btn-success {
    background-color: #28a745;
}

.btn-tree.btn-danger {
    background-color: #dc3545;
}

.btn-tree.btn-primary {
    background-color: #007bff;
}

.btn-tree i {
    font-size: 8px;
    margin: 0;
}

.badge {
    font-size: 9px;
    padding: 1px 4px;
}

.spin {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}
</style>
