<!-- 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({
  companyName: '',
  legalName: '',
  document: '',
  slug: '',
  adminName: '',
  adminEmail: '',
  adminPassword: '',
})

const documentLabel = computed(() => documentType.value === 'pj' ? 'CNPJ' : 'CPF')
const documentPlaceholder = computed(() => documentType.value === 'pj' ? '00.000.000/0001-00' : '000.000.000-00')
const nameLabel = computed(() => documentType.value === 'pj' ? 'Razão Social' : 'Nome Completo')

// Auto-gera slug a partir do nome fantasia
watch(() => form.companyName, (val) => {
  form.slug = 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.companyName,
        legal_name: form.legalName,
        document_type: documentType.value,
        document: form.document,
        slug: form.slug,
        admin_name: form.adminName,
        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>

      <div class="section-label">Dados da Empresa</div>

      <UFormField label="Nome Fantasia / Apelido" class="field">
        <UInput v-model="form.companyName" placeholder="Ex: Tech Gov" required />
      </UFormField>

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

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

      <UFormField label="Identificador único (slug)" class="field">
        <UInput v-model="form.slug" placeholder="minha-empresa" required />
        <template #hint>
          <span class="slug-hint">Usado para fazer login. Ex: <strong>{{ form.slug || 'minha-empresa' }}</strong></span>
        </template>
      </UFormField>

      <div class="section-label">Dados de Acesso</div>

      <UFormField label="Seu nome" class="field">
        <UInput v-model="form.adminName" placeholder="Nome do responsável" required />
      </UFormField>

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

      <UFormField label="Senha" class="field">
        <UInput v-model="form.adminPassword" type="password" placeholder="Mínimo 8 caracteres" 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>
