<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { LogIn, Cpu, Shield, UserPlus } from 'lucide-vue-next'
import api from '@/api'

const auth = useAuthStore()
const router = useRouter()

// Tab state
const isLogin = ref(true)

// Login fields
const email = ref('')
const password = ref('')
const error = ref('')
const isLoading = ref(false)

// Register fields
const registerEmail = ref('')
const registerPassword = ref('')
const registerConfirmPassword = ref('')
const registerName = ref('')
const isRegistering = ref(false)
const registerError = ref('')

// Password strength calculation
function getPasswordStrength(pwd: string): { level: 'weak' | 'medium' | 'strong', text: string } {
  if (pwd.length < 8) return { level: 'weak', text: '太短' }
  let score = 0
  if (pwd.length >= 8) score++
  if (pwd.length >= 12) score++
  if (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd)) score++
  if (/\d/.test(pwd)) score++
  if (/[^a-zA-Z0-9]/.test(pwd)) score++
  if (score <= 2) return { level: 'weak', text: '弱' }
  if (score <= 3) return { level: 'medium', text: '中' }
  return { level: 'strong', text: '强' }
}

const passwordStrength = computed(() => getPasswordStrength(registerPassword.value))

async function handleLogin() {
  try {
    error.value = ''
    isLoading.value = true
    await auth.login(email.value, password.value)
    router.push('/chat')
  } catch (e: unknown) {
    error.value = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail || 'Authentication failed'
  } finally {
    isLoading.value = false
  }
}

async function handleRegister() {
  if (registerPassword.value !== registerConfirmPassword.value) {
    registerError.value = '两次密码输入不一致'
    return
  }
  if (registerPassword.value.length < 8) {
    registerError.value = '密码至少需要8个字符'
    return
  }

  try {
    registerError.value = ''
    isRegistering.value = true
    await api.post('/api/auth/register', {
      email: registerEmail.value,
      password: registerPassword.value,
      full_name: registerName.value
    })
    // Register成功后自动登录
    await auth.login(registerEmail.value, registerPassword.value)
    router.push('/chat')
  } catch (e: unknown) {
    registerError.value = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail || '注册失败'
  } finally {
    isRegistering.value = false
  }
}
</script>

