<template>
  <form @submit.prevent="submit" class="proposer-form" novalidate>
    <div class="field-group" :class="{ 'field-error': errors.nom }">
      <label for="res-nom">Nom du réseau / collectif / ressource <span class="required">*</span></label>
      <input id="res-nom" v-model="form.nom" type="text" placeholder="Ex : Collectif des Arpenteurs, Archi'Résilience..." @blur="validateField('nom')" />
      <span v-if="errors.nom" class="error-msg" role="alert">{{ errors.nom }}</span>
    </div>

    <div class="field-group" :class="{ 'field-error': errors.type_principal }">
      <fieldset>
        <legend>Type <span class="label-hint">(optionnel)</span></legend>
        <div class="radio-group">
          <label v-for="t in TYPES" :key="t" class="radio-label" :class="{ active: form.type_principal === t }">
            <input type="radio" :value="t" v-model="form.type_principal" name="res-type" />{{ LABELS[t] }}
          </label>
        </div>
      </fieldset>
    </div>

    <div class="field-group" :class="{ 'field-error': errors.url }">
      <label for="res-url">Site web <span class="label-hint">(optionnel)</span></label>
      <input id="res-url" v-model="form.url" type="url" placeholder="https://..." @blur="validateField('url')" />
      <span v-if="errors.url" class="error-msg" role="alert">{{ errors.url }}</span>
    </div>

    <div class="field-group" :class="{ 'field-error': errors.description_user }">
      <label for="res-desc">Description courte <span class="required">*</span> <span class="label-hint">(50 à 500 caractères)</span></label>
      <textarea id="res-desc" v-model="form.description_user" rows="4" placeholder="Présente ce réseau/collectif : son objet, son échelle, ce qui le distingue..." @blur="validateField('description_user')" />
      <div class="field-meta">
        <span v-if="errors.description_user" class="error-msg" role="alert">{{ errors.description_user }}</span>
        <span v-else class="char-count" :class="{ 'char-warn': form.description_user.length > 450 }">{{ form.description_user.length }}/500</span>
      </div>
    </div>

    <div class="field-group">
      <label for="res-ville">Ville principale <span class="label-hint">(optionnel)</span></label>
      <input id="res-ville" v-model="form.localisation_ville" type="text" placeholder="Ex : Paris, Lyon..." />
    </div>

    <div class="field-group">
      <label for="res-projet-lien">Lien vers un projet / réalisation <span class="label-hint">(optionnel)</span></label>
      <input id="res-projet-lien" v-model="form.projet_lien" type="url" placeholder="https://..." />
    </div>

    <div class="field-group">
      <label for="res-projet-adresse">Adresse du projet <span class="label-hint">(optionnel)</span></label>
      <input id="res-projet-adresse" v-model="form.projet_adresse" type="text" placeholder="Ex : 12 rue des Lilas, 75000 Paris" />
    </div>

    <div class="field-group" :class="{ 'field-error': errors.submitted_by_email }">
      <label for="res-email">Ton email <span class="label-hint">(optionnel — pour le suivi)</span></label>
      <input id="res-email" v-model="form.submitted_by_email" type="email" placeholder="ton@email.fr" autocomplete="email" @blur="validateField('submitted_by_email')" />
      <span v-if="errors.submitted_by_email" class="error-msg" role="alert">{{ errors.submitted_by_email }}</span>
    </div>

    <div v-if="serverError" class="server-error" role="alert"><strong>Erreur :</strong> {{ serverError }}</div>

    <div class="form-actions">
      <button type="submit" class="btn-primary" :disabled="submitting">{{ submitting ? 'Envoi en cours...' : 'Proposer →' }}</button>
    </div>
    <p class="form-note">Ta proposition sera examinée par l'équipe avant publication.</p>
  </form>
</template>

<script setup lang="ts">
import { z } from 'zod'

const TYPES = ['agence', 'collectif', 'reseau', 'asso', 'ressource'] as const
const LABELS: Record<string, string> = { agence: 'Agence', collectif: 'Collectif', reseau: 'Réseau', asso: 'Association', ressource: 'Ressource' }

const Schema = z.object({
  nom: z.string().min(3, 'Minimum 3 caractères').max(150, 'Maximum 150 caractères').trim(),
  type_principal: z.string().optional(),
  url: z.string().url('URL invalide').optional().or(z.literal('')),
  description_user: z.string().min(50, 'Minimum 50 caractères').max(500, 'Maximum 500 caractères').trim(),
  localisation_ville: z.string().max(100).optional(),
  projet_lien: z.string().url('URL invalide').optional().or(z.literal('')),
  projet_adresse: z.string().max(200).optional(),
  submitted_by_email: z.string().email('Email invalide').optional().or(z.literal('')),
})

const emit = defineEmits<{ success: [] }>()

const form = reactive({
  nom: '', type_principal: '', url: '', description_user: '',
  localisation_ville: '', projet_lien: '', projet_adresse: '', submitted_by_email: '',
})
const errors = reactive<Record<string, string>>({})
const submitting = ref(false)
const serverError = ref('')

function validateField(field: string) {
  const partial = Schema.partial()
  const result = partial.safeParse({ [field]: (form as any)[field] })
  if (!result.success) {
    const fieldErrors = result.error.flatten().fieldErrors
    errors[field] = fieldErrors[field]?.[0] ?? ''
  } else {
    delete errors[field]
  }
}

function validateAll(): boolean {
  const result = Schema.safeParse(form)
  if (!result.success) {
    const flat = result.error.flatten().fieldErrors
    Object.assign(errors, Object.fromEntries(Object.entries(flat).map(([k, v]) => [k, v?.[0] ?? ''])))
    return false
  }
  Object.keys(errors).forEach(k => delete errors[k])
  return true
}

async function submit() {
  serverError.value = ''
  if (!validateAll()) {
    await nextTick()
    const firstError = document.querySelector('.field-error')
    firstError?.scrollIntoView({ behavior: 'smooth', block: 'center' })
    return
  }
  submitting.value = true
  try {
    await $fetch('/api/submit', {
      method: 'POST',
      body: {
        submission_type: 'reseau',
        nom: form.nom,
        type_principal: form.type_principal || undefined,
        url: form.url || undefined,
        description_user: form.description_user,
        localisation_ville: form.localisation_ville || undefined,
        projet_lien: form.projet_lien || undefined,
        projet_adresse: form.projet_adresse || undefined,
        submitted_by_email: form.submitted_by_email || undefined,
      },
    })
    emit('success')
  } catch (e: any) {
    const status = e?.status ?? e?.statusCode
    if (status === 429) {
      serverError.value = 'Tu as déjà soumis 3 fiches aujourd\'hui. Réessaie demain.'
    } else if (status === 422 && e?.data) {
      const fieldErrors = e.data
      Object.entries(fieldErrors).forEach(([k, v]) => { errors[k] = Array.isArray(v) ? v[0] : String(v) })
      serverError.value = 'Certains champs sont invalides — vérifie les erreurs ci-dessus.'
    } else {
      serverError.value = 'Une erreur s\'est produite. Réessaie dans quelques instants.'
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
@import './form-styles.css';
</style>
