<template>
  <div class="page">
    <h1>🔐 Вход в систему</h1>
    <p>Войдите в свой личный кабинет</p>

    <form @submit.prevent="handleLogin" class="login-form">
      <div class="form-group">
        <input type="email" placeholder="Email" class="form-input" v-model="credentials.email" required
          :disabled="loading">
      </div>
      <div class="form-group">
        <input type="password" placeholder="Пароль" class="form-input" autocomplete="current-password"
          v-model="credentials.password" required :disabled="loading">
      </div>

      <button type="submit" class="btn btn-primary" :disabled="loading">
        {{ loading ? 'Вход...' : 'Войти' }}
      </button>

      <div v-if="error" class="error-message">
        {{ error }}
      </div>
    </form>

    <div class="login-links">
      <div class="register-link">
        <p>Нет аккаунта? <router-link to="/register" class="link">Зарегистрируйтесь здесь</router-link></p>
      </div>
      <p><a href="#" class="link">Забыли пароль?</a></p>
    </div>

    <button class="btn btn-secondary" @click="$router.push('/')">← На главную</button>
  </div>
</template>

<script>
import { useAuthStore } from '../stores/auth'

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Login',
  setup() {
    const authStore = useAuthStore()
    return { authStore }
  },
  data() {
    return {
      credentials: {
        email: '',
        password: ''
      }
    }
  },
  computed: {
    loading() {
      return this.authStore.loading
    },
    error() {
      return this.authStore.error
    }
  },
  methods: {
    handleFirstInteraction() {
      if (!this.hasInteracted) {
        this.hasInteracted = true
        this.showContent()
        clearTimeout(this.autoShowTimeout)
      }
    },
    showContent() {
      this.isContentVisible = true
      // Эмитим событие для показа хедера
      this.$emit('show-header')
    },
    async handleLogin() {
      const result = await this.authStore.login(this.credentials)

      if (result.success) {
        // Показываем уведомление об успешном входе
        this.showSuccessNotification()

        // Редиректим после небольшой задержки
        setTimeout(() => {
          this.$router.push('/profile')
        }, 1500)
      }
    },
    showSuccessNotification() {
      const notification = document.createElement('div')
      notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #2e8b57;
        color: white;
        padding: 15px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 10000;
        max-width: 300px;
        font-family: Arial, sans-serif;
      `
      notification.textContent = '✅ Вход выполнен успешно!'

      document.body.appendChild(notification)

      setTimeout(() => {
        if (notification.parentNode) {
          notification.parentNode.removeChild(notification)
        }
      }, 3000)
    }
  },
  beforeUnmount() {
    // Убираем обработчики при размонтировании
    window.removeEventListener('scroll', this.handleFirstInteraction)
    window.removeEventListener('click', this.handleFirstInteraction)
    window.removeEventListener('touchstart', this.handleFirstInteraction)
    clearTimeout(this.autoShowTimeout)
  },
  // Добавляем проверку при монтировании компонента
  mounted() {
    // Если пользователь уже авторизован, показываем уведомление
    if (this.authStore.isAuthenticated) {
      this.showAlreadyLoggedInNotification()
    }
    window.addEventListener('scroll', this.handleFirstInteraction, { passive: true, once: true })
    window.addEventListener('click', this.handleFirstInteraction, { once: true })
    window.addEventListener('touchstart', this.handleFirstInteraction, { once: true })
    this.autoShowTimeout = setTimeout(() => {
      if (!this.hasInteracted) {
        this.showContent()
      }
    }, 3000)
  },
  showAlreadyLoggedInNotification() {
    const notification = document.createElement('div')
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #ffd700;
        color: #333;
        padding: 15px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 10000;
        max-width: 300px;
        font-family: Arial, sans-serif;
      `
    notification.textContent = 'ℹ️ Вы уже авторизованы!'

    document.body.appendChild(notification)

    setTimeout(() => {
      if (notification.parentNode) {
        notification.parentNode.removeChild(notification)
      }
    }, 3000)
  }
}
</script>

<style scoped>
.login-form {
  max-width: 300px;
  margin: 2rem auto;
}

.form-group {
  margin-bottom: 1rem;
}

.form-input {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #2e8b57;
}

.form-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.btn-primary {
  width: 100%;
  background-color: #2e8b57;
  color: white;
  padding: 12px;
  font-size: 1rem;
  margin-top: 1rem;
}

.btn-primary:hover:not(:disabled) {
  background-color: #26734a;
}

.btn-primary:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.login-links {
  margin-top: 1.5rem;
  text-align: center;
}

.link {
  color: #2e8b57;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

.error-message {
  background-color: #fee;
  color: #c33;
  padding: 12px;
  border-radius: 6px;
  margin-top: 1rem;
  border-left: 4px solid #c33;
  text-align: center;
}
</style>