<template>
  <div class="login-container scanlines">
    <!-- Background decorations -->
    <div class="bg-grid"></div>
    <div class="bg-glow"></div>
    <div class="corner-tl"></div>
    <div class="corner-tr"></div>
    <div class="corner-bl"></div>
    <div class="corner-br"></div>

    <div class="login-wrapper">
      <!-- Logo -->
      <div class="login-logo">
        <div class="logo-ring r1"></div>
        <div class="logo-ring r2"></div>
        <div class="logo-ring r3"></div>
        <div class="logo-core">
          <Cpu :size="36" />
        </div>
      </div>

      <div class="login-title">JARVIS</div>
      <div class="login-subtitle">PERSONAL AI ASSISTANT</div>

      <!-- Tab Switch -->
      <div class="tab-switch">
        <button
          class="tab-btn"
          :class="{ active: isLogin }"
          @click="isLogin = true"
        >
          登录
        </button>
        <button
          class="tab-btn"
          :class="{ active: !isLogin }"
          @click="isLogin = false"
        >
          注册
        </button>
      </div>

      <!-- Login Form -->
      <form v-if="isLogin" class="login-form" @submit.prevent="handleLogin">
        <div class="field-group">
          <label class="field-label">// OPERATOR ID</label>
          <div class="field-input">
            <input v-model="email" type="text" placeholder="邮箱 / 用户名 / ID" required />
          </div>
        </div>

        <div class="field-group">
          <label class="field-label">// ACCESS CODE</label>
          <div class="field-input">
            <input v-model="password" type="password" placeholder="••••••••" required />
          </div>
        </div>

        <div v-if="error" class="error-msg">
          <Shield :size="12" />
          {{ error }}
        </div>

        <button type="submit" class="login-btn" :disabled="isLoading">
          <div v-if="isLoading" class="btn-loader"></div>
          <LogIn v-else :size="15" />
          <span>{{ isLoading ? 'AUTHENTICATING...' : 'AUTHENTICATE' }}</span>
        </button>
      </form>

      <!-- Register Form -->
      <form v-else class="login-form" @submit.prevent="handleRegister">
        <div class="field-group">
          <label class="field-label">// EMAIL</label>
          <div class="field-input">
            <input v-model="registerEmail" type="email" placeholder="your@email.com" required />
          </div>
        </div>

        <div class="field-group">
          <label class="field-label">// NAME</label>
          <div class="field-input">
            <input v-model="registerName" type="text" placeholder="Your Name" required />
          </div>
        </div>

        <div class="field-group">
          <label class="field-label">// PASSWORD</label>
          <div class="field-input">
            <input v-model="registerPassword" type="password" placeholder="••••••••" required />
          </div>
          <div v-if="registerPassword" class="password-strength">
            <div class="strength-bar">
              <div
                class="strength-fill"
                :class="passwordStrength.level"
                :style="{
                  width: passwordStrength.level === 'weak' ? '33%' : passwordStrength.level === 'medium' ? '66%' : '100%'
                }"
              ></div>
            </div>
            <span class="strength-text" :class="passwordStrength.level">{{ passwordStrength.text }}</span>
          </div>
        </div>

        <div class="field-group">
          <label class="field-label">// CONFIRM PASSWORD</label>
          <div class="field-input">
            <input v-model="registerConfirmPassword" type="password" placeholder="••••••••" required />
          </div>
        </div>

        <div v-if="registerError" class="error-msg">
          <Shield :size="12" />
          {{ registerError }}
        </div>

        <button type="submit" class="login-btn" :disabled="isRegistering">
          <div v-if="isRegistering" class="btn-loader"></div>
          <UserPlus v-else :size="15" />
          <span>{{ isRegistering ? 'REGISTERING...' : 'REGISTER' }}</span>
        </button>
      </form>

      <!-- Footer info -->
      <div class="login-footer">
        <div class="footer-line"></div>
        <div class="footer-text">JARVIS AI SYSTEM v2.0</div>
        <div class="footer-line"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-void);
  position: relative;
  overflow: hidden;
}

/* Background */
.bg-grid {
  position: absolute;
  inset: 0;
  background-image:
    linear-gradient(rgba(0, 245, 212, 0.04) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 245, 212, 0.04) 1px, transparent 1px);
  background-size: 50px 50px;
}

.bg-glow {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  height: 600px;
  background: radial-gradient(ellipse, rgba(0, 245, 212, 0.06) 0%, transparent 70%);
  pointer-events: none;
}

/* Corners */
.corner-tl, .corner-tr, .corner-bl, .corner-br {
  position: absolute;
  width: 40px;
  height: 40px;
}
.corner-tl::before, .corner-tl::after,
.corner-tr::before, .corner-tr::after,
.corner-bl::before, .corner-bl::after,
.corner-br::before, .corner-br::after {
  content: '';
  position: absolute;
  background: var(--accent-cyan);
}
.corner-tl::before, .corner-tr::before,
.corner-bl::before, .corner-bl::after,
.corner-br::before, .corner-br::after { width: 100%; height: 1px; }
.corner-tl::after, .corner-tr::after,
.corner-tr::before, .corner-tr::after,
.corner-bl::after, .corner-br::after { width: 1px; height: 100%; }
.corner-tl { top: 24px; left: 24px; }
.corner-tr { top: 24px; right: 24px; transform: scaleX(-1); }
.corner-bl { bottom: 24px; left: 24px; transform: scaleY(-1); }
.corner-br { bottom: 24px; right: 24px; transform: scale(-1); }

/* Wrapper */
.login-wrapper {
  width: 380px;
  padding: 48px 40px;
  background: rgba(10, 15, 26, 0.9);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-lg);
  backdrop-filter: blur(20px);
  position: relative;
  animation: fade-in-up 0.5s ease;
  box-shadow:
    0 0 40px rgba(0, 245, 212, 0.08),
    0 25px 50px rgba(0, 0, 0, 0.5);
}

/* Logo */
.login-logo {
  position: relative;
  width: 80px;
  height: 80px;
  margin: 0 auto 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--accent-cyan);
}

.logo-ring {
  position: absolute;
  border-radius: 50%;
  border: 1px solid var(--accent-cyan);
  animation: spin linear infinite;
}
.r1 { width: 80px; height: 80px; opacity: 0.2; animation-duration: 12s; border-style: dashed; }
.r2 { width: 60px; height: 60px; opacity: 0.35; animation-duration: 7s; animation-direction: reverse; }
.r3 { width: 44px; height: 44px; opacity: 0.5; animation-duration: 4s; }

.login-core {
  position: relative;
  z-index: 1;
  filter: drop-shadow(0 0 12px var(--accent-cyan));
  animation: pulse-glow 2s ease-in-out infinite;
}

.login-title {
  font-family: var(--font-display);
  font-size: 36px;
  font-weight: 800;
  letter-spacing: 0.25em;
  color: var(--accent-cyan);
  text-align: center;
  text-shadow: var(--glow-cyan);
  margin-bottom: 4px;
}

.login-subtitle {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.35em;
  color: var(--text-dim);
  text-align: center;
  margin-bottom: 24px;
}

/* Tab Switch */
.tab-switch {
  display: flex;
  gap: 4px;
  margin-bottom: 24px;
  padding: 4px;
  background: var(--bg-card);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-dim);
}

.tab-btn {
  flex: 1;
  padding: 8px 16px;
  background: transparent;
  border: none;
  border-radius: var(--radius-sm);
  color: var(--text-dim);
  font-family: var(--font-mono);
  font-size: 11px;
  letter-spacing: 0.1em;
  cursor: pointer;
  transition: all var(--transition-fast);
}

.tab-btn:hover {
  color: var(--text-secondary);
}

.tab-btn.active {
  background: var(--accent-cyan-dim);
  color: var(--accent-cyan);
}

/* Form */
.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.field-group { display: flex; flex-direction: column; gap: 6px; }

.field-label {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.15em;
  color: var(--text-dim);
}

.field-input {
  background: var(--bg-card);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-md);
  padding: 12px 14px;
  transition: all var(--transition-fast);
}

.field-input:focus-within {
  border-color: var(--accent-cyan);
  box-shadow: 0 0 0 1px rgba(0,245,212,0.1), var(--glow-cyan);
}

.field-input input {
  width: 100%;
  font-size: 13px;
  color: var(--text-primary);
  background: transparent;
  border: none;
  outline: none;
}

.field-input input::placeholder {
  color: var(--text-dim);
}

/* Password Strength */
.password-strength {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
}

.strength-bar {
  flex: 1;
  height: 3px;
  background: var(--border-dim);
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all var(--transition-fast);
}

.strength-fill.weak { background: var(--accent-red); }
.strength-fill.medium { background: var(--accent-amber); }
.strength-fill.strong { background: var(--accent-green); }

.strength-text {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.1em;
}

.strength-text.weak { color: var(--accent-red); }
.strength-text.medium { color: var(--accent-amber); }
.strength-text.strong { color: var(--accent-green); }

.error-msg {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: rgba(255, 71, 87, 0.08);
  border: 1px solid rgba(255, 71, 87, 0.2);
  border-radius: var(--radius-md);
  color: var(--accent-red);
  font-size: 11px;
  letter-spacing: 0.05em;
}

.login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 14px;
  background: var(--accent-cyan-dim);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-md);
  color: var(--accent-cyan);
  font-family: var(--font-display);
  font-size: 12px;
  letter-spacing: 0.15em;
  font-weight: 600;
  transition: all var(--transition-mid);
  margin-top: 4px;
}

.login-btn:hover:not(:disabled) {
  background: rgba(0, 245, 212, 0.2);
  box-shadow: var(--glow-cyan);
  transform: translateY(-1px);
}

.btn-loader {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top-color: var(--accent-cyan);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

/* Footer */
.login-footer {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 32px;
}

.footer-line {
  flex: 1;
  height: 1px;
  background: var(--border-dim);
}

.footer-text {
  font-family: var(--font-mono);
  font-size: 8px;
  letter-spacing: 0.15em;
  color: var(--text-muted);
  white-space: nowrap;
}

@keyframes spin { to { transform: rotate(360deg); } }
</style>
