<template>
  <div v-if="open" class="modal-overlay" @click.self="$emit('close')">
    <div class="modal">
      <div class="modal-header">
        <h3>{{ isEdit ? 'Редактировать карту' : 'Новая карта сети' }}</h3>
        <button class="btn btn-secondary btn-sm" type="button" @click="$emit('close')">✕</button>
      </div>
      <form @submit.prevent="onSubmit">
        <div class="form-group">
          <label>Название *</label>
          <input v-model="form.name" class="form-control" required placeholder="Например: Коллектив А" />
        </div>
        <div class="form-group">
          <label>Тип карты *</label>
          <select v-model="form.mapTypeId" class="form-control" required>
            <option v-for="type in mapTypes" :key="type.id" :value="String(type.id)">
              {{ type.name }}{{ type.isDefault ? ' (по умолчанию)' : '' }}{{ type.conflictologyEnabled ? ' · конфликтология' : '' }}
            </option>
          </select>
        </div>
        <div v-if="selectedMapType?.conflictologyEnabled" class="form-group">
          <label>Предмет / инцидент конфликта (в центре карты) *</label>
          <input
            v-model="form.conflictSubject"
            class="form-control"
            required
            placeholder="Например: Спор о зоне ответственности"
          />
          <p class="text-muted field-hint">
            Секторы и круги задаются в типе карты; здесь — только название конфликта в центре.
          </p>
        </div>
        <div class="form-group">
          <label>Описание</label>
          <textarea
            v-model="form.description"
            class="form-control"
            rows="3"
            placeholder="Цель карты, контекст..."
          />
        </div>
        <div class="modal-footer">
          <button
            v-if="isEdit && deletable"
            type="button"
            class="btn btn-danger"
            @click="$emit('delete')"
          >
            Удалить
          </button>
          <div class="modal-footer-actions">
            <button type="button" class="btn btn-secondary" @click="$emit('close')">Отмена</button>
            <button type="submit" class="btn btn-primary">Сохранить</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { reactive, watch, computed } from 'vue'

const props = defineProps({
  open: { type: Boolean, default: false },
  initial: { type: Object, default: () => ({}) },
  deletable: { type: Boolean, default: false },
  mapTypes: { type: Array, default: () => [] },
  defaultMapTypeId: { type: String, default: '' },
})
const emit = defineEmits(['close', 'submit', 'delete'])

const isEdit = computed(() => Boolean(props.initial?.id))

const form = reactive({
  name: '',
  description: '',
  mapTypeId: '',
  conflictSubject: '',
})

const selectedMapType = computed(() =>
  props.mapTypes.find((t) => String(t.id) === String(form.mapTypeId)) || null
)

watch(
  () => [props.open, props.initial, props.defaultMapTypeId, props.mapTypes],
  () => {
    if (!props.open) return
    form.name = props.initial?.name || ''
    form.description = props.initial?.description || ''
    form.mapTypeId = String(
      props.initial?.mapTypeId || props.defaultMapTypeId || props.mapTypes[0]?.id || ''
    )
    form.conflictSubject = props.initial?.conflictSubject
      || props.initial?.conflict_subject
      || ''
  },
  { immediate: true, deep: true }
)

watch(
  () => [form.mapTypeId, form.name, selectedMapType.value?.conflictologyEnabled],
  () => {
    if (!selectedMapType.value?.conflictologyEnabled) {
      form.conflictSubject = ''
      return
    }
    if (!form.conflictSubject.trim() && form.name.trim()) {
      form.conflictSubject = form.name.trim()
    }
  }
)

function onSubmit() {
  const conflictType = selectedMapType.value?.conflictologyEnabled
  emit('submit', {
    name: form.name.trim(),
    description: form.description.trim(),
    mapTypeId: form.mapTypeId,
    conflictSubject: conflictType ? form.conflictSubject.trim() : '',
  })
}
</script>

<style scoped>
.modal-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-top: 20px;
}
.modal-footer-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}
.field-hint {
  margin: 6px 0 0;
  font-size: 13px;
  line-height: 1.45;
}
</style>
