<script setup lang="ts">
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import api from '../api';
import { ElMessage } from 'element-plus';
import { useAuthStore, type StaffUser } from '../stores/auth';
import RobotVerify from '../components/RobotVerify.vue';
import AdminLocaleSwitcher from '../components/AdminLocaleSwitcher.vue';
import { useAdminLocale } from '../composables/useAdminLocale';
import { ensureStaffSession } from '../utils/session-hydrate';
import { effectivePermissions, firstAdminFallback } from '../utils/admin-access';
import bgImage from '../assets/images/bg.webp';

const router = useRouter();
const route = useRoute();
const auth = useAuthStore();
const { t } = useAdminLocale();

const form = ref({ username: '', password: '' });
const loading = ref(false);
const captchaRef = ref<InstanceType<typeof RobotVerify> | null>(null);
const isDev = import.meta.env.DEV;

async function finishLogin(payload: { token: string; user: StaffUser }) {
  auth.setSession(payload.token, payload.user);
  await ensureStaffSession();
  const redirectQuery = route.query.redirect as string | undefined;
  const role = auth.user.value?.role;
  const permissions = effectivePermissions(role, auth.user.value?.permissions);
  const target =
    redirectQuery ||
    firstAdminFallback(role, permissions) ||
    '/';
  await router.push(target);
}

async function quickLogin(username: string, password: string) {
  loading.value = true;
  try {
    const { data } = await api.post('/manage/auth/login', { username, password });
    const payload = data.data as { token: string; user: StaffUser };
    await finishLogin(payload);
  } catch {
    ElMessage.error(t('login.err_quick'));
  } finally {
    loading.value = false;
  }
}

