<template>
  <view class="register-page">
    <!-- 顶部装饰 -->
    <view class="header-decoration">
      <view class="decoration-circle circle-1"></view>
      <view class="decoration-circle circle-2"></view>
    </view>

    <!-- 品牌区域 -->
    <view class="brand-section">
      <view class="brand-logo">
        <u-icon name="home-fill" size="80" color="#3B82F6"></u-icon>
      </view>
      <text class="brand-name">品住会商家中心</text>
      <text class="brand-slogan">{{ modeConfig.slogan }}</text>
    </view>

    <!-- 表单容器 -->
    <view class="form-container">
      <!-- 模式切换标签 -->
      <view class="mode-tabs">
        <view
          class="tab-item"
          :class="{ active: mode === 'register' }"
          @tap="switchMode('register')"
        >
          <text class="tab-text">注册</text>
          <view v-if="mode === 'register'" class="tab-indicator"></view>
        </view>
        <view
          class="tab-item"
          :class="{ active: mode === 'login' }"
          @tap="switchMode('login')"
        >
          <text class="tab-text">登录</text>
          <view v-if="mode === 'login'" class="tab-indicator"></view>
        </view>
      </view>

      <!-- 注册表单 -->
      <view v-if="mode === 'register'" class="form-wrapper">
        <view class="input-group">
          <view class="input-item">
            <view class="input-label">
              <u-icon name="phone" size="32" color="#6B7280"></u-icon>
              <text class="label-text">手机号</text>
            </view>
            <input
              class="input-field"
              type="number"
              v-model="registerForm.phone"
              placeholder="请输入11位手机号"
              maxlength="11"
              placeholder-class="input-placeholder"
            />
          </view>

          <view class="input-item">
            <view class="input-label">
              <u-icon name="lock" size="32" color="#6B7280"></u-icon>
              <text class="label-text">登录密码</text>
            </view>
            <input
              class="input-field"
              :type="showPassword ? 'text' : 'password'"
              v-model="registerForm.password"
              placeholder="6-20位字母、数字或符号"
              maxlength="20"
              placeholder-class="input-placeholder"
            />
            <view class="input-suffix" @tap="togglePassword">
              <u-icon :name="showPassword ? 'eye-fill' : 'eye-off'" size="36" color="#9CA3AF"></u-icon>
            </view>
          </view>

          <view class="input-item">
            <view class="input-label">
              <u-icon name="chat" size="32" color="#6B7280"></u-icon>
              <text class="label-text">短信验证码</text>
            </view>
            <input
              class="input-field code-field"
              type="number"
              v-model="registerForm.code"
              placeholder="请输入6位验证码"
              maxlength="6"
              placeholder-class="input-placeholder"
            />
            <view class="input-suffix">
              <view
                class="code-button"
                :class="{ disabled: registerCountdown > 0 || !canSendRegisterCode }"
                @tap="sendRegisterCode"
              >
                {{ registerCountdown > 0 ? `${registerCountdown}秒` : '获取验证码' }}
              </view>
            </view>
          </view>

          <view class="input-item">
            <view class="input-label">
              <u-icon name="account" size="32" color="#6B7280"></u-icon>
              <text class="label-text">联系人姓名</text>
            </view>
            <input
              class="input-field"
              type="text"
              v-model="registerForm.contactName"
              placeholder="请输入真实姓名"
              maxlength="50"
              placeholder-class="input-placeholder"
            />
          </view>

          <view class="input-item optional-item">
            <view class="input-label">
              <u-icon name="email" size="32" color="#9CA3AF"></u-icon>
              <text class="label-text optional">邮箱（选填）</text>
            </view>
            <input
              class="input-field"
              type="text"
              v-model="registerForm.email"
              placeholder="用于接收重要通知"
              placeholder-class="input-placeholder"
            />
          </view>
        </view>

        <!-- 协议勾选 -->
        <view class="agreement-section">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-wrapper">
              <checkbox :checked="agreed" color="#3B82F6" class="agreement-checkbox" />
              <text class="agreement-text">
                我已阅读并同意
                <text class="link-text" @tap.stop="showAgreement('merchant')">《商家服务协议》</text>
                及
                <text class="link-text" @tap.stop="showAgreement('privacy')">《隐私政策》</text>
              </text>
            </label>
          </checkbox-group>
        </view>

        <!-- 提交按钮 -->
        <button
          class="submit-button"
          :class="{ disabled: !canSubmitRegister }"
          :disabled="!canSubmitRegister"
          @tap="handleRegister"
        >
          <text class="button-text">{{ loading ? '注册中...' : '立即注册' }}</text>
        </button>
      </view>

      <!-- 登录表单 -->
      <view v-else class="form-wrapper">
        <view class="input-group">
          <view class="input-item">
            <view class="input-label">
              <u-icon name="phone" size="32" color="#6B7280"></u-icon>
              <text class="label-text">手机号</text>
            </view>
            <input
              class="input-field"
              type="number"
              v-model="loginForm.phone"
              placeholder="请输入11位手机号"
              maxlength="11"
              placeholder-class="input-placeholder"
            />
          </view>

          <view class="input-item">
            <view class="input-label">
              <u-icon name="chat" size="32" color="#6B7280"></u-icon>
              <text class="label-text">短信验证码</text>
            </view>
            <input
              class="input-field code-field"
              type="number"
              v-model="loginForm.code"
              placeholder="请输入6位验证码"
              maxlength="6"
              placeholder-class="input-placeholder"
            />
            <view class="input-suffix">
              <view
                class="code-button"
                :class="{ disabled: loginCountdown > 0 || !canSendLoginCode }"
                @tap="sendLoginCode"
              >
                {{ loginCountdown > 0 ? `${loginCountdown}秒` : '获取验证码' }}
              </view>
            </view>
          </view>
        </view>

        <!-- 协议勾选 -->
        <view class="agreement-section">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-wrapper">
              <checkbox :checked="agreed" color="#3B82F6" class="agreement-checkbox" />
              <text class="agreement-text">
                我已阅读并同意
                <text class="link-text" @tap.stop="showAgreement('merchant')">《商家服务协议》</text>
                及
                <text class="link-text" @tap.stop="showAgreement('privacy')">《隐私政策》</text>
              </text>
            </label>
          </checkbox-group>
        </view>

        <!-- 提交按钮 -->
        <button
          class="submit-button"
          :class="{ disabled: !canSubmitLogin }"
          :disabled="!canSubmitLogin"
          @tap="handleLogin"
        >
          <text class="button-text">{{ loading ? '登录中...' : '立即登录' }}</text>
        </button>
      </view>

      <!-- 底部提示 -->
      <view class="footer-tips">
        <view class="tip-item">
          <u-icon name="checkmark-circle" size="32" color="#10B981"></u-icon>
          <text class="tip-text">免费入驻，零门槛开店</text>
        </view>
        <view class="tip-item">
          <u-icon name="checkmark-circle" size="32" color="#10B981"></u-icon>
          <text class="tip-text">专业工具，高效管理</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { sellerRegister, sellerLogin, sellerSendCode } from '@/api/seller/auth';
