<template>
  <div class="create-object">
    <section class="page-hero">
      <div class="container">
        <h1>Добавить объект</h1>
      </div>
    </section>

    <section class="section">
      <div class="container">
        <form @submit.prevent="handleCreate" class="create-object__form">
          <div class="form-group">
            <label class="form-label">Название</label>
            <input
              v-model="form.title"
              type="text"
              class="form-input"
              required
            />
          </div>

          <div class="form-group">
            <label class="form-label">Краткое описание</label>
            <input
              v-model="form.short_description"
              type="text"
              class="form-input"
            />
          </div>

          <div class="form-group">
            <label class="form-label">Описание</label>
            <textarea
              v-model="form.description"
              class="form-input"
              rows="6"
              required
            ></textarea>
          </div>

          <div class="form-group">
            <label class="form-label">Местоположение</label>
            <input
              v-model="form.location"
              type="text"
              class="form-input"
              placeholder="Город, адрес"
            />
          </div>

          <button type="submit" class="btn btn--primary btn--lg" :disabled="saving">
            {{ saving ? 'Сохранение...' : 'Создать объект' }}
          </button>

          <p v-if="error" class="create-object__error">{{ error }}</p>
        </form>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  title: 'Добавить объект',
  middleware: 'auth',
})

const objectsStore = useObjectsStore()

const form = reactive({
  title: '',
  short_description: '',
  description: '',
  location: '',
})
const saving = ref(false)
const error = ref('')

async function handleCreate() {
  saving.value = true
  error.value = ''
  try {
    const obj = await objectsStore.createObject({ ...form })
    navigateTo(`/objects/${obj.id}`)
  } catch (e: any) {
    error.value = e.message || 'Ошибка создания'
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.page-hero {
  background: var(--color-primary);
  padding: 60px 0;
  text-align: center;
  color: var(--color-text-white);
}

.page-hero h1 {
  color: var(--color-text-white);
}

.create-object__form {
  max-width: 640px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

textarea.form-input {
  resize: vertical;
  min-height: 120px;
}

.create-object__error {
  font-family: var(--font-body);
  font-size: var(--font-size-small);
  color: var(--color-red);
  padding: 8px;
  background: var(--color-bg-error);
  border-radius: var(--radius-sm);
}
</style>
