<template>
  <div class="pc-login-container">
    <div class="lang-selector-wrapper">
      <selectLang />
    </div>

    <div class="bg-glow glow-top-right"></div>
    <div class="bg-glow glow-bottom-left"></div>

    <div class="login-card">
      <div class="logo-header">
        <h2 class="app-name tmc">{{ appName || 'MELBET' }}</h2>
        <p class="app-desc">{{ appDescription || t('专业体育与彩票竞猜平台') }}</p>
      </div>

      <el-tabs v-model="activeLoginType" class="custom-tabs" stretch>
        <el-tab-pane :label="t('邮箱登录')" name="email"></el-tab-pane>
        <el-tab-pane :label="t('手机号登录')" name="phone"></el-tab-pane>
      </el-tabs>

      <div v-show="activeLoginType === 'email'" class="form-wrapper">
        <el-input
            v-model="emailForm.account"
            :placeholder="t('请输入登录邮箱')"
            clearable
            size="large"
            class="custom-input"
        >
          <template #prefix><el-icon><Message /></el-icon></template>
        </el-input>

        <el-input
            v-model="emailForm.password"
            :placeholder="t('请输入登录密码')"
            type="password"
            show-password
            clearable
            size="large"
            class="custom-input"
        >
          <template #prefix><el-icon><Lock /></el-icon></template>
        </el-input>
      </div>

      <div v-show="activeLoginType === 'phone'" class="form-wrapper">
        <div class="phone-input-group">
          <el-select v-model="selectedAreaCode" size="large" class="area-select" :teleported="false">
            <el-option v-for="item in areaCodes" :key="item.value" :label="item.value" :value="item.value">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
          <el-input
              v-model="phoneForm.phone"
              :placeholder="t('请输入手机号')"
              clearable
              size="large"
              class="custom-input phone-input"
          >
            <template #prefix><el-icon><Iphone /></el-icon></template>
          </el-input>
        </div>

        <!-- <div class="code-input-group">
          <el-input
              v-model="phoneForm.code"
              :placeholder="t('请输入验证码')"
              clearable
              size="large"
              class="custom-input"
          >
            <template #prefix><el-icon><Key /></el-icon></template>
          </el-input>
          <el-button type="primary" size="large" class="get-code-btn" :disabled="countdown > 0" @click="getCode">
            {{ countdown > 0 ? `${countdown}s` : t('获取验证码') }}
          </el-button>
        </div> -->
      </div>

      <div class="action-row">
        <el-checkbox v-model="RememberPwd" class="custom-checkbox">{{ t('记住密码') }}</el-checkbox>
        <div class="register-link" @click="router.push('/register')">
          {{ t('还没有账号') }}？<span class="tmc">{{ t('去注册') }}</span>
        </div>
      </div>

      <el-button type="primary" class="submit-btn" size="large" @click="onLoginClick">
        {{ t('登录') }}
      </el-button>

      <div class="guest-mode tmc" @click="onGuestClick">
        {{ t('游客模式') }}
      </div>

      <div class="agreement-row">
        <el-checkbox v-model="agreed" class="custom-checkbox">{{ t('我已阅读并同意') }}</el-checkbox>
        <span class="agreement-link tmc" @click="onAgreementClick">《{{ t('产品服务协议') }}》</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Message, Lock, Iphone, Key } from '@element-plus/icons-vue';
import socket from '@/utils/websocket.js'
import { appDescription, appName } from '@/settings/index.mjs';
import selectLang from '@/components/selectLang/index.vue';
import { postUserLogin, sendCode } from "@/request/api";

const router = useRouter();
const { t } = useI18n();

const agreed = ref(false);
const RememberPwd = ref(false);
const activeLoginType = ref('email');

const selectedAreaCode = ref('+86');
const areaCodes = ref([
  { name: '+86 中国大陆', value: '+86' },
  { name: '+1 美国', value: '+1' },
  { name: '+84 越南', value: '+84' },
  { name: '+44 英国', value: '+44' },
  { name: '+61 澳大利亚', value: '+61' }
]);

const emailForm = reactive({ account: '', password: '' });
const phoneForm = reactive({ phone: '', code: '' });

const countdown = ref(0);
let timer = null;

