<template>
  <div class="landing-login">
    <section class="landing-login-intro">
      <p class="landing-login-eyebrow">SingleChat</p>
      <h2>Direkt in den Chat</h2>
      <p class="landing-login-copy">
        Kompakt, schnell und ohne Umwege. Erstelle dein Profil und starte sofort eine Unterhaltung.
      </p>
      <div class="landing-login-features">
        <span>Weltweiter Chat</span>
        <span>Bildaustausch</span>
        <span>Kompakte Bedienung</span>
      </div>
      <nav class="landing-login-topic-links" aria-label="SingleChat Themen">
        <router-link to="/kostenloser-single-chat">Kostenloser Single Chat</router-link>
        <router-link to="/single-chat-ohne-anmeldung">Ohne lange Anmeldung</router-link>
        <router-link to="/single-treff-chat">Single Treff Chat</router-link>
      </nav>
      <div class="welcome-message" v-html="$t('welcome')"></div>
    </section>

    <section class="landing-login-card">
      <div class="landing-login-card-header">
        <h3>Profil starten</h3>
        <p>Wenige Angaben genügen für den Einstieg.</p>
      </div>

      <form class="landing-login-fields" @submit.prevent="handleSubmit">
        <div class="landing-form-row">
          <label>{{ $t('label_nick') }}</label>
          <input v-model="nickname" type="text" required minlength="3" />
        </div>
        
        <div class="landing-form-row">
          <label>{{ $t('label_gender') }}</label>
          <select v-model="gender" required>
            <option value="">{{ $t('label_gender') }}</option>
            <option value="F">{{ $t('gender_female') }}</option>
            <option value="M">{{ $t('gender_male') }}</option>
            <option value="P">{{ $t('gender_pair') }}</option>
            <option value="TF">{{ $t('gender_trans_mf') }}</option>
            <option value="TM">{{ $t('gender_trans_fm') }}</option>
          </select>
        </div>
        
        <div class="landing-form-row">
          <label>{{ $t('label_age') }}</label>
          <input v-model.number="age" type="number" required min="18" max="120" />
        </div>
        
        <div class="landing-form-row">
          <label>{{ $t('label_country') }}</label>
          <select v-model="country" required>
            <option value="">{{ $t('label_country') }}</option>
            <option v-for="(code, name) in countries" :key="code" :value="name">
              {{ name }}
            </option>
          </select>
        </div>
        
        <div class="landing-form-row landing-form-row-submit">
          <button type="submit">{{ $t('button_start_chat') }}</button>
        </div>
      </form>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import axios from 'axios';
import { useChatStore } from '../stores/chat';
import { useI18n } from 'vue-i18n';
import countryTranslations from '../i18n/countries.json';
import { readProfileCookie, writeProfileCookie } from '../utils/profileCookie';

const { locale } = useI18n();
const chatStore = useChatStore();
const nickname = ref('');
const gender = ref('');
const age = ref(18);
const country = ref('');
const countriesRaw = ref({});

// Übersetzte Länderliste (sortiert)
const countries = computed(() => {
  const translated = {};
  const translations = countryTranslations[locale.value] || countryTranslations['en'] || {};
  
  for (const [englishName, code] of Object.entries(countriesRaw.value)) {
    // Verwende Übersetzung falls vorhanden, sonst englischen Namen
    translated[translations[englishName] || englishName] = code;
  }
  
  // Sortiere alphabetisch nach übersetztem Namen
  const sorted = {};
  Object.keys(translated).sort((a, b) => a.localeCompare(b, locale.value)).forEach(key => {
    sorted[key] = translated[key];
  });
  
  return sorted;
});

onMounted(async () => {
  try {
    const response = await axios.get('/api/countries');
    countriesRaw.value = response.data;
  } catch (error) {
    console.error('Fehler beim Laden der Länderliste:', error);
  }

  restoreProfileFromCookie();
});

watch([nickname, gender, age, country], () => {
  persistProfileToCookie();
});

function restoreProfileFromCookie() {
  const profile = readProfileCookie();
  if (!profile) return;

  if (typeof profile.nickname === 'string') {
    nickname.value = profile.nickname;
  }
  if (typeof profile.gender === 'string') {
    gender.value = profile.gender;
  }
  if (Number.isFinite(profile.age)) {
    age.value = profile.age;
  }
  if (typeof profile.country === 'string') {
    country.value = profile.country;
  }
}

function persistProfileToCookie() {
  writeProfileCookie({
    nickname: nickname.value.trim(),
    gender: gender.value,
    age: Number(age.value) || 18,
    country: country.value
  });
}

