<template>
  <div class="card glass">
    <div class="row">
      <strong class="op">{{ model.op }}</strong>
      <div class="spacer"></div>
      <button class="icon" title="Subir" @click="$emit('move-up')">▲</button>
      <button class="icon" title="Bajar" @click="$emit('move-down')">▼</button>
      <button class="icon danger" title="Eliminar" @click="$emit('remove')">✕</button>
    </div>
    <div class="fields">
      <template v-for="(val,key) in editable" :key="key">
        <label>{{ key }}<input v-model="editable[key]" /></label>
      </template>
    </div>
    <div class="row end">
      <button class="btn tiny" @click="apply">Aplicar cambios</button>
    </div>
  </div>
</template>

<script setup>
import { reactive, watch } from 'vue';
const props = defineProps({ modelValue: { type: Object, required: true } });
const emit = defineEmits(['update:modelValue','move-up','move-down','remove']);

const model = props.modelValue;
const editable = reactive({});

function refresh() {
  Object.keys(editable).forEach(k => delete editable[k]);
  for (const [k, v] of Object.entries(model)) {
    if (k === 'op') continue;
    editable[k] = typeof v === 'object' ? JSON.stringify(v) : String(v);
  }
}
refresh();

watch(() => props.modelValue, () => refresh(), { deep: true });

function apply() {
  const updated = { op: model.op };
  for (const [k, v] of Object.entries(editable)) {
    try {
      updated[k] = JSON.parse(v);
    } catch {
      // numeric fallback if possible
      const n = Number(v);
      updated[k] = isNaN(n) ? v : n;
    }
  }
  emit('update:modelValue', updated);
}
</script>

<style scoped>
.glass { background: var(--glass); border: 1px solid var(--border); border-radius: 12px; padding: 10px; }
.row { display: flex; align-items: center; gap: 6px; }
.spacer { flex: 1; }
.op { color: var(--accent); }
.icon { background: transparent; border: 1px solid var(--border); color: var(--fg); border-radius: 8px; padding: 2px 6px; cursor: pointer; }
.icon.danger { border-color: #a44; color: #e99; }
.fields { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
label { color: var(--muted); display: inline-flex; gap: 6px; align-items: center; }
input { color: var(--fg); background: rgba(255,255,255,0.04); border: 1px solid var(--border); border-radius: 8px; padding: 4px 6px; }
.end { justify-content: flex-end; margin-top: 8px; }
.btn.tiny { font-size: 12px; padding: 6px 8px; }
</style>