import { useSellerStore } from '@/store/seller';

const sellerStore = useSellerStore();

const mode = ref<'register' | 'login'>('register');
const loading = ref(false);
const agreed = ref(false);
const showPassword = ref(false);

const registerCountdown = ref(0);
const loginCountdown = ref(0);

const registerForm = ref({
  phone: '',
  code: '',
  contactName: '',
  email: '',
  password: '',
});

const loginForm = ref({
  phone: '',
  code: '',
});

const modeConfig = computed(() => {
  return mode.value === 'register'
    ? {
        slogan: '开通店铺，发布房源，开启您的生意之旅',
      }
    : {
        slogan: '登录商家中心，管理您的店铺与订单',
      };
});

const canSendRegisterCode = computed(() => {
  return validatePhone(registerForm.value.phone);
});

const canSendLoginCode = computed(() => {
  return validatePhone(loginForm.value.phone);
});

const canSubmitRegister = computed(() => {
  const { phone, password, code, contactName } = registerForm.value;
  return (
    agreed.value &&
    !loading.value &&
    validatePhone(phone) &&
    password.length >= 6 &&
    password.length <= 20 &&
    code.length === 6 &&
    contactName.trim().length >= 2
  );
});

const canSubmitLogin = computed(() => {
  const { phone, code } = loginForm.value;
  return (
    agreed.value &&
    !loading.value &&
    validatePhone(phone) &&
    code.length === 6
  );
});

