<template>
  <div class="relative">
    <div 
      class="group flex items-center gap-1.5 border border-transparent rounded-[4px] px-1.5 py-1 text-text cursor-pointer mb-px select-none hover:bg-panel-2"
      :class="{ 
        'bg-accent-2/15 border-accent-2/30': store.selectedWidgetId === node.id, 
        'opacity-50': !node.visible,
        'bg-accent/20 border-dashed border-accent': isDragOver 
      }"
      @click.stop="store.selectedWidgetId = node.id"
      :style="{ paddingLeft: `${level * 16 + 8}px` }"
      draggable="true"
      @dragstart="onDragStart($event, node)"
      @dragover.prevent="onDragOver($event)"
      @dragleave="isDragOver = false"
      @drop.stop="onDrop($event, node)"
    >
      <span 
        class="w-4 h-4 flex items-center justify-center text-[8px] text-muted cursor-pointer hover:text-text"
        @click.stop="toggleExpand"
        :style="{ visibility: node.children.length > 0 ? 'visible' : 'hidden' }"
      >
        {{ expanded ? '▼' : '▶' }}
      </span>
      
      <span class="material-symbols-outlined text-[16px] text-accent opacity-80">{{ getIconForType(node.type) }}</span>
      
      <div class="flex-1 min-w-0 flex flex-col overflow-hidden">
        <span class="text-[12px] truncate">{{ displayTitle(node) }}</span>
        <span class="text-[9px] text-muted">{{ TYPE_LABELS[typeKeyFor(node.type)] }} #{{ node.id }}</span>
      </div>

      <div class="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition">
        <button
          class="w-4 h-4 grid place-items-center text-[10px] text-muted hover:text-text"
          :class="canMoveUp ? '' : 'opacity-30 cursor-not-allowed'"
          @click.stop="moveUp"
          :disabled="!canMoveUp"
          title="Nach oben"
        >
          <span class="material-symbols-outlined text-[14px]">arrow_upward</span>
        </button>
        <button
          class="w-4 h-4 grid place-items-center text-[10px] text-muted hover:text-text"
          :class="canMoveDown ? '' : 'opacity-30 cursor-not-allowed'"
          @click.stop="moveDown"
          :disabled="!canMoveDown"
          title="Nach unten"
        >
          <span class="material-symbols-outlined text-[14px]">arrow_downward</span>
        </button>
      </div>
    </div>
    
    <div class="relative" v-if="node.children.length > 0 && expanded">
      <div class="absolute top-0 bottom-0 w-px bg-white/5" :style="{ left: `${level * 16 + 15}px` }"></div>
      <TreeItem 
        v-for="child in node.children" 
        :key="child.id" 
        :node="child" 
        :level="level + 1" 
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useEditorStore } from '../stores/editor';
import { typeKeyFor } from '../utils';
import { TYPE_LABELS, WIDGET_TYPES } from '../constants';

const props = defineProps({
  node: Object,
  level: { type: Number, default: 0 }
});

const store = useEditorStore();
const expanded = ref(true);
const isDragOver = ref(false);
const canMoveUp = computed(() => store.canMoveWidget?.(props.node.id, 'up'));
const canMoveDown = computed(() => store.canMoveWidget?.(props.node.id, 'down'));

function toggleExpand() {
    expanded.value = !expanded.value;
}

function getIconForType(type) {
    switch(type) {
        case WIDGET_TYPES.LABEL: return 'text_fields';
        case WIDGET_TYPES.BUTTON: return 'smart_button';
        case WIDGET_TYPES.LED: return 'light_mode';
        case WIDGET_TYPES.ICON: return 'image';
        case WIDGET_TYPES.TABVIEW: return 'tab';
        case WIDGET_TYPES.TABPAGE: return 'article';
        case WIDGET_TYPES.POWERFLOW: return 'device_hub';
        case WIDGET_TYPES.POWERNODE: return 'radio_button_checked';
        case WIDGET_TYPES.ARC: return 'donut_large';
        case WIDGET_TYPES.BUTTONMATRIX: return 'dialpad';
        default: return 'widgets';
    }
}

function displayTitle(node) {
    if (!node) return '';
    if (node.type === WIDGET_TYPES.POWERNODE && typeof node.text === 'string') {
        const [label] = node.text.split('\n');
        return label || TYPE_LABELS[typeKeyFor(node.type)];
    }
    return node.text || TYPE_LABELS[typeKeyFor(node.type)];
}

function onDragStart(e, node) {
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', node.id.toString());
    store.selectedWidgetId = node.id;
}

function onDragOver(e) {
    // Only allow dropping on containers (Button, TabView, TabPage)
    // Actually, dropping ON a widget means "put inside".
    // Dropping BETWEEN is harder to implement in this simple tree.
    // Let's allow dropping on anything that CAN accept children.
    const type = props.node.type;
    const canAccept = type === WIDGET_TYPES.BUTTON || 
                      type === WIDGET_TYPES.TABVIEW || 
                      type === WIDGET_TYPES.TABPAGE ||
                      type === WIDGET_TYPES.POWERFLOW;
    
    if (canAccept) {
        isDragOver.value = true;
        e.dataTransfer.dropEffect = 'move';
    } else {
        e.dataTransfer.dropEffect = 'none';
    }
}

function onDrop(e, targetNode) {
    isDragOver.value = false;
    const draggedId = parseInt(e.dataTransfer.getData('text/plain'));
    
    if (draggedId === targetNode.id) return; // Drop on self
    
    // Check compatibility
    const type = targetNode.type;
    const canAccept = type === WIDGET_TYPES.BUTTON || 
                      type === WIDGET_TYPES.TABVIEW || 
                      type === WIDGET_TYPES.TABPAGE ||
                      type === WIDGET_TYPES.POWERFLOW;
                      
    if (canAccept) {
        store.reparentWidget(draggedId, targetNode.id);
    }
}

function moveUp() {
    if (!canMoveUp.value) return;
    store.moveWidget(props.node.id, 'up');
}

function moveDown() {
    if (!canMoveDown.value) return;
    store.moveWidget(props.node.id, 'down');
}
</script>
