<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { defaultPhoneIsoForLocale, getPhoneDialFromIso } from '@thebet365/shared';
import { useAuthStore } from '../stores/auth';
import { useAppLocale } from '../composables/useAppLocale';
import LocaleSwitcher from '../components/LocaleSwitcher.vue';
import PhoneCountrySelect from '../components/PhoneCountrySelect.vue';
import RobotVerify from '../components/RobotVerify.vue';
import GoldSpinner from '../components/GoldSpinner.vue';
import loginBg from '../assets/images/zt2.webp';

const props = withDefaults(defineProps<{ desktop?: boolean }>(), { desktop: false });

type LoginMode = 'account' | 'phone';

const { t, locale } = useI18n();
const { syncLocaleToBackend } = useAppLocale();
const auth = useAuthStore();
const router = useRouter();
const route = useRoute();
const captchaRef = ref<InstanceType<typeof RobotVerify> | null>(null);
const loginMode = ref<LoginMode>('account');
const account = ref('');
const phone = ref('');
const countryIso = ref(defaultPhoneIsoForLocale(locale.value));
const password = ref('');
const error = ref('');
const loading = ref(false);

const resetSuccess = computed(() => route.query.reset === 'success');

function goForgotPassword() {
  router.push({
    path: '/forgot-password',
    query: route.query.redirect ? { redirect: route.query.redirect as string } : {},
  });
}

function switchLoginMode(mode: LoginMode) {
  if (loginMode.value === mode) return;
  loginMode.value = mode;
  error.value = '';
}

async function submit() {
  if (!captchaRef.value?.validate()) {
    error.value = t('auth.captcha_wrong');
    captchaRef.value?.refresh();
    return;
  }
  loading.value = true;
  error.value = '';
  try {
    const isPhone = loginMode.value === 'phone';
    const loginId = isPhone ? phone.value : account.value;
    const countryCode = isPhone ? getPhoneDialFromIso(countryIso.value) : undefined;
    await auth.login(loginId, password.value, countryCode);
    await syncLocaleToBackend();
    const redirectTo = (route.query.redirect as string) || '/';
    router.push(redirectTo);
  } catch (e: unknown) {
    error.value = (e as { response?: { data?: { error?: string } } })?.response?.data?.error || 'Login failed';
  } finally {
    loading.value = false;
  }
}

function isGuestBrowsablePath(path: string): boolean {
  if (!path || path === '/' || path === '/bet') return true;
  if (path.startsWith('/match/')) return true;
  return false;
}

function continueBrowsing() {
  const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '';
  const target = isGuestBrowsablePath(redirect) ? redirect || '/' : '/';
  router.replace(target);
}

function goRegister() {
  router.push({
    path: '/register',
    query: route.query.redirect ? { redirect: route.query.redirect as string } : {},
  });
}
</script>

<template>
  <div class="login-page" :class="{ 'login-page--desktop': props.desktop }" :style="props.desktop ? undefined : { backgroundImage: `url(${loginBg})` }">
    <div v-if="!props.desktop" class="login-lang">
      <LocaleSwitcher compact />
    </div>
    <div class="login-stack">
      <form
        @submit.prevent="submit"
        class="login-form"
        :class="{ 'ps-gold-frame': !props.desktop, 'is-busy': loading }"
      >
      <div v-if="loading" class="form-busy-overlay" aria-hidden="true">
        <GoldSpinner :size="40" :active="true" />
        <p class="form-busy-text">{{ t('auth.logging_in') }}</p>
      </div>
      <h2 v-if="props.desktop" class="form-title">{{ t('auth.login') }}</h2>
      <div class="auth-tabs">
        <button
          type="button"
          class="auth-tab"
          :class="{ active: loginMode === 'account' }"
          :disabled="loading"
          @click="switchLoginMode('account')"
        >
          {{ t('auth.login_by_account') }}
        </button>
        <button
          type="button"
          class="auth-tab"
          :class="{ active: loginMode === 'phone' }"
          :disabled="loading"
          @click="switchLoginMode('phone')"
        >
          {{ t('auth.login_by_phone') }}
        </button>
      </div>

      <div v-if="loginMode === 'account'" class="field">
        <label>{{ t('auth.username') }}</label>
        <input
          v-model="account"
          class="field-input ps-gold-input"
          required
          autocomplete="username"
          maxlength="32"
          :disabled="loading"
          :placeholder="t('auth.username_placeholder')"
        />
      </div>

      <div v-else class="field">
        <label>{{ t('auth.phone') }}</label>
        <div class="inline-row">
          <PhoneCountrySelect v-model="countryIso" />
          <input
            v-model="phone"
            class="field-input ps-gold-input"
            type="tel"
            required
            autocomplete="tel-national"
            :disabled="loading"
            :placeholder="t('auth.phone_local_placeholder')"
          />
        </div>
      </div>

      <div class="field">
        <label>{{ t('auth.password') }}</label>
        <input v-model="password" class="field-input ps-gold-input" type="password" required autocomplete="current-password" :disabled="loading" />
      </div>

      <button type="button" class="btn-forgot" :disabled="loading" @click="goForgotPassword">
        {{ t('auth.forgot_password') }}
      </button>

      <RobotVerify ref="captchaRef" />
      <p v-if="resetSuccess" class="success">{{ t('auth.reset_success') }}</p>
      <p v-if="error" class="error">{{ error }}</p>
      <button
        type="submit"
        class="btn-login btn-gold-outline"
        :class="{ 'is-loading': loading }"
        :disabled="loading"
        :aria-busy="loading"
      >
        <span v-if="loading" class="btn-inline-loading">
          <GoldSpinner :size="18" :active="true" />
          {{ t('auth.logging_in') }}
        </span>
        <span v-else>{{ t('auth.login') }}</span>
      </button>
      <button v-if="props.desktop" type="button" class="btn-skip" :disabled="loading" @click="goRegister">
        {{ t('auth.go_register') }}
      </button>
      </form>
      <div v-if="!props.desktop" class="login-actions">
        <button type="button" class="btn-skip" :disabled="loading" @click="goRegister">
          {{ t('auth.go_register') }}
        </button>
        <button type="button" class="btn-skip-light" :disabled="loading" @click="continueBrowsing">
          {{ t('auth.continue_browsing') }}
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-lang {
  position: absolute;
  top: max(12px, env(safe-area-inset-top));
  right: 16px;
  z-index: 10;
}

