<template>
  <div class="lock-screen">
    <!-- macOS Style Background -->
    <div class="background-image">
      <div class="blur-overlay"></div>
      <div class="gradient-overlay"></div>
        </div>

    <!-- Lock Screen Content -->
    <div class="lock-content">
      <!-- Time and Date -->
      <div class="time-section">
        <div class="current-time">{{ currentTime }}</div>
        <div class="current-date">{{ currentDate }}</div>
      </div>

        <!-- User Avatar and Login Form -->
        <div class="login-section">
          <!-- User Avatar -->
          <div class="user-avatar">
            <div class="avatar-circle">
              <div class="avatar-icon">👤</div>
          </div>
            <div class="user-name-field">
              <input
                v-model="form.username"
                type="text"
                :placeholder="$t('auth.login.usernamePlaceholder')"
                class="username-input"
                :class="{ 'error': errors.username }"
                required
              />
              <div v-if="errors.username" class="error-message">{{ errors.username }}</div>
            </div>
            </div>

          <!-- Login Form -->
          <div class="login-form show">
            <form @submit.prevent="handleLogin" class="form">
            <!-- Password Field -->
              <div class="password-field">
              <input
                  ref="passwordInput"
                v-model="form.password"
                type="password"
                :placeholder="$t('auth.login.passwordPlaceholder')"
                  class="password-input"
                  :class="{ 'error': errors.password, 'shake': shakeAnimation }"
                required
              />
                <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
            </div>

              <!-- Login Button -->
              <button 
                type="submit" 
                class="login-button"
                :disabled="isLoading || !form.password"
              >
                <span v-if="isLoading" class="loading-spinner"></span>
                <span v-else>→</span>
              </button>
            </form>

            <!-- Options -->
            <div class="login-options">
              <button class="option-link" @click="handleForgotPassword">
                {{ $t('auth.login.forgotPassword') }}
              </button>
              <button class="option-link" @click="goToRegister">
                {{ $t('auth.login.signUp') }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Bottom Actions -->
      <div class="bottom-actions">
        <button class="action-button" @click="goHome">
          <div class="action-icon">🏠</div>
          <div class="action-text">{{ $t('lockScreen.home') }}</div>
        </button>
      </div>
    </div>

    <!-- Status Bar -->
    <div class="status-bar">
      <div class="status-left">
        <!-- Empty for now -->
      </div>
      <div class="status-center">
        <!-- Empty for now -->
      </div>
      <div class="status-right">
        <!-- Language Toggle -->
        <div class="language-switcher-wrapper" ref="languageSwitcherWrapper">
          <button @click="toggleLanguageMenu" class="language-switcher">
            {{ currentLanguageDisplay }}
          </button>
          <div v-if="isLanguageMenuOpen" class="language-menu">
            <ul>
              <li v-for="lang in availableLanguages" :key="lang.key" @click="selectLanguage(lang.key as 'en' | 'zh')">
                <span class="checkmark" :style="{ visibility: locale === lang.key ? 'visible' : 'hidden' }">✓</span>
                <span>{{ lang.label }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';

const router = useRouter();
const { t, locale, setLocale } = useI18n();

// Time and date
const currentTime = ref('');
const currentDate = ref('');

// User info
const userName = ref('User');

// Current locale
const currentLocale = computed(() => locale.value);

// --- Language Switcher Logic ---
const isLanguageMenuOpen = ref(false);
const languageSwitcherWrapper = ref<HTMLElement | null>(null);
const availableLanguages = computed(() => [
  { key: 'en', label: 'English', display: 'EN' },
  { key: 'zh', label: '繁體中文', display: '注' },
]);

const currentLanguageDisplay = computed(() => {
  const current = availableLanguages.value.find(lang => lang.key === locale.value);
  return current?.display || '注';
});

// Form data
const form = reactive({
  username: '',
  password: ''
});

// Form validation
const errors = reactive({
  username: '',
  password: ''
});

// UI state
const isLoading = ref(false);
const shakeAnimation = ref(false);

// Refs
const passwordInput = ref<HTMLInputElement>();

// Update time
const updateTime = () => {
  const now = new Date();
  const currentLocale = locale.value;
  
  // Set locale for time and date formatting
  const localeCode = currentLocale === 'zh' ? 'zh-TW' : 'en-US';
  
  currentTime.value = now.toLocaleTimeString(localeCode, {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  });
  currentDate.value = now.toLocaleDateString(localeCode, {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// Validation functions
const validateUsername = () => {
  errors.username = '';

  if (!form.username) {
    errors.username = t('auth.common.required');
    return false;
  }
  if (form.username.length < 3) {
    errors.username = t('auth.common.usernameTooShort');
    return false;
  }

  return true;
};

const validatePassword = () => {
  errors.password = '';

  if (!form.password) {
    errors.password = t('auth.common.required');
    return false;
  }
  if (form.password.length < 6) {
    errors.password = t('auth.common.passwordTooShort');
    return false;
  }

  return true;
};

// Event handlers

const handleLogin = async () => {
  if (!validateUsername() || !validatePassword()) {
    shakeAnimation.value = true;
    setTimeout(() => {
      shakeAnimation.value = false;
    }, 500);
    return;
  }

  isLoading.value = true;
  
  try {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // Success - redirect to home
    router.push('/');
  } catch (error) {
    console.error('Login error:', error);
    shakeAnimation.value = true;
    setTimeout(() => {
      shakeAnimation.value = false;
    }, 500);
  } finally {
    isLoading.value = false;
  }
};

const handleForgotPassword = () => {
  alert('Forgot password functionality coming soon!');
};

const goToRegister = () => {
  router.push('/register');
};

const goHome = () => {
  router.push('/');
};


function toggleLanguageMenu() {
  isLanguageMenuOpen.value = !isLanguageMenuOpen.value;
}

function selectLanguage(lang: 'en' | 'zh') {
  setLocale(lang);
  isLanguageMenuOpen.value = false;
}

const handleClickOutside = (event: MouseEvent) => {
  if (languageSwitcherWrapper.value && !languageSwitcherWrapper.value.contains(event.target as Node)) {
    isLanguageMenuOpen.value = false;
  }
};

// Lifecycle
let timeInterval: number;

onMounted(() => {
  updateTime();
  timeInterval = setInterval(updateTime, 1000);
});

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval);
  }
  document.removeEventListener('click', handleClickOutside);
});

// Watch for language menu state
watch(isLanguageMenuOpen, (isOpen) => {
  if (isOpen) {
    document.addEventListener('click', handleClickOutside);
  } else {
    document.removeEventListener('click', handleClickOutside);
  }
});

// Watch for language changes and update time format
watch(locale, () => {
  updateTime();
});
</script>

<style scoped>
.lock-screen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, 
    #667eea 0%, 
    #764ba2 25%, 
    #f093fb 50%, 
    #f5576c 75%, 
    #4facfe 100%);
  background-size: 400% 400%;
  animation: gradient-shift 15s ease infinite;
  z-index: 0;
}