onMounted(() => {
  const pages = getCurrentPages();
  const page = pages[pages.length - 1] as any;
  const param = page.options?.mode || page.$page?.options?.mode;
  if (param === 'login') {
    mode.value = 'login';
  }
});

function validatePhone(phone: string): boolean {
  return /^1[3-9]\d{9}$/.test(phone);
}

function validateEmail(email: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function switchMode(newMode: 'register' | 'login') {
  if (mode.value === newMode) return;
  mode.value = newMode;
  agreed.value = false;
}

function togglePassword() {
  showPassword.value = !showPassword.value;
}

function startCountdown(type: 'register' | 'login') {
  const countdown = type === 'register' ? registerCountdown : loginCountdown;
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
}

async function sendRegisterCode() {
  if (registerCountdown.value > 0 || !canSendRegisterCode.value) return;

  const { phone } = registerForm.value;

  try {
    await sellerSendCode(phone);
    uni.showToast({ title: '验证码已发送', icon: 'success' });
    startCountdown('register');
  } catch (error: any) {
    uni.showToast({ title: error.message || '发送失败，请稍后重试', icon: 'none' });
  }
}

async function sendLoginCode() {
  if (loginCountdown.value > 0 || !canSendLoginCode.value) return;

  const { phone } = loginForm.value;

  try {
    await sellerSendCode(phone);
    uni.showToast({ title: '验证码已发送', icon: 'success' });
    startCountdown('login');
  } catch (error: any) {
    uni.showToast({ title: error.message || '发送失败，请稍后重试', icon: 'none' });
  }
}

async function handleRegister() {
  if (!canSubmitRegister.value) return;

  const { phone, password, code, contactName, email } = registerForm.value;

  if (email && !validateEmail(email)) {
    uni.showToast({ title: '邮箱格式不正确', icon: 'none' });
    return;
  }

  loading.value = true;

  try {
    const res = await sellerRegister({
      phone,
      code,
      contactName: contactName.trim(),
      email: email || undefined,
      password,
    });

    sellerStore.setSellerLogin({
      accessToken: res.data.accessToken,
      sellerInfo: res.data.sellerInfo,
    });

    uni.showToast({ title: '注册成功，欢迎加入品住会', icon: 'success', duration: 2000 });

    setTimeout(() => {
      uni.redirectTo({ url: '/pages/seller/home' });
    }, 1500);
  } catch (error: any) {
    uni.showToast({ title: error.message || '注册失败，请稍后重试', icon: 'none', duration: 2000 });
  } finally {
    loading.value = false;
  }
}

async function handleLogin() {
  if (!canSubmitLogin.value) return;

  const { phone, code } = loginForm.value;

  loading.value = true;

  try {
    const res = await sellerLogin({ phone, code });

    sellerStore.setSellerLogin({
      accessToken: res.data.accessToken,
      sellerInfo: res.data.sellerInfo,
    });

    uni.showToast({ title: '登录成功，欢迎回来', icon: 'success', duration: 2000 });

    setTimeout(() => {
      uni.redirectTo({ url: '/pages/seller/home' });
    }, 1500);
  } catch (error: any) {
    uni.showToast({ title: error.message || '登录失败，请稍后重试', icon: 'none', duration: 2000 });
  } finally {
    loading.value = false;
  }
}

function showAgreement(type: string) {
  uni.navigateTo({
    url: `/pages/agreement/index?type=${type}`,
  });
}

function onAgreementChange(e: any) {
  agreed.value = e.detail.value.length > 0;
}
</script>

<style lang="scss" scoped>
@import '@/static/styles/common.scss';

.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

/* 顶部装饰 */
.header-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  pointer-events: none;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);

  &.circle-1 {
    width: 300rpx;
    height: 300rpx;
    top: -100rpx;
    right: -50rpx;
  }

  &.circle-2 {
    width: 200rpx;
    height: 200rpx;
    top: 100rpx;
    left: -80rpx;
  }
}

/* 品牌区域 */
.brand-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 48rpx 60rpx;
  position: relative;
  z-index: 1;
}