function initRecall() {
  const isRemember = localStorage.getItem('is_remember_pwd');
  if (isRemember === 'true') {
    const savedAccount = localStorage.getItem('saved_account');
    const savedPassword = localStorage.getItem('saved_password');
    if (savedAccount && savedPassword) {
      emailForm.account = savedAccount;
      emailForm.password = savedPassword;
      RememberPwd.value = true;
    }
  }
}

function getCode() {
  if (!phoneForm.phone) return ElMessage.warning(t('请输入手机号'));

  // 接口已封装提示，只需处理业务逻辑
  sendCode({ phone: phoneForm.phone, area: selectedAreaCode.value }).then(res => {
    countdown.value = 60;
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) clearInterval(timer);
    }, 1000);
  });
}

function onAgreementClick() {
  ElMessageBox.alert(
      `<div style="line-height: 1.6; color: #333; text-align: left;">
      <h3 style="margin-bottom: 16px;">平台服务协议</h3>
      <p>1. 本平台提供相关的体育与彩票服务...</p>
      <p>2. 请确保您已达到法定年龄...</p>
    </div>`,
      t('产品服务协议'),
      { dangerouslyUseHTMLString: true, confirmButtonText: t('确定'), customClass: 'agreement-msgbox' }
  );
}

function validateEmailForm() {
  if (!emailForm.account) { ElMessage.warning(t('请输入登录邮箱')); return false; }
  if (!emailForm.password) { ElMessage.warning(t('请输入登录密码')); return false; }
  if (emailForm.password.length < 6 || emailForm.password.length > 20) {
    ElMessage.warning(t('密码长度需在6-20个字符之间'));
    return false;
  }
  return true;
}

function validatePhoneForm() {
  if (!phoneForm.phone) { ElMessage.warning(t('请输入手机号')); return false; }
  // if (!phoneForm.code) { ElMessage.warning(t('请输入验证码')); return false; }
  // if (phoneForm.code.length !== 6) { ElMessage.warning(t('验证码长度为6位')); return false; }
  return true;
}

function checkAgreement(callback) {
  if (!agreed.value) {
    ElMessageBox.confirm(
        t('为了保障您的权益，请先阅读并同意') + '《' + t('产品服务协议') + '》',
        t('温馨提示'),
        { confirmButtonText: t('同意并继续'), cancelButtonText: t('取消'), type: 'warning' }
    ).then(() => {
      agreed.value = true;
      callback();
    }).catch(() => {});
    return;
  }
  callback();
}

function onGuestClick() {
  checkAgreement(() => { router.push('/SportsBetting'); });
}

function onLoginClick() {
  checkAgreement(async () => {
    let isValid = false;
    if (activeLoginType.value === 'email') {
      isValid = validateEmailForm();
    } else {
      isValid = validatePhoneForm();
      if (isValid) return ElMessage.info(t('手机号登录功能暂未开放，敬请期待'));
    }
    if (!isValid) return;

    // 接口已封装提示，只需处理业务逻辑
    postUserLogin({ account: emailForm.account, password: emailForm.password }).then((res) => {
      socket.close();
      if (activeLoginType.value === 'email') {
        if (RememberPwd.value) {
          localStorage.setItem('is_remember_pwd', 'true');
          localStorage.setItem('saved_account', emailForm.account);
          localStorage.setItem('saved_password', emailForm.password);
        } else {
          localStorage.removeItem('is_remember_pwd');
          localStorage.removeItem('saved_account');
          localStorage.removeItem('saved_password');
        }
      }
      localStorage.setItem('token', res.data.token);
      let timer = setTimeout(() => {
        clearTimeout(timer)
        socket.connect(res.data.token);
      }, 2000)
      setTimeout(() => { router.push('/SportsBetting'); }, 1000);
    });
  });
}

onMounted(() => { initRecall(); });
</script>

<style scoped lang="scss">
$bg-dark: #1a1a1a;
$card-bg: #262626;
$main-color: #f8b932;
$text-normal: #c0c4cc;