@keyframes gradient-shift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.blur-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
}

.gradient-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    180deg,
    rgba(0, 0, 0, 0.1) 0%,
    rgba(0, 0, 0, 0.3) 50%,
    rgba(0, 0, 0, 0.6) 100%
  );
}

.lock-content {
  position: relative;
  z-index: 1;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 60px 40px 40px;
  color: white;
  min-height: 100vh;
  box-sizing: border-box;
}

.time-section {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.current-time {
  font-size: 6rem;
  font-weight: 200;
  letter-spacing: -0.02em;
  margin-bottom: 8px;
  text-shadow: 0 2px 20px rgba(0, 0, 0, 0.3);
  animation: time-glow 2s ease-in-out infinite alternate;
  line-height: 1;
  white-space: nowrap;
}

@keyframes time-glow {
  from { text-shadow: 0 2px 20px rgba(0, 0, 0, 0.3); }
  to { text-shadow: 0 2px 30px rgba(255, 255, 255, 0.1); }
}

.current-date {
  font-size: 1.5rem;
  font-weight: 300;
  opacity: 0.9;
  text-shadow: 0 1px 10px rgba(0, 0, 0, 0.3);
  line-height: 1.2;
  white-space: nowrap;
}

.login-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  position: relative;
  width: 100%;
  justify-content: center;
}

.user-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}


.avatar-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(20px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
}

.avatar-circle:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
}

.avatar-icon {
  font-size: 3rem;
  filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.3));
}

.user-name-field {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.username-input {
  width: 300px;
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50px;
  color: white;
  font-size: 1.1rem;
  font-weight: 300;
  text-align: center;
  outline: none;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.username-input::placeholder {
  color: rgba(255, 255, 255, 0.7);
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.username-input:focus {
  background: rgba(255, 255, 255, 0.25);
  border-color: rgba(255, 255, 255, 0.6);
  box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.1);
}

.username-input.error {
  border-color: #ff6b6b;
  background: rgba(255, 107, 107, 0.2);
  animation: shake 0.5s ease-in-out;
}

.login-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.5s cubic-bezier(0.16, 1, 0.3, 1);
  pointer-events: none;
}

.login-form.show {
  opacity: 1;
  transform: translateY(0);
  pointer-events: all;
}

.form {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: center;
  position: relative;
}

.password-field {
  position: relative;
}

.password-input {
  width: 300px;
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50px;
  color: white;
  font-size: 1.1rem;
  font-weight: 300;
  text-align: center;
  transition: all 0.3s ease;
  outline: none;
  display: block;
  margin: 0 auto;
}

.password-input::placeholder {
  color: rgba(255, 255, 255, 0.7);
}

.password-input:focus {
  background: rgba(255, 255, 255, 0.25);
  border-color: rgba(255, 255, 255, 0.6);
  box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.1);
}