async function login() {
  if (!captchaRef.value?.validate()) {
    ElMessage.error(t('login.err_captcha'));
    captchaRef.value?.refresh();
    return;
  }
  loading.value = true;
  try {
    const { data } = await api.post('/manage/auth/login', form.value);
    const payload = data.data as { token: string; user: StaffUser };
    await finishLogin(payload);
  } catch {
    ElMessage.error(t('login.err_failed'));
    captchaRef.value?.refresh();
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div class="login-page" :style="{ backgroundImage: `url(${bgImage})` }">
    <div class="login-mask" />
    <div class="login-wrap">
      <form @submit.prevent="login" class="login-form" autocomplete="off">
        <div class="form-lang">
          <AdminLocaleSwitcher variant="gold" />
        </div>

        <div class="form-body">
          <aside class="form-brand">
            <img src="/logo.png" alt="TheBet365" class="logo-large" />
          </aside>

          <div class="form-fields">
            <h2 class="title">{{ t('login.title') }}</h2>

            <label>{{ t('login.username') }}</label>
            <input v-model="form.username" class="field" :placeholder="t('login.username_ph')" autocomplete="off" required />
            <label>{{ t('login.password') }}</label>
            <input v-model="form.password" class="field" type="password" :placeholder="t('login.password_ph')" autocomplete="off" required />

            <RobotVerify ref="captchaRef" />

            <button type="submit" class="btn-login" :disabled="loading">
              {{ loading ? '...' : t('login.submit') }}
            </button>

            <template v-if="isDev">
              <div class="quick-label">{{ t('login.quick_label') }}</div>
              <div class="quick-btns">
                <button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('admin', 'Admin@123')">
                  <span class="quick-role">{{ t('login.quick_admin') }}</span>
                  <span class="quick-acc">admin</span>
                </button>
                <button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('agent1', 'Agent@123')">
                  <span class="quick-role">{{ t('login.quick_agent') }}</span>
                  <span class="quick-acc">agent1</span>
                </button>
                <button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('agent2', 'Agent@123')">
                  <span class="quick-role">{{ t('login.quick_agent2') }}</span>
                  <span class="quick-acc">agent2</span>
                </button>
                <button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('matchadmin', 'MatchAdmin@123')">
                  <span class="quick-role">{{ t('login.quick_match_admin') }}</span>
                  <span class="quick-acc">matchadmin</span>
                </button>
                <button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('financeadmin', 'FinanceAdmin@123')">
                  <span class="quick-role">{{ t('login.quick_finance_admin') }}</span>
                  <span class="quick-acc">financeadmin</span>
                </button>
                <button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('support1', 'Support@123')">
                  <span class="quick-role">{{ t('login.quick_support') }}</span>
                  <span class="quick-acc">support1</span>
                </button>
              </div>
            </template>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped>
.login-page {
  min-height: 100vh;
  background-color: #000;
  background-size: cover;
  background-position: center top;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.login-mask {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.55);
}
.login-wrap {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 720px;
  padding: 0 20px;
}

.login-form {
  position: relative;
  padding: 14px 0 0;
  background: rgba(14, 14, 14, 0.92);
  border: 1px solid rgba(212, 175, 55, 0.28);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.45);
  overflow: hidden;
}

.form-lang {
  display: flex;
  justify-content: flex-end;
  padding: 0 18px 10px;
}

.form-body {
  display: grid;
  grid-template-columns: minmax(200px, 260px) 1fr;
  align-items: stretch;
}

.form-brand {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 28px 20px;
  background: rgba(0, 0, 0, 0.25);
  border-right: 1px solid rgba(212, 175, 55, 0.15);
}

.logo-large {
  width: 100%;
  max-width: 220px;
  height: auto;
  object-fit: contain;
  filter: drop-shadow(0 4px 24px rgba(212, 175, 55, 0.25));
}

.form-fields {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 22px 24px 24px;
  min-width: 0;
}

.title {
  text-align: left;
  font-size: 15px;
  font-weight: 700;
  color: #aaa;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  margin-bottom: 4px;
}

@media (max-width: 640px) {
  .login-wrap {
    max-width: 400px;
  }

  .form-body {
    grid-template-columns: 1fr;
  }

  .form-brand {
    padding: 20px 24px 12px;
    border-right: none;
    border-bottom: 1px solid rgba(212, 175, 55, 0.15);
  }

  .logo-large {
    max-width: 180px;
  }

  .form-fields {
    padding: 18px 20px 22px;
  }

  .title {
    text-align: center;
  }
}
label {
  font-size: 11px;
  color: #666;
  font-weight: 600;
  letter-spacing: 0.05em;
  text-transform: uppercase;
}
.field {
  width: 100%;
  height: 44px;
  padding: 0 14px;
  background: #0a0a0a;
  border: 1px solid #2a2a2a;
  border-radius: 8px;
  color: #fff;
  font-size: 14px;
  font-family: inherit;
  outline: none;
  box-sizing: border-box;
  transition: border-color 0.2s;
}
.field::placeholder { color: #3a3a3a; }
.field:focus {
  border-color: rgba(255, 255, 255, 0.28);
  box-shadow: none;
}
.field:-webkit-autofill,
.field:-webkit-autofill:focus {
  -webkit-box-shadow: 0 0 0 1000px #0a0a0a inset;
  -webkit-text-fill-color: #fff;
  caret-color: #fff;
}
.btn-login {
  margin-top: 6px;
  height: 44px;
  background: #f5f5f5;
  border: 1px solid #f5f5f5;
  border-radius: 6px;
  color: #0a0a0a;
  font-size: 14px;
  font-weight: 500;
  font-family: inherit;
  letter-spacing: 0;
  box-shadow: none;
  transition: background 0.15s, border-color 0.15s;
}
.btn-login:hover:not(:disabled) {
  background: #ffffff;
  border-color: #ffffff;
  color: #0a0a0a;
  box-shadow: none;
}
.btn-login:disabled { opacity: 0.4; cursor: not-allowed; }
.quick-label {
  font-size: 10px;
  color: #2a2a2a;
  text-align: center;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  margin-top: 6px;
}
.quick-btns {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}
.quick-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  padding: 8px 10px;
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid #1e1e1e;
  border-radius: 7px;
  font-family: inherit;
  cursor: pointer;
  transition: all 0.15s;
}
.quick-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.06);
  border-color: rgba(255, 255, 255, 0.18);
}
.quick-btn:disabled { opacity: 0.4; cursor: not-allowed; }
.quick-role {
  font-size: 11px;
  font-weight: 700;
  color: #555;
  letter-spacing: 0.04em;
}
.quick-acc {
  font-size: 12px;
  color: var(--gold-text);
  font-weight: 600;
  font-family: monospace;
}

