<template>
  <main class="flex items-center justify-center page-container">
    <div class="card login-card">
      <div class="card-header">
        <h3>mitlist</h3>
      </div>
      <div class="card-body">
        <form @submit.prevent="onSubmit" class="form-layout">
          <div class="form-group mb-2">
            <label for="email" class="form-label">{{ t('loginPage.emailLabel') }}</label>
            <input type="email" id="email" v-model="email" class="form-input" required autocomplete="email" />
            <p v-if="formErrors.email" class="form-error-text">{{ formErrors.email }}</p>
          </div>

          <div class="form-group mb-3">
            <label for="password" class="form-label">{{ t('loginPage.passwordLabel') }}</label>
            <div class="input-with-icon-append">
              <input :type="isPwdVisible ? 'text' : 'password'" id="password" v-model="password" class="form-input"
                required autocomplete="current-password" />
              <button type="button" @click="isPwdVisible = !isPwdVisible" class="icon-append-btn"
                :aria-label="t('loginPage.togglePasswordVisibilityLabel')">
                <svg class="icon icon-sm">
                  <use :xlink:href="isPwdVisible ? '#icon-settings' : '#icon-settings'"></use>
                </svg> <!-- Placeholder for visibility icons -->
              </button>
            </div>
            <p v-if="formErrors.password" class="form-error-text">{{ formErrors.password }}</p>
          </div>

          <p v-if="formErrors.general" class="alert alert-error form-error-text">{{ formErrors.general }}</p>

          <button type="submit" class="btn btn-primary w-full mt-2" :disabled="loading">
            <span v-if="loading" class="spinner-dots-sm" role="status"><span /><span /><span /></span>
            {{ t('loginPage.loginButton') }}
          </button>

          <div class="text-center mt-2">
            <router-link to="/auth/signup" class="link-styled">{{ t('loginPage.signupLink') }}</router-link>
          </div>

          <SocialLoginButtons />
        </form>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
import { useAuthStore } from '@/stores/auth'; // Assuming path
import { useNotificationStore } from '@/stores/notifications';
import SocialLoginButtons from '@/components/SocialLoginButtons.vue';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const notificationStore = useNotificationStore();
const { t, locale, messages } = useI18n();

// Debug output
console.log('=== i18n Debug Info ===');
console.log('Current locale:', locale.value);
console.log('Available messages:', messages.value);
console.log('English messages:', messages.value.en);
console.log('LoginPage messages:', messages.value.en?.loginPage);
console.log('Test translation:', t('loginPage.emailLabel'));
console.log('Test fallback:', t('message.hello'));

const email = ref('');
const password = ref('');
const isPwdVisible = ref(false);
const loading = ref(false);
const formErrors = ref<{ email?: string; password?: string; general?: string }>({});

const isValidEmail = (val: string): boolean => {
  const emailPattern = /^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,8}[a-zA-Z]{2,63}$/;
  return emailPattern.test(val);
};

const validateForm = (): boolean => {
  formErrors.value = {};
  if (!email.value.trim()) {
    formErrors.value.email = t('loginPage.errors.emailRequired');
  } else if (!isValidEmail(email.value)) {
    formErrors.value.email = t('loginPage.errors.emailInvalid');
  }
  if (!password.value) {
    formErrors.value.password = t('loginPage.errors.passwordRequired');
  }
  return Object.keys(formErrors.value).length === 0;
};

const onSubmit = async () => {
  if (!validateForm()) {
    return;
  }
  loading.value = true;
  formErrors.value.general = undefined; // Clear previous general errors
  try {
    await authStore.login(email.value, password.value);
    notificationStore.addNotification({ message: t('loginPage.notifications.loginSuccess'), type: 'success' });
    const redirectPath = (route.query.redirect as string) || '/';
    router.push(redirectPath);
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : t('loginPage.errors.loginFailed');
    formErrors.value.general = message;
    console.error(message, error);
    notificationStore.addNotification({ message, type: 'error' });
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  /* dvh for dynamic viewport height */
  min-height: 100dvh;
  padding: 1rem;
}

.login-card {
  width: 100%;
  max-width: 400px;
}

/* form-layout, w-full, mt-2, text-center styles were removed as utility classes from Valerie UI are used directly or are available. */

.link-styled {
  color: var(--primary);
  text-decoration: none;
  border-bottom: 2px solid transparent;
  transition: border-color var(--transition-speed) var(--transition-ease-out);
}

.link-styled:hover,
.link-styled:focus {
  border-bottom-color: var(--primary);
}

.form-error-text {
  color: var(--danger);
  font-size: 0.85rem;
  margin-top: 0.25rem;
}

.alert.form-error-text {
  /* For general error message */
  padding: 0.75rem 1rem;
  margin-bottom: 1rem;
}

.input-with-icon-append {
  position: relative;
  display: flex;
}

.input-with-icon-append .form-input {
  padding-right: 3rem;
  /* Space for the button */
}

.icon-append-btn {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 3rem;
  /* Width of the button */
  background: transparent;
  border: none;
  border-left: var(--border);
  /* Separator line */
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--dark);
  opacity: 0.7;
}

.icon-append-btn:hover,
.icon-append-btn:focus {
  opacity: 1;
  background-color: rgba(0, 0, 0, 0.03);
}

.icon-append-btn .icon {
  margin: 0;
}

/* Remove default icon margin */
</style>