<template>
  <section class="auth-layout">
    <div class="panel">
      <p class="section-tag">运营平台</p>
      <h1>登录或注册</h1>
      <p class="muted">登录后进入 IM、Push、App 管理三大模块。</p>

      <div class="tab-row">
        <button :class="mode === 'login' ? 'primary' : 'secondary'" @click="mode = 'login'">登录</button>
        <button :class="mode === 'register' ? 'primary' : 'secondary'" @click="mode = 'register'">注册</button>
      </div>

      <form class="form-grid" @submit.prevent="submit">
        <label v-if="mode === 'register'">
          企业名称
          <input v-model="form.accountName" placeholder="星云运营中心" required />
        </label>
        <label v-if="mode === 'register'">
          联系人
          <input v-model="form.contactName" placeholder="林青" required />
        </label>
        <label>
          邮箱
          <input v-model="form.email" type="email" placeholder="ops@nebula.example" required />
        </label>
        <label v-if="mode === 'register'">
          手机号
          <input v-model="form.phone" placeholder="13800138000" required />
        </label>
        <label class="full">
          密码
          <input v-model="form.password" type="password" placeholder="请输入密码" required />
        </label>
        <button class="primary full">{{ mode === 'login' ? '登录并进入工作台' : '注册并登录' }}</button>
      </form>

      <p v-if="message" class="success-text">{{ message }}</p>
      <p class="muted">内置测试账号：`ops@nebula.example / 123456`</p>
    </div>
  </section>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../api/client'

const router = useRouter()
const mode = ref<'login' | 'register'>('login')
const message = ref('')
const form = reactive({
  accountName: '',
  contactName: '',
  email: '',
  phone: '',
  password: '',
})

async function submit() {
  message.value = ''
  try {
    if (mode.value === 'register') {
      await api.registerAccount(form)
    }
    const result = await api.login({ email: form.email, password: form.password })
    localStorage.setItem('ops-session', JSON.stringify(result))
    await router.push('/console/apps')
  } catch (error) {
    message.value = error instanceof Error ? error.message : '操作失败'
  }
}
</script>