.pc-login-container {
  position: relative; min-height: 100vh; width: 100vw; background-color: $bg-dark;
  display: flex; justify-content: center; align-items: center; overflow: hidden;

  .lang-selector-wrapper { position: absolute; top: 24px; right: 32px; z-index: 10; }

  .bg-glow { position: absolute; border-radius: 50%; filter: blur(100px); opacity: 0.15; z-index: 1; }
  .glow-top-right { top: -10%; right: 10%; width: 400px; height: 400px; background-color: $main-color; }
  .glow-bottom-left { bottom: -10%; left: 10%; width: 300px; height: 300px; background-color: $main-color; }

  .login-card {
    min-width: 500px;
    position: relative; z-index: 2; width: 30%; padding: 40px;
    background-color: rgba($card-bg, 0.95); border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); border: 1px solid rgba(255, 255, 255, 0.05);

    .logo-header {
      text-align: center; margin-bottom: 30px;
      .app-name { font-size: 32px; margin: 0 0 10px 0; font-weight: 900; letter-spacing: 2px; }
      .app-desc { font-size: 14px; color: #909399; margin: 0; }
    }

    .custom-tabs {
      margin-bottom: 24px;
      :deep(.el-tabs__item) {
        color: $text-normal; font-size: 16px;
        &.is-active { color: $main-color; font-weight: bold; }
        &:hover { color: $main-color; }
      }
      :deep(.el-tabs__active-bar) { background-color: $main-color; }
      :deep(.el-tabs__nav-wrap::after) { background-color: rgba(255,255,255,0.1); }
    }

    .form-wrapper { display: flex; flex-direction: column; gap: 20px; }

    .custom-input {
      :deep(.el-input__wrapper) {
        background-color: #1f1f1f; box-shadow: 0 0 0 1px #333 inset; padding: 0 16px; height: 48px;
        &:hover, &.is-focus { box-shadow: 0 0 0 1px $main-color inset; }
      }
      :deep(.el-input__inner) { color: #fff; height: 100%; &::placeholder { color: #666; } }
      :deep(.el-icon) { color: #888; font-size: 18px; }
    }

    /* 手机号混合排版 - 修复区号选择框高度与白底 */
    .phone-input-group {
      display: flex; gap: 12px; align-items: stretch;

      .area-select {
        width: 110px;
        /* 兼容新老版本的 Element Plus Wrapper */
        :deep(.el-input__wrapper),
        :deep(.el-select__wrapper) {
          background-color: #1f1f1f;
          box-shadow: 0 0 0 1px #333 inset;
          height: 48px;
          min-height: 48px;
          &:hover, &.is-focus { box-shadow: 0 0 0 1px $main-color inset; }
        }
        :deep(.el-input__inner), :deep(.el-select__placeholder) { color: #fff; text-align: center;}
      }

      .phone-input { flex: 1; }
    }

    .code-input-group {
      display: flex; gap: 12px;
      .custom-input { flex: 1; }
      .get-code-btn { width: 120px; height: 48px; font-weight: bold; color: #000; }
    }

    .action-row {
      display: flex; justify-content: space-between; align-items: center; margin-top: 20px; margin-bottom: 30px;
      .register-link { font-size: 14px; color: $text-normal; cursor: pointer; span { &:hover { text-decoration: underline; } } }
    }

    .custom-checkbox {
      :deep(.el-checkbox__label) { color: $text-normal; }
      :deep(.el-checkbox__input.is-checked .el-checkbox__inner) { background-color: $main-color; border-color: $main-color; }
      :deep(.el-checkbox__input.is-checked + .el-checkbox__label) { color: #fff; }
    }

    .submit-btn { width: 100%; height: 50px; font-size: 18px; font-weight: bold; color: #000; letter-spacing: 4px; margin-bottom: 20px; border-radius: 8px; }

    .guest-mode { text-align: center; cursor: pointer; font-size: 14px; margin-bottom: 30px; &:hover { text-decoration: underline; } }

    .agreement-row {
      display: flex; align-items: center; justify-content: center; font-size: 13px;
      .agreement-link { cursor: pointer; margin-left: -6px; &:hover { text-decoration: underline; } }
    }
  }

  /* 穿透修改下拉菜单黑底金字，彻底去除白边 */
  :deep(.el-popper) {
    background-color: #1f1f1f !important;
    border: 1px solid #333 !important;
    .el-select-dropdown__item {
      color: #c0c4cc;
      &.is-hovering, &:hover { background-color: #333; }
      &.is-selected { color: $main-color; font-weight: bold; }
    }
    .el-popper__arrow::before {
      background-color: #1f1f1f !important;
      border: 1px solid #333 !important;
    }
  }
}
</style>
