<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useApi } from '@/composables/useApi'
import { useAuthStore } from '@/stores/auth'
import type { AuthResponse } from '@/types'
import Logo from '@/components/ds/brand/Logo.vue'
import Input from '@/components/ds/forms/Input.vue'
import Button from '@/components/ds/core/Button.vue'
import Alert from '@/components/ds/feedback/Alert.vue'

const router = useRouter()
const api = useApi()
const authStore = useAuthStore()

const email = ref('')
const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const licenseKey = ref('')
const loading = ref(false)
const error = ref('')

const emailValid = computed(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value))
const usernameValid = computed(() => username.value.length >= 3)
const passwordsMatch = computed(() => password.value === confirmPassword.value)

const formValid = computed(() =>
  emailValid.value &&
  usernameValid.value &&
  password.value.length >= 8 &&
  passwordsMatch.value &&
  licenseKey.value.trim().length > 0
)

function validate(): string | null {
  if (!emailValid.value) return 'Please enter a valid email address.'
  if (!usernameValid.value) return 'Username must be at least 3 characters.'
  if (password.value.length < 8) return 'Password must be at least 8 characters.'
  if (!passwordsMatch.value) return 'Passwords do not match.'
  if (!licenseKey.value.trim()) return 'License key is required.'
  return null
}

async function handleRegister() {
  const validationError = validate()
  if (validationError) {
    error.value = validationError
    return
  }

  error.value = ''
  loading.value = true

  try {
    const response = await api.post<AuthResponse>('/auth/register', {
      email: email.value,
      username: username.value,
      password: password.value,
      license_key: licenseKey.value.trim(),
    })

    authStore.setAuth(response)
    if (response.license) {
      authStore.setLicense(response.license)
    }
    router.push('/setup')
  } catch (err: unknown) {
    if (err instanceof Error) {
      error.value = err.message
    } else {
      error.value = 'An unexpected error occurred'
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="auth-shell">
    <div class="auth-card">
      <!-- Branding -->
      <div class="auth-brand">
        <div class="auth-brand__mark">
          <Logo :size="36" tagline="Game Server Operations" />
        </div>
        <p class="auth-brand__sub">Create your account</p>
      </div>

      <!-- Error message -->
      <Alert v-if="error" tone="danger">{{ error }}</Alert>

      <!-- Register form -->
      <form class="auth-form" @submit.prevent="handleRegister">
        <Input
          v-model="email"
          id="email"
          label="Email"
          type="email"
          placeholder="you@example.com"
          autocomplete="email"
          :required="true"
        />

        <Input
          v-model="username"
          id="username"
          label="Username"
          type="text"
          placeholder="At least 3 characters"
          autocomplete="username"
          :required="true"
        />

        <Input
          v-model="password"
          id="password"
          label="Password"
          type="password"
          placeholder="At least 8 characters"
          autocomplete="new-password"
          :required="true"
        />

        <Input
          v-model="confirmPassword"
          id="confirm-password"
          label="Confirm password"
          type="password"
          placeholder="Re-enter your password"
          autocomplete="new-password"
          :required="true"
        />

        <Input
          v-model="licenseKey"
          id="license-key"
          label="License key"
          type="text"
          placeholder="XXXX-XXXX-XXXX-XXXX"
          autocomplete="off"
          :mono="true"
          :required="true"
        />

        <Button
          type="submit"
          :loading="loading"
          :disabled="!formValid"
          :block="true"
          size="md"
        >
          Create account
        </Button>
      </form>

      <!-- Login link -->
      <p class="auth-footer">
        Already have an account?
        <router-link to="/login" class="auth-footer__link">Sign in</router-link>
      </p>
    </div>
  </div>
</template>

<style scoped>
.auth-shell {
  min-height: 100vh;
  background: var(--surface-canvas);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--space-4);
}

.auth-card {
  width: 100%;
  max-width: 400px;
  background: var(--surface-base);
  border-radius: var(--radius-lg);
  box-shadow: var(--ring-default), var(--shadow-lg);
  padding: var(--space-8);
  display: flex;
  flex-direction: column;
  gap: var(--space-5);
}

.auth-brand {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-2);
  padding-bottom: var(--space-1);
}

.auth-brand__mark {
  color: var(--accent);
}

.auth-brand__sub {
  margin: 0;
  font-size: var(--text-sm);
  color: var(--text-tertiary);
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.auth-footer {
  margin: 0;
  text-align: center;
  font-size: var(--text-sm);
  color: var(--text-muted);
}
.auth-footer__link {
  color: var(--accent-text);
  text-decoration: none;
  font-weight: 600;
  margin-left: 4px;
}
.auth-footer__link:hover { color: var(--accent-hover); }
</style>