.login-page {
  position: relative;
  height: 100%;
  min-height: 100dvh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  padding: 34vh 20px max(20px, env(safe-area-inset-bottom));
  background-color: var(--bg-body);
  background-size: cover;
  background-position: center top;
  background-repeat: no-repeat;
}

.login-page--desktop {
  min-height: auto;
  height: auto;
  width: 100%;
  align-items: stretch;
  justify-content: flex-start;
  padding: 0;
  background-color: transparent;
  overflow: visible;
}

.login-page--desktop .login-stack {
  max-width: none;
  width: 100%;
}

.login-stack {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 320px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.login-form {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 14px;
}

.login-form.is-busy {
  pointer-events: none;
}

.form-busy-overlay {
  position: absolute;
  inset: 0;
  z-index: 3;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  border-radius: inherit;
  background: rgba(255, 255, 255, 0.88);
  backdrop-filter: blur(4px);
  pointer-events: all;
}

.form-busy-text {
  margin: 0;
  font-size: 13px;
  font-weight: 700;
  color: var(--primary);
  letter-spacing: 0.04em;
}

.btn-inline-loading {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.login-page--desktop .login-form {
  gap: 10px;
  padding: 0;
  border: none !important;
  background: transparent !important;
  box-shadow: none !important;
}

.form-title {
  margin: 0 0 8px;
  font-size: 18px;
  font-weight: 800;
  color: var(--primary);
  text-align: left;
  letter-spacing: 0.02em;
}

.login-page--desktop .field {
  gap: 8px;
}

.login-page--desktop label {
  font-size: 13px;
}

.login-page--desktop .field-input {
  height: 46px;
  padding: 0 14px;
}

.login-page--desktop .auth-tabs {
  margin-bottom: 8px;
}

.login-page--desktop .btn-login {
  margin-top: 10px;
  min-height: 50px;
  font-size: 15px;
}

.login-page--desktop .btn-skip {
  margin-top: 6px;
  padding: 12px 16px;
  border-radius: var(--radius-sm);
  border: 1px solid var(--border);
  background: var(--bg-card);
}

.login-page--desktop .btn-skip:hover:not(:disabled) {
  border-color: var(--border-active);
  background: var(--surface-accent);
}

.login-page--desktop .error {
  padding: 6px 10px;
  border-radius: var(--radius-sm);
  background: rgba(220, 38, 38, 0.08);
  border-left: 2px solid var(--danger);
}

.login-page--desktop .success {
  padding: 6px 10px;
  border-radius: var(--radius-sm);
  background: rgba(5, 150, 105, 0.08);
  border-left: 2px solid var(--success);
}

.btn-login.is-loading:disabled {
  opacity: 1;
}

.auth-tab:disabled,
.btn-forgot:disabled,
.btn-skip:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.login-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  padding: 0 14px 4px;
}

.auth-tabs {
  display: flex;
  gap: 6px;
  margin-bottom: 4px;
  padding: 4px;
  border-radius: var(--radius-sm);
  background: var(--bg-body);
  border: 1px solid var(--border);
}

.auth-tab {
  flex: 1;
  min-height: 34px;
  padding: 0 8px;
  border-radius: 6px;
  border: 1px solid transparent;
  background: transparent;
  color: var(--text-muted);
  font-size: 12px;
  font-weight: 700;
  cursor: pointer;
  transition: background 0.2s, border-color 0.2s, color 0.2s;
}

.auth-tab.active {
  border-color: var(--primary);
  color: var(--text);
  background: var(--surface-accent);
}

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

.field-input {
  width: 100%;
  height: 36px;
  padding: 0 10px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--bg-input);
  color: var(--text);
  font-size: 14px;
  font-family: inherit;
}

.field-input:focus {
  outline: none;
  border-color: var(--border-gold-soft);
}

.inline-row {
  display: flex;
  gap: 6px;
  align-items: center;
}

.inline-row .field-input {
  flex: 1;
  min-width: 0;
}

label {
  font-size: 11px;
  color: var(--text-muted);
  font-weight: 600;
  letter-spacing: 0.04em;
}

.btn-forgot {
  align-self: flex-end;
  margin: -4px 0 0;
  padding: 0;
  border: none;
  background: transparent;
  color: var(--text-muted);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
}

.btn-forgot:active {
  color: var(--text);
}

.btn-login {
  margin-top: 4px;
  padding: 10px 14px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 800;
  letter-spacing: 0.06em;
}

.btn-login:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.btn-skip {
  padding: 6px 14px;
  border: none;
  background: transparent;
  color: var(--primary);
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  text-align: center;
}

.btn-skip:active {
  color: var(--primary-dark);
}

.btn-skip-light {
  padding: 6px 16px;
  border: none;
  background: transparent;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 400;
  cursor: pointer;
  white-space: nowrap;
  text-align: center;
}

.btn-skip-light:active {
  color: var(--text);
}

.error {
  color: var(--danger);
  font-size: 13px;
  font-weight: 600;
}

.success {
  margin: 0;
  color: var(--success);
  font-size: 12px;
  font-weight: 600;
  line-height: 1.4;
}
</style>