.password-input.error {
  border-color: #ff6b6b;
  background: rgba(255, 107, 107, 0.2);
  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-10px); }
  75% { transform: translateX(10px); }
}

.password-input.shake {
  animation: shake 0.5s ease-in-out;
}

.error-message {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 12px;
  font-size: 0.9rem;
  color: #ff6b6b;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
  white-space: nowrap;
  z-index: 10;
}

.login-button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(20px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: white;
  font-size: 1.2rem;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  right: -70px;
  top: 50%;
  transform: translateY(-50%);
}

.login-button:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.6);
  transform: translateY(-50%) scale(1.1);
}

.login-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: translateY(-50%);
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.login-options {
  display: flex;
  gap: 32px;
  margin-top: 16px;
}

.option-link {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.9rem;
  cursor: pointer;
  text-decoration: underline;
  transition: all 0.3s ease;
}

.option-link:hover {
  color: white;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}


.bottom-actions {
  display: flex;
  justify-content: center;
  position: relative;
  width: 100%;
  margin-top: 40px;
  align-items: center;
}

.action-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.8);
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 12px;
  border-radius: 12px;
}

.action-button:hover {
  color: white;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  transform: translateY(-2px);
}

.action-icon {
  font-size: 1.5rem;
  filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.3));
}

.action-text {
  font-size: 0.8rem;
  font-weight: 300;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}

.status-bar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 22px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background: var(--taskbar-background);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  color: var(--taskbar-item-text-color);
  font-size: 12px;
  font-weight: 500;
  z-index: 2;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.status-left,
.status-center,
.status-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.language-switcher-wrapper {
  position: relative;
}

.language-switcher {
  background: none;
  border: none;
  color: var(--taskbar-item-text-color);
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  padding: 0 4px;
  width: 24px;
  height: 22px;
  text-align: center;
  line-height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.language-menu {
  position: absolute;
  top: calc(100% + 4px);
  right: 0;
  width: 160px;
  background-color: var(--start-menu-background);
  border: 1px solid var(--start-menu-border-color);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  padding: 4px;
  z-index: 10001;
}

.language-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.language-menu li {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.15s ease-in-out;
}

.language-menu li:hover {
  background-color: var(--taskbar-item-background-hover);
}

.checkmark {
  width: 16px;
  text-align: center;
  margin-right: 4px;
}

/* Responsive Design */
@media (max-width: 768px) {
  .lock-content {
    padding: 40px 20px 20px;
  }
  
  .current-time {
    font-size: 4rem;
  }
  
  .current-date {
    font-size: 1.2rem;
  }
  
  .avatar-circle {
    width: 100px;
    height: 100px;
  }
  
  .avatar-icon {
    font-size: 2.5rem;
  }
  
  .password-input {
    width: 250px;
    padding: 14px 20px;
    font-size: 1rem;
  }
  
  .username-input {
    width: 250px;
    padding: 14px 20px;
    font-size: 1rem;
  }
  
  .form {
    flex-direction: column;
    gap: 16px;
    align-items: center;
  }
  
  .password-field {
    position: relative;
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 12px;
  }
  
  .login-button {
    position: static;
    transform: none;
    right: auto;
    top: auto;
    margin: 0;
  }
  
  .login-options {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .bottom-actions {
    gap: 30px;
  }
  
  .status-bar {
    padding: 8px 16px;
    font-size: 0.8rem;
  }
}

/* Extra small screens */
@media (max-width: 480px) {
  .lock-content {
    padding: 20px 16px 16px;
  }
  
  .current-time {
    font-size: 3rem;
  }
  
  .current-date {
    font-size: 1rem;
  }
  
  .avatar-circle {
    width: 80px;
    height: 80px;
  }
  
  .avatar-icon {
    font-size: 2rem;
  }
  
  .username-input,
  .password-input {
    width: 200px;
    padding: 12px 16px;
    font-size: 0.9rem;
  }
  
  .form {
    gap: 12px;
  }
  
  .password-field {
    flex-direction: row;
    gap: 8px;
    justify-content: center;
  }
  
  .login-button {
    width: 40px;
    height: 40px;
    font-size: 1rem;
    margin: 0;
  }
  
  .login-options {
    gap: 12px;
  }
  
  .option-link {
    font-size: 0.8rem;
  }
}

/* Dark mode adjustments */
@media (prefers-color-scheme: dark) {
  .background-image {
    background: linear-gradient(135deg, 
      #1a1a2e 0%, 
      #16213e 25%, 
      #0f3460 50%, 
      #533483 75%, 
      #e94560 100%);
  }
}
</style>
