<template>
  <form @submit.prevent="submit" class="proposer-form" novalidate>
    <div class="field-group" :class="{ 'field-error': errors.nom }">
      <label for="job-nom">Nom de la plateforme / job board <span class="required">*</span></label>
      <input id="job-nom" v-model="form.nom" type="text" placeholder="Ex : Houzz, Architoo, BOAMP..." @blur="validateField('nom')" />
      <span v-if="errors.nom" class="error-msg" role="alert">{{ errors.nom }}</span>
    </div>

    <div class="field-group">
      <label for="job-type">Type de plateforme <span class="label-hint">(optionnel)</span></label>
      <div class="radio-group">
        <label v-for="t in TYPES" :key="t" class="radio-label" :class="{ active: form.type_plateforme === t }">
          <input type="radio" :value="t" v-model="form.type_plateforme" name="job-type" />{{ LABELS[t] }}
        </label>
      </div>
    </div>

    <div class="field-group" :class="{ 'field-error': errors.url }">
      <label for="job-url">Site web <span class="required">*</span></label>
      <input id="job-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="job-desc">Description courte <span class="required">*</span> <span class="label-hint">(50 à 500 caractères)</span></label>
      <textarea id="job-desc" v-model="form.description_user" rows="4" placeholder="Décris la plateforme : qui la gère, quel type de missions, quel modèle économique..." @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" :class="{ 'field-error': errors.submitted_by_email }">
      <label for="job-email">Ton email <span class="label-hint">(optionnel — pour le suivi)</span></label>
      <input id="job-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 = ['mise-en-relation', 'appel-offre-public', 'communaute-pro'] as const
const LABELS: Record<string, string> = { 'mise-en-relation': 'Mise en relation (B2C)', 'appel-offre-public': 'Appels d\'offres publics', 'communaute-pro': 'Communauté pro' }

const Schema = z.object({
  nom: z.string().min(3, 'Minimum 3 caractères').max(150, 'Maximum 150 caractères').trim(),
  url: z.string().url('URL invalide (commencer par https://)'),
  description_user: z.string().min(50, 'Minimum 50 caractères').max(500, 'Maximum 500 caractères').trim(),
  type_plateforme: z.string().optional(),
  submitted_by_email: z.string().email('Email invalide').optional().or(z.literal('')),
})

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

const form = reactive({
  nom: '', url: '', description_user: '', type_plateforme: '', 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: 'job',
        nom: form.nom,
        url: form.url,
        description_user: form.description_user,
        type_plateforme: form.type_plateforme || 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>