/* Light operational login */
.login-page {
  min-height: 100dvh;
  background-color: #f7f6f3;
  background-size: cover;
  background-position: center;
}

.login-page::before {
  content: '';
  position: absolute;
  inset: 0;
  background:
    linear-gradient(120deg, rgba(247, 246, 243, 0.94), rgba(247, 246, 243, 0.82)),
    rgba(247, 246, 243, 0.9);
}

.login-mask {
  background:
    linear-gradient(180deg, rgba(255, 255, 255, 0.54), rgba(240, 237, 230, 0.82));
}

.login-wrap {
  max-width: 760px;
}

.login-form {
  padding: 12px 0 0;
  border: 1px solid var(--border);
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.94);
  box-shadow: 0 24px 72px rgba(56, 49, 37, 0.14);
  backdrop-filter: blur(14px);
}

.form-lang {
  padding: 0 18px 12px;
}

.form-body {
  grid-template-columns: minmax(210px, 270px) 1fr;
}

.form-brand {
  background: #f4f0e8;
  border-right: 1px solid var(--border);
}

.logo-large {
  filter: none;
}

.form-fields {
  gap: 10px;
  padding: 24px 26px 26px;
}

.title {
  margin: 0 0 8px;
  color: var(--text);
  font-size: 18px;
  font-weight: 800;
  letter-spacing: 0;
  text-transform: none;
}

label {
  color: #6c675f;
  font-size: 12px;
  font-weight: 750;
  letter-spacing: 0;
  text-transform: none;
}

.field {
  height: 44px;
  background: #ffffff;
  border-color: var(--border);
  border-radius: 8px;
  color: var(--text);
  font-weight: 600;
}

.field::placeholder {
  color: #aaa49a;
}

.field:focus {
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(31, 35, 32, 0.08);
}

.field:-webkit-autofill,
.field:-webkit-autofill:focus {
  -webkit-box-shadow: 0 0 0 1000px #ffffff inset;
  -webkit-text-fill-color: var(--text);
  caret-color: var(--text);
}

.btn-login {
  height: 44px;
  border-color: var(--primary);
  border-radius: 8px;
  background: var(--primary);
  color: #ffffff;
  font-weight: 750;
}

.btn-login:hover:not(:disabled) {
  border-color: var(--primary-light);
  background: var(--primary-light);
  color: #ffffff;
}

.btn-login:disabled {
  opacity: 0.58;
}

.quick-label {
  margin-top: 8px;
  color: var(--text-muted);
  letter-spacing: 0;
  text-transform: none;
}

.quick-btns {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

.quick-btn {
  min-height: 54px;
  border-color: var(--border);
  border-radius: 8px;
  background: #fbfaf7;
}

.quick-btn:hover:not(:disabled) {
  background: var(--accent-hover);
  border-color: #d5cfc3;
}

.quick-role {
  color: var(--text-muted);
  letter-spacing: 0;
}

.quick-acc {
  color: var(--text);
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}

@media (max-width: 640px) {
  .login-page {
    align-items: stretch;
  }

  .login-wrap {
    display: flex;
    align-items: center;
    max-width: 420px;
    min-height: 100dvh;
    padding: 18px;
  }

  .form-brand {
    padding: 22px 24px 14px;
    border-right: none;
    border-bottom: 1px solid var(--border);
  }

  .form-fields {
    padding: 20px;
  }

  .title {
    text-align: left;
  }

  .quick-btns {
    grid-template-columns: 1fr;
  }
}
</style>
