<!-- front-end/app/pages/register.vue -->
<script setup lang="ts">
definePageMeta({ layout: 'auth' })

const { public: { apiBase } } = useRuntimeConfig()
const token = useCookie<string | null>('auth_token', { maxAge: 60 * 60 * 8 })
const refreshToken = useCookie<string | null>('refresh_token', { maxAge: 60 * 60 * 24 * 7 })

const documentType = ref<'pf' | 'pj'>('pj')
const form = reactive({
  legalName: '',
  document: '',
  adminEmail: '',
  adminPassword: '',
})

const isPJ = computed(() => documentType.value === 'pj')
const documentLabel = computed(() => isPJ.value ? 'CNPJ' : 'CPF')
const documentPlaceholder = computed(() => isPJ.value ? '00.000.000/0001-00' : '000.000.000-00')

function toSlug(val: string) {
  return val.toLowerCase()
    .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9\s-]/g, '')
    .trim()
    .replace(/\s+/g, '-')
    .slice(0, 50)
}

const error = ref('')
const loading = ref(false)

async function handleSubmit() {
  error.value = ''
  loading.value = true
  try {
    const res = await $fetch<{ access_token: string; refresh_token: string }>(`${apiBase}/auth/register`, {
      method: 'POST',
      body: {
        company_name: form.legalName,
        legal_name: form.legalName,
        document_type: documentType.value,
        document: form.document,
        slug: toSlug(form.legalName),
        admin_name: form.legalName,
        admin_email: form.adminEmail,
        admin_password: form.adminPassword,
      },
    })
    token.value = res.access_token
    refreshToken.value = res.refresh_token
    navigateTo('/')
  } catch (err: any) {
    error.value = err?.data?.error || 'Erro ao criar conta. Tente novamente.'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="register-card">
    <div class="register-header">
      <h1>Criar conta</h1>
      <p>Preencha os dados para começar a usar o Licitatche</p>
    </div>

    <form @submit.prevent="handleSubmit">
      <!-- Tipo de pessoa -->
      <div class="type-toggle">
        <button
          type="button"
          :class="['type-btn', documentType === 'pj' && 'active']"
          @click="documentType = 'pj'"
        >
          Pessoa Jurídica
        </button>
        <button
          type="button"
          :class="['type-btn', documentType === 'pf' && 'active']"
          @click="documentType = 'pf'"
        >
          Pessoa Física
        </button>
      </div>

      <UFormField :label="isPJ ? 'Razão Social' : 'Nome Completo'" class="field">
        <UInput v-model="form.legalName" :placeholder="isPJ ? 'Razão Social completa' : 'Nome completo'" class="w-full" required />
      </UFormField>

      <UFormField :label="documentLabel" class="field">
        <UInput v-model="form.document" :placeholder="documentPlaceholder" class="w-full" required />
      </UFormField>

      <UFormField label="E-mail" class="field">
        <UInput v-model="form.adminEmail" type="email" placeholder="voce@empresa.com.br" class="w-full" required />
      </UFormField>

      <UFormField label="Senha" class="field">
        <UInput v-model="form.adminPassword" type="password" placeholder="Mínimo 8 caracteres" class="w-full" required />
      </UFormField>

      <p v-if="error" class="error-msg">{{ error }}</p>

      <UButton type="submit" block size="md" :loading="loading" class="btn-register">
        Criar conta
      </UButton>

      <p class="login-link">
        Já tem conta? <NuxtLink to="/login">Fazer login</NuxtLink>
      </p>
    </form>
  </div>
</template>

<style scoped>
.register-card {
  background: white;
  border-radius: 20px;
  padding: 40px;
  width: 100%;
  max-width: 460px;
  box-shadow: 0 25px 60px rgba(0, 0, 0, 0.25);
}
.register-header { margin-bottom: 24px; }
.register-header h1 { font-size: 22px; font-weight: 700; color: #0f172a; letter-spacing: -0.5px; }
.register-header p { font-size: 13px; color: #64748b; margin-top: 4px; }

.type-toggle { display: flex; gap: 8px; margin-bottom: 20px; }
.type-btn {
  flex: 1; padding: 8px; border-radius: 8px; border: 1.5px solid #e2e8f0;
  font-size: 13px; font-weight: 500; color: #64748b; cursor: pointer; background: white;
  transition: all 0.15s;
}
.type-btn.active {
  border-color: #667eea; color: #667eea; background: #f0f3ff;
}

.section-label {
  font-size: 11px; font-weight: 700; color: #94a3b8; letter-spacing: 0.8px;
  text-transform: uppercase; margin: 16px 0 12px;
}
.field { margin-bottom: 14px; }
.slug-hint { font-size: 11px; color: #94a3b8; margin-top: 4px; display: block; }
.error-msg { color: #dc2626; font-size: 13px; margin-bottom: 12px; }
.btn-register {
  background: linear-gradient(135deg, #667eea, #764ba2) !important;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
  margin-top: 4px;
}
.login-link { text-align: center; font-size: 13px; color: #64748b; margin-top: 16px; }
.login-link a { color: #667eea; font-weight: 600; text-decoration: none; }
</style>
