<template>
  <div class="signup-container">
    <div class="signup-card">
      <div class="signup-header">
        <div class="logo">
          <img src="/logo.svg" :alt="appName" width="48" height="48" />
        </div>
        <h1 class="title">{{ appName }}</h1>
      </div>

      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        size="medium"
        :show-label="false"
        @keyup.enter="handleSignup"
      >
        <n-form-item path="username">
          <n-input
            v-model:value="formData.username"
            :placeholder="t('Username')"
            :input-props="{ autocomplete: 'username' }"
          >
            <template #prefix>
              <Icon icon="tabler:user" />
            </template>
          </n-input>
        </n-form-item>

        <n-form-item path="password">
          <n-input
            v-model:value="formData.password"
            type="password"
            :placeholder="t('Password')"
            :input-props="{ autocomplete: 'new-password' }"
            show-password-on="click"
          >
            <template #prefix>
              <Icon icon="tabler:lock" />
            </template>
          </n-input>
        </n-form-item>

        <n-form-item path="confirmPassword">
          <n-input
            v-model:value="formData.confirmPassword"
            type="password"
            :placeholder="t('Confirm Password')"
            :input-props="{ autocomplete: 'new-password' }"
            show-password-on="click"
          >
            <template #prefix>
              <Icon icon="tabler:lock" />
            </template>
          </n-input>
        </n-form-item>

        <n-form-item path="email">
          <n-input
            v-model:value="formData.email"
            :placeholder="isEnglish ? t('Email') : t('Email (Optional)')"
            :input-props="{ autocomplete: 'email', type: 'email' }"
          >
            <template #prefix>
              <Icon icon="tabler:mail" />
            </template>
          </n-input>
        </n-form-item>

        <n-form-item v-if="!isEnglish" path="phoneNumber">
          <n-input
            v-model:value="formData.phoneNumber"
            :placeholder="t('Mobile')"
            :input-props="{ autocomplete: 'tel' }"
          >
            <template #prefix>
              <Icon icon="tabler:phone" />
            </template>
          </n-input>
        </n-form-item>

        <n-form-item>
          <n-button
            type="primary"
            size="medium"
            block
            :loading="loading"
            @click="handleSignup"
            class="brand-button"
          >
            {{ t('Sign up') }}
          </n-button>
        </n-form-item>
      </n-form>

      <div class="signup-footer">
        <n-text depth="3">
          {{ t('Already have an account?') }}
          <router-link to="/login" class="login-link">
            {{ t('Login') }}
          </router-link>
        </n-text>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { NForm, NFormItem, NInput, NButton, NText, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { useAuthStore } from '../../shared/stores/auth'
import { signupApi } from '../../shared/api/auth'

const router = useRouter()
const message = useMessage()
const authStore = useAuthStore()

// Language priority: custom language > browser language > default English
const getUserLanguage = () => {
  const customLang = 'zh-CN'
  
  if (customLang) {
    return customLang
  }
  
  const browserLang = navigator.language.toLowerCase()
  if (browserLang.startsWith('zh')) {
    return 'zh-CN'
  }
  
  return 'en-US'
}

const t = (key) => {
  const currentLang = getUserLanguage()
  
  const translations = {
    'zh-CN': {
      'Username': '用户名',
      'Password': '密码',
      'Confirm Password': '确认密码',
      'Email': '邮箱',
      'Email (Optional)': '邮箱(可选)',
      'Mobile': '手机号',
      'Sign up': '注册',
      'Already have an account?': '已有账户?',
      'Login': '登录',
      'Passwords do not match': '密码不匹配',
      'Please enter username': '请输入用户名',
      'Username must be at least 3 characters': '用户名至少需要3个字符',
      'Please enter password': '请输入密码',
      'Password must be at least 6 characters': '密码至少需要6个字符',
      'Please confirm password': '请确认密码',
      'Please enter email': '请输入邮箱',
      'Please enter a valid email address': '请输入有效的邮箱地址',
      'Please enter phone number': '请输入手机号',
      'Please enter a valid phone number': '请输入有效的手机号',
      'Sign up successful': '注册成功',
      'Sign up failed': '注册失败',
      'Sign up successful but auto-login failed, please login manually': '注册成功，但自动登录失败，请手动登录',
      'Sign up failed, please try again': '注册失败，请重试'
    }
  }
  
  if (currentLang === 'zh-CN' && translations['zh-CN']?.[key]) {
    return translations['zh-CN'][key]
  }
  return key
}

const formRef = ref()
const loading = ref(false)

const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phoneNumber: ''
})

const validatePasswordMatch = (_rule: any, value: string) => {
  if (value !== formData.password) {
    return new Error(t('Passwords do not match'))
  }
  return true
}

const isEnglish = computed(() => getUserLanguage() === 'en-US')

