<script setup>
import { defineProps, defineEmits } from "vue";

const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  checkedNodes: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(["update:checkedNodes"]);

const toggleExpand = (node) => {
  node.expanded = !node.expanded;
};

const isChecked = (node) => {
  return props.checkedNodes.includes(node.value);
};

const isIndeterminate = (node) => {
  if (!node.children?.length) return false;
  
  const hasCheckedChild = node.children.some(child => 
    isChecked(child) || isIndeterminate(child)
  );
  const allChildrenChecked = node.children.every(child => isChecked(child));
  
  return hasCheckedChild && !allChildrenChecked;
};

const toggleNode = (node, checked) => {
  const newCheckedNodes = new Set(props.checkedNodes);
  
  const processNode = (currentNode) => {
    if (checked) {
      newCheckedNodes.add(currentNode.value);
    } else {
      newCheckedNodes.delete(currentNode.value);
    }
    
    currentNode.children?.forEach(child => {
      processNode(child);
    });
  };
  
  processNode(node);
  emit("update:checkedNodes", Array.from(newCheckedNodes));
};
</script>

<template>
  <ul class="pl-4 text-white ">
    <li v-for="node in data" :key="node.value" class="mb-2">
      <div class="flex items-center">
        <span 
          v-if="node.children?.length" 
          @click="toggleExpand(node)" 
          class="cursor-pointer mr-2 w-4 inline-block"
        >
          {{ node.expanded ? '▼' : '▶' }}
        </span>
        <span v-else class="w-4 mr-2"></span>
        
        <input
          type="checkbox"
          :checked="isChecked(node)"
          :indeterminate="isIndeterminate(node)"
          @change="toggleNode(node, $event.target.checked)"
          class="mr-2"
        />
        
        <span class="cursor-pointer" @click="toggleNode(node, !isChecked(node))">
          {{ node.label }}
        </span>
      </div>
      
      <MQTTCheckboxTree
        v-if="node.children?.length && node.expanded"
        :data="node.children"
        :checked-nodes="checkedNodes"
        @update:checked-nodes="$emit('update:checkedNodes', $event)"
        class="mt-2"
      />
    </li>
  </ul>
</template>