<template>
  <div
    class="arch-node rounded-xl select-none relative overflow-visible"
    :class="[selected ? 'ring-2 ring-monokai-cyan/70 ring-offset-1 ring-offset-monokai-bg' : '']"
    :style="nodeStyle"
    @dblclick.stop="startEdit"
  >
    <!-- Redimensionnement -->
    <NodeResizer
      :min-width="40"
      :min-height="28"
      :is-visible="selected && !data.locked"
      :color="data.borderColor || '#B5B5B5'"
    />

    <!-- Contenu du noeud -->
    <div class="px-3 py-2 flex items-center gap-1.5 h-full min-w-0">
      <!-- Icône -->
      <span v-if="data.icon" class="flex-shrink-0 inline-flex items-center">
        <img
          v-if="isImageIcon"
          :src="iconUrl"
          :style="{ width: `${data.iconSize || 16}px`, height: `${data.iconSize || 16}px` }"
          class="object-contain"
        />
        <span v-else :style="{ fontSize: `${data.iconSize || 16}px` }">{{ data.icon }}</span>
      </span>

      <!-- Label (éditable ou lecture) -->
      <input
        v-if="isEditing"
        ref="editInput"
        v-model="editValue"
        class="bg-transparent border-b border-monokai-cyan text-monokai-text text-sm outline-none min-w-0 flex-1"
        @blur="commitEdit"
        @keydown.enter="commitEdit"
        @keydown.escape="cancelEdit"
      />
      <span
        v-else
        class="truncate flex-1 min-w-0"
        :style="{ color: data.fontColor || '#E6E6E6', fontSize: `${data.fontSize || 14}px` }"
      >
        {{ data.label }}
      </span>
    </div>

    <!-- Indicateur online -->
    <div
      v-if="data.online"
      class="absolute left-2 bottom-1 flex items-center gap-1 text-[9px] text-monokai-green"
    >
      <span class="w-2 h-2 rounded-full bg-monokai-green inline-block"></span>
      online
    </div>

    <!-- Indicateur verrouillé -->
    <div v-if="data.locked" class="absolute right-1 top-1 text-monokai-comment text-[10px]">
      <span class="mdi mdi-lock"></span>
    </div>

    <!-- Handles dynamiques (interfaces réseau) -->
    <Handle
      v-for="handle in handles"
      :key="handle.id"
      :id="handle.id"
      type="source"
      :position="handle.position"
      :style="handle.style"
      class="!rounded-full !border"
    />
  </div>
</template>

<script setup>
import { computed, ref, nextTick } from 'vue'
import { Handle, Position } from '@vue-flow/core'
import { NodeResizer } from '@vue-flow/node-resizer'
import { applyFillOpacity } from '@/composables/useArchitectureMigration'

const props = defineProps({
  id: String,
  data: { type: Object, required: true },
  selected: Boolean,
})

const emit = defineEmits(['update:data'])

// --- Édition inline du label ---
const isEditing = ref(false)
const editValue = ref('')
const editInput = ref(null)

function startEdit() {
  if (props.data.locked) return
  isEditing.value = true
  editValue.value = props.data.label || ''
  nextTick(() => editInput.value?.focus())
}

function commitEdit() {
  if (!isEditing.value) return
  isEditing.value = false
  if (editValue.value !== props.data.label) {
    // Mise à jour via le store (le parent capture l'événement)
    props.data.label = editValue.value
  }
}

function cancelEdit() {
  isEditing.value = false
}

// --- Icône ---
const isImageIcon = computed(() => {
  const icon = props.data.icon || ''
  return icon.includes('.') && (icon.endsWith('.svg') || icon.endsWith('.png') || icon.endsWith('.jpg'))
})

const iconUrl = computed(() => `/icons/${props.data.icon}`)

// --- Style du noeud ---
const nodeStyle = computed(() => ({
  borderColor: props.data.borderColor || '#B5B5B5',
  borderWidth: `${props.data.borderWidth || 2}px`,
  borderStyle: props.data.borderStyle || 'solid',
  backgroundColor: applyFillOpacity(props.data.fillColor, props.data.opacity),
  color: props.data.color || '#E6E6E6',
}))

// --- Handles dynamiques (connecteurs / interfaces réseau) ---
const handles = computed(() => {
  const result = []
  const d = props.data
  const size = d.connectorSize || 12
  const bgColor = d.connectorColor || '#B5B5B5'
  const strokeColor = d.connectorStrokeColor || '#1E1F1C'

  const baseStyle = {
    width: `${size}px`,
    height: `${size}px`,
    backgroundColor: bgColor,
    borderColor: strokeColor,
  }

  const addSide = (count, side, position) => {
    for (let i = 0; i < (count || 0); i++) {
      const fraction = ((i + 1) / ((count || 0) + 1)) * 100
      const posStyle = { ...baseStyle }

      if (side === 'top' || side === 'bottom') {
        posStyle.left = `${fraction}%`
        posStyle.transform = 'translateX(-50%)'
      } else {
        posStyle.top = `${fraction}%`
        posStyle.transform = 'translateY(-50%)'
      }

      result.push({
        id: `${side}-${i}`,
        position,
        style: posStyle,
      })
    }
  }

  addSide(d.connectTop, 'top', Position.Top)
  addSide(d.connectBottom, 'bottom', Position.Bottom)
  addSide(d.connectLeft, 'left', Position.Left)
  addSide(d.connectRight, 'right', Position.Right)

  return result
})
</script>

<style scoped>
.arch-node {
  font-family: inherit;
}
</style>