const rules = computed(() => {
  const rules: any = {
    username: [
      { required: true, message: t('Please enter username'), trigger: 'blur' },
      { min: 3, message: t('Username must be at least 3 characters'), trigger: 'blur' }
    ],
    password: [
      { required: true, message: t('Please enter password'), trigger: 'blur' },
      { min: 6, message: t('Password must be at least 6 characters'), trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: t('Please confirm password'), trigger: 'blur' },
      { validator: validatePasswordMatch, trigger: 'blur' }
    ]
  }

  // English version: email required, phone number optional
  if (isEnglish.value) {
    rules.email = [
      { required: true, message: t('Please enter email'), trigger: 'blur' },
      {
        validator: (_rule: any, value: string) => {
          // required rule already handles empty values, only validate format here
          if (!value) return true
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
          if (!emailRegex.test(value)) {
            return new Error(t('Please enter a valid email address'))
          }
          return true
        },
        trigger: 'blur'
      }
    ]
    rules.phoneNumber = [
      {
        validator: (_rule: any, value: string) => {
          if (!value) return true
          const phoneRegex = /^1[3-9]\d{9}$/
          if (!phoneRegex.test(value)) {
            return new Error(t('Please enter a valid phone number'))
          }
          return true
        },
        trigger: 'blur'
      }
    ]
  } else {
    // Chinese version: email optional, phone number required
    rules.email = [
      {
        validator: (_rule: any, value: string) => {
          if (!value) return true
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
          if (!emailRegex.test(value)) {
            return new Error(t('Please enter a valid email address'))
          }
          return true
        },
        trigger: 'blur'
      }
    ]
    rules.phoneNumber = [
      { required: true, message: t('Please enter phone number'), trigger: 'blur' },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: t('Please enter a valid phone number'),
        trigger: 'blur'
      }
    ]
  }

  return rules
})

const handleSignup = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    const result = await signupApi({
      username: formData.username,
      password: formData.password,
      email: formData.email || undefined,
      phone_number: isEnglish.value ? (formData.phoneNumber || undefined) : formData.phoneNumber
    })
    
    if (result.success) {
      message.success(t('Sign up successful'))
      if (result.user) {
        authStore.user = result.user
        authStore.isAuthenticated = true
        localStorage.setItem('jingrow_user', JSON.stringify(result.user))
        localStorage.setItem('jingrow_authenticated', 'true')
        router.push('/')
      } else {
        const loginResult = await authStore.login(formData.username, formData.password)
        if (loginResult.success) {
          router.push('/')
        } else {
          message.warning(loginResult.error || t('Sign up successful but auto-login failed, please login manually'))
          router.push('/login')
        }
      }
    } else {
      const errorMsg = result.error || t('Sign up failed')
      message.error(errorMsg)
    }
  } catch (error: any) {
    message.error(error.message || t('Sign up failed, please try again'))
  } finally {
    loading.value = false
  }
}

const appName = ref(localStorage.getItem('appName') || 'Jingrow')

onMounted(async () => {
  // Signup page is accessed before authentication, so boot info won't have app_name.
  // Fetch it via the public API (allow_guest=True), same as old Jinja2 server-side rendering.
  if (!localStorage.getItem('appName')) {
    try {
      const res = await fetch('/api/action/jingrow.sessions.get_app_name', {
        headers: { 'Accept': 'application/json' },
        credentials: 'include'
      })
      if (res.ok) {
        const result = await res.json()
        const name = result.message
        if (name) {
          localStorage.setItem('appName', name)
          appName.value = name
        }
      }
    } catch { /* ignore */ }
  }
  
  await authStore.initAuth()
  
  if (authStore.isLoggedIn) {
    router.push('/')
  }
})
</script>

<style scoped>
.signup-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  padding: 20px;
}

.signup-card {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 40px);
  overflow-y: auto;
}

.signup-header {
  text-align: center;
  margin-bottom: 20px;
}

:deep(.n-form-item) {
  margin-bottom: 6px !important;
}

:deep(.n-form-item:last-child) {
  margin-bottom: 0 !important;
}

:deep(.n-form-item:not(.n-form-item--error) .n-form-item__feedback-wrapper) {
  min-height: 0 !important;
  margin-top: 0 !important;
  padding-top: 0 !important;
}

:deep(.n-form-item--error .n-form-item__feedback-wrapper) {
  margin-top: 4px !important;
  min-height: auto !important;
}

.logo {
  margin-bottom: 12px;
}

.logo img {
  width: 40px;
  height: 40px;
}

.title {
  font-size: 32px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.signup-footer {
  text-align: center;
  margin-top: 16px;
  padding-top: 16px;
}

.login-link {
  color: #1fc76f;
  text-decoration: none;
  font-weight: 500;
  margin-left: 4px;
  transition: color 0.2s;
}

.login-link:hover {
  color: #1fc76f;
  text-decoration: underline;
}

:deep(.brand-button) {
  background: #e6f8f0 !important;
  border: 1px solid #1fc76f !important;
  color: #0d684b !important;
}

:deep(.brand-button .n-button__border),
:deep(.brand-button .n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

:deep(.brand-button:hover) {
  background: #dcfce7 !important;
  border-color: #1fc76f !important;
  color: #166534 !important;
  box-shadow: 0 2px 8px rgba(31, 199, 111, 0.15) !important;
}

:deep(.brand-button:hover .n-button__border),
:deep(.brand-button:hover .n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

:deep(.brand-button:active) {
  background: #1fc76f !important;
  border-color: #1fc76f !important;
  color: white !important;
  box-shadow: 0 1px 4px rgba(31, 199, 111, 0.2) !important;
}

:deep(.brand-button:active .n-button__border),
:deep(.brand-button:active .n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

:deep(.brand-button:focus) {
  background: #e6f8f0 !important;
  border-color: #1fc76f !important;
  color: #0d684b !important;
}

:deep(.brand-button:focus .n-button__border),
:deep(.brand-button:focus .n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}
</style>