function handleSubmit() {
  if (!nickname.value || nickname.value.trim().length < 3) {
    alert('Bitte gib einen gültigen Nicknamen ein (mindestens 3 Zeichen)');
    return;
  }
  
  if (!gender.value) {
    alert('Bitte wähle ein Geschlecht aus');
    return;
  }
  
  if (!age.value || age.value < 18) {
    alert('Du musst mindestens 18 Jahre alt sein');
    return;
  }
  
  if (!country.value) {
    alert('Bitte wähle ein Land aus');
    return;
  }
  
  // Finde den englischen Namen für das ausgewählte Land
  const translations = countryTranslations[locale.value] || countryTranslations['en'] || {};
  let englishCountryName = country.value;
  
  // Suche den englischen Namen, falls ein übersetzter Name verwendet wurde
  for (const [englishName, translatedName] of Object.entries(translations)) {
    if (translatedName === country.value) {
      englishCountryName = englishName;
      break;
    }
  }
  
  chatStore.login(nickname.value.trim(), gender.value, age.value, englishCountryName);
  persistProfileToCookie();
}
</script>

<style scoped>
.landing-login {
  width: 80%;
  max-width: 1400px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  justify-content: center;
  gap: 24px;
  align-items: stretch;
  height: min(80%, 720px);
  max-height: 80%;
}

.landing-login-intro {
  padding: 32px;
  border-radius: 20px;
  border: 1px solid #cfe0d3;
  background:
    radial-gradient(circle at top left, rgba(61, 134, 84, 0.28), transparent 32%),
    linear-gradient(180deg, rgba(232, 243, 235, 0.98) 0%, rgba(244, 248, 245, 0.94) 100%);
  box-shadow: 0 24px 60px rgba(31, 50, 39, 0.10);
  min-height: 100%;
  overflow: auto;
}

.landing-login-eyebrow {
  margin: 0 0 8px;
  font-size: 11px;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  color: #496254;
}

.landing-login-intro h2 {
  margin: 0 0 10px;
  font-size: 30px;
  line-height: 1.05;
  color: #18201b;
}

.landing-login-copy {
  margin: 0 0 16px;
  color: #4f5d54;
  line-height: 1.55;
}

.landing-login-features {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 18px;
}

.landing-login-features span {
  display: inline-flex;
  align-items: center;
  min-height: 30px;
  padding: 0 12px;
  border-radius: 999px;
  border: 1px solid #bfd5c4;
  background: #e2efe5;
  color: #245c3a;
  font-size: 12px;
  font-weight: 600;
}

.landing-login-topic-links {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 0 0 18px;
}

.landing-login-topic-links a {
  color: #245c3a;
  font-size: 13px;
  font-weight: 700;
  text-decoration: none;
}

.landing-login-topic-links a:hover {
  text-decoration: underline;
}

.landing-login-card {
  padding: 24px;
  border-radius: 20px;
  border: 1px solid #d4ddd6;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.99) 0%, rgba(249, 251, 249, 0.97) 100%);
  box-shadow: 0 24px 60px rgba(31, 50, 39, 0.10);
  min-height: 100%;
  overflow: auto;
}

.landing-login-card-header {
  margin-bottom: 18px;
}

.landing-login-card-header h3 {
  margin: 0 0 4px;
  font-size: 20px;
  color: #18201b;
}

.landing-login-card-header p {
  margin: 0;
  color: #637067;
}

.landing-login-fields {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.landing-form-row {
  display: grid;
  gap: 6px;
}

.landing-form-row label {
  min-width: 0;
  color: #536159;
  font-size: 12px;
  font-weight: 600;
}

.landing-form-row input,
.landing-form-row select {
  width: 100%;
  height: 42px;
  padding: 0 12px;
  border: 1px solid #d3ddd5;
  border-radius: 10px;
  background: #fbfdfb;
  color: #18201b;
}

.landing-form-row input:focus,
.landing-form-row select:focus {
  outline: none;
  border-color: #8bb497;
  box-shadow: 0 0 0 3px rgba(61, 134, 84, 0.12);
}

.landing-form-row button {
  height: 42px;
  padding: 0 16px;
  border: 1px solid #295f3d;
  border-radius: 10px;
  background: linear-gradient(180deg, #4a8d61 0%, #2c6240 100%);
  color: #fff;
  font-weight: 600;
}

.landing-form-row-submit {
  margin-top: 4px;
}

.welcome-message {
  padding: 18px;
  border: 1px solid #d7dfd9;
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.72);
}

@media (max-width: 820px) {
  .landing-login {
    width: 100%;
    grid-template-columns: 1fr;
    min-height: auto;
    height: auto;
    max-height: none;
  }

  .landing-login-intro,
  .landing-login-card {
    padding: 20px;
    min-height: auto;
    overflow: visible;
  }

  .landing-login-intro h2 {
    font-size: 24px;
  }
}
</style>