.brand-logo {
  width: 140rpx;
  height: 140rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 32rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
}

.brand-name {
  font-size: 44rpx;
  font-weight: 700;
  color: #FFFFFF;
  margin-bottom: 16rpx;
  letter-spacing: 1rpx;
}

.brand-slogan {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
  line-height: 1.6;
  max-width: 500rpx;
}

/* 表单容器 */
.form-container {
  background: #FFFFFF;
  border-radius: 40rpx 40rpx 0 0;
  padding: 0 48rpx 80rpx;
  position: relative;
  z-index: 2;
  min-height: calc(100vh - 400rpx);
}

/* 模式切换标签 */
.mode-tabs {
  display: flex;
  gap: 64rpx;
  padding: 48rpx 0 40rpx;
  border-bottom: 2rpx solid #F3F4F6;
}

.tab-item {
  position: relative;
  cursor: pointer;
}

.tab-text {
  font-size: 32rpx;
  color: #9CA3AF;
  font-weight: 500;
  transition: all 0.3s ease;

  .tab-item.active & {
    color: #3B82F6;
    font-weight: 600;
  }
}

.tab-indicator {
  position: absolute;
  bottom: -18rpx;
  left: 0;
  right: 0;
  height: 6rpx;
  background: #3B82F6;
  border-radius: 3rpx;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    transform: scaleX(0);
  }
  to {
    transform: scaleX(1);
  }
}

/* 表单包装器 */
.form-wrapper {
  padding-top: 48rpx;
}

/* 输入组 */
.input-group {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.input-item {
  position: relative;

  &.optional-item {
    .input-label {
      opacity: 0.7;
    }
  }
}

.input-label {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.label-text {
  font-size: 28rpx;
  color: #374151;
  font-weight: 500;

  &.optional {
    color: #9CA3AF;
  }
}

.input-field {
  width: 100%;
  height: 96rpx;
  background: #F9FAFB;
  border: 2rpx solid #E5E7EB;
  border-radius: 16rpx;
  padding: 0 28rpx;
  font-size: 30rpx;
  color: #111827;
  transition: all 0.3s ease;
  box-sizing: border-box;

  &:focus {
    background: #FFFFFF;
    border-color: #3B82F6;
    box-shadow: 0 0 0 6rpx rgba(59, 130, 246, 0.1);
  }

  &.code-field {
    padding-right: 220rpx;
  }
}

.input-placeholder {
  color: #9CA3AF;
  font-size: 28rpx;
}

.input-suffix {
  position: absolute;
  right: 28rpx;
  top: 72rpx;
  display: flex;
  align-items: center;
  height: 96rpx;
}

.code-button {
  padding: 0 28rpx;
  height: 64rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #FFFFFF;
  font-weight: 500;
  white-space: nowrap;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);

  &:active:not(.disabled) {
    transform: scale(0.96);
    box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
  }

  &.disabled {
    background: #E5E7EB;
    color: #9CA3AF;
    box-shadow: none;
  }
}

/* 协议区域 */
.agreement-section {
  margin: 48rpx 0 40rpx;
}

.agreement-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
}

.agreement-checkbox {
  margin-top: 4rpx;
  transform: scale(1.1);
}

.agreement-text {
  flex: 1;
  font-size: 24rpx;
  color: #6B7280;
  line-height: 1.7;
}

.link-text {
  color: #3B82F6;
  font-weight: 500;
  text-decoration: underline;
}

/* 提交按钮 */
.submit-button {
  width: 100%;
  height: 104rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;

  &:active:not(.disabled) {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);
  }

  &.disabled {
    background: #E5E7EB;
    box-shadow: none;

    .button-text {
      color: #9CA3AF;
    }
  }
}

.button-text {
  font-size: 32rpx;
  color: #FFFFFF;
  font-weight: 600;
  letter-spacing: 1rpx;
}

/* 底部提示 */
.footer-tips {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  margin-top: 64rpx;
  padding: 40rpx 32rpx;
  background: linear-gradient(135deg, #F0F9FF 0%, #E0E7FF 100%);
  border-radius: 20rpx;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.tip-text {
  font-size: 26rpx;
  color: #374151;
  font-weight: 500;
}
</style>