<template>
  <div :class="['feedback-panel-shell', { 'feedback-panel-embedded': embedded }]">
    <section v-if="showHero" class="feedback-hero">
      <p class="feedback-eyebrow">Oeffentliches Feedback</p>
      <h2>Meinungen, Hinweise und Verbesserungsvorschlaege</h2>
      <p>
        Alle Kommentare sind oeffentlich sichtbar. Pflicht ist nur der Kommentar selbst, alle weiteren Angaben sind optional.
      </p>
    </section>

    <div class="feedback-layout">
      <section class="feedback-form-panel">
        <h3>Feedback senden</h3>
        <form class="feedback-form" @submit.prevent="submitFeedback">
          <label>
            <span>Name</span>
            <input v-model="form.name" type="text" maxlength="80">
          </label>
          <label>
            <span>Alter</span>
            <input v-model="form.age" type="number" min="18" max="120">
          </label>
          <label>
            <span>Land</span>
            <select v-model="form.country">
              <option value="">{{ $t('label_country') }}</option>
              <option v-for="(code, name) in countries" :key="code" :value="name">
                {{ name }}
              </option>
            </select>
          </label>
          <label>
            <span>Geschlecht</span>
            <select v-model="form.gender">
              <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>
          </label>
          <label class="feedback-form-comment">
            <span>Kommentar *</span>
            <textarea v-model="form.comment" rows="7" required maxlength="4000"></textarea>
          </label>
          <button type="submit" :disabled="isSubmitting">
            {{ isSubmitting ? 'Wird gesendet...' : 'Feedback absenden' }}
          </button>
        </form>
        <p v-if="submitMessage" class="feedback-success">{{ submitMessage }}</p>
        <p v-if="submitError" class="feedback-error">{{ submitError }}</p>
      </section>

      <section class="feedback-list-panel">
        <div class="feedback-list-header">
          <div>
            <h3>Kommentare</h3>
            <p>{{ feedbackItems.length }} Eintraege</p>
          </div>
          <div class="feedback-admin">
            <template v-if="adminStatus.authenticated">
              <span class="feedback-admin-badge">Admin: {{ adminStatus.username }}</span>
              <button type="button" class="feedback-admin-button" @click="logoutAdmin">Logout</button>
            </template>
            <form v-else class="feedback-admin-form" @submit.prevent="loginAdmin">
              <input v-model="adminForm.username" type="text" placeholder="Admin-Name">
              <input v-model="adminForm.password" type="password" placeholder="Passwort">
              <button type="submit">Admin-Login</button>
            </form>
          </div>
        </div>

        <p v-if="adminError" class="feedback-error">{{ adminError }}</p>

        <div class="feedback-list">
          <article v-for="item in feedbackItems" :key="item.id" class="feedback-item">
            <header class="feedback-item-header">
              <div>
                <strong>{{ item.name || 'Anonym' }}</strong>
                <span v-if="formatMeta(item)" class="feedback-item-meta">{{ formatMeta(item) }}</span>
              </div>
              <div class="feedback-item-actions">
                <time :datetime="item.createdAt">{{ formatDate(item.createdAt) }}</time>
                <button
                  v-if="adminStatus.authenticated"
                  type="button"
                  class="feedback-delete"
                  @click="deleteFeedback(item.id)"
                >
                  Loeschen
                </button>
              </div>
            </header>
            <p>{{ item.comment }}</p>
          </article>

          <p v-if="feedbackItems.length === 0" class="feedback-empty">
            Noch kein Feedback vorhanden.
          </p>
        </div>
      </section>
    </div>
  </div>
</template>

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

const props = defineProps({
  showHero: {
    type: Boolean,
    default: true
  },
  embedded: {
    type: Boolean,
    default: false
  }
});

const { locale } = useI18n();

const feedbackItems = ref([]);
const isSubmitting = ref(false);
const submitMessage = ref('');
const submitError = ref('');
const adminError = ref('');

const form = ref({
  name: '',
  age: '',
  country: '',
  gender: '',
  comment: ''
});

const countriesRaw = ref({});

const countries = computed(() => {
  const translated = {};
  const translations = countryTranslations[locale.value] || countryTranslations.en || {};

  for (const [englishName, code] of Object.entries(countriesRaw.value)) {
    translated[translations[englishName] || englishName] = code;
  }

  const sorted = {};
  Object.keys(translated)
    .sort((a, b) => a.localeCompare(b, locale.value))
    .forEach((key) => {
      sorted[key] = translated[key];
    });

  return sorted;
});

const adminForm = ref({
  username: '',
  password: ''
});

const adminStatus = ref({
  authenticated: false,
  username: null
});

async function loadFeedback() {
  const response = await axios.get('/api/feedback', { withCredentials: true });
  feedbackItems.value = response.data.items || [];
  adminStatus.value.authenticated = !!response.data.admin;
}

async function loadAdminStatus() {
  const response = await axios.get('/api/feedback/admin-status', { withCredentials: true });
  adminStatus.value = response.data;
}

async function submitFeedback() {
  isSubmitting.value = true;
  submitMessage.value = '';
  submitError.value = '';

  try {
    await axios.post('/api/feedback', form.value, { withCredentials: true });
    submitMessage.value = 'Danke. Dein Feedback wurde gespeichert.';
    const profile = readProfileCookie();
    form.value = {
      name: profile?.nickname || '',
      age: Number.isFinite(profile?.age) ? profile.age : '',
      country: profile?.country || '',
      gender: profile?.gender || '',
      comment: ''
    };
    await loadFeedback();
  } catch (error) {
    submitError.value = error.response?.data?.error || 'Feedback konnte nicht gespeichert werden.';
  } finally {
    isSubmitting.value = false;
  }
}

async function loginAdmin() {
  adminError.value = '';
  try {
    const response = await axios.post('/api/feedback/admin-login', adminForm.value, { withCredentials: true });
    adminStatus.value = { authenticated: true, username: response.data.username };
    adminForm.value.password = '';
  } catch (error) {
    adminError.value = error.response?.data?.error || 'Admin-Login fehlgeschlagen.';
  }
}

async function logoutAdmin() {
  await axios.post('/api/feedback/admin-logout', {}, { withCredentials: true });
  adminStatus.value = { authenticated: false, username: null };
}

async function deleteFeedback(id) {
  await axios.delete(`/api/feedback/${id}`, { withCredentials: true });
  await loadFeedback();
}

function formatDate(value) {
  return new Date(value).toLocaleString('de-DE');
}

function formatMeta(item) {
  return [item.country, item.age, item.gender].filter(Boolean).join(' · ');
}

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);
  }

  const profile = readProfileCookie();
  if (profile) {
    form.value.name = profile.nickname || '';
    form.value.age = Number.isFinite(profile.age) ? profile.age : '';
    form.value.country = profile.country || '';
    form.value.gender = profile.gender || '';
  }

  await Promise.all([loadFeedback(), loadAdminStatus()]);
});
</script>

<style scoped>
.feedback-panel-shell {
  flex: 1;
  min-height: 0;
  overflow: auto;
  padding: 20px;
}

.feedback-panel-embedded {
  padding: 0;
}

.feedback-hero {
  max-width: 960px;
  margin: 0 auto 20px;
  padding: 24px;
  border: 1px solid #d7dfd9;
  border-radius: 18px;
  background:
    radial-gradient(circle at top left, rgba(61, 134, 84, 0.18), transparent 28%),
    linear-gradient(180deg, rgba(255, 255, 255, 0.95) 0%, rgba(243, 247, 244, 0.92) 100%);
}

.feedback-eyebrow {
  margin: 0 0 6px;
  font-size: 11px;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: #617067;
}

.feedback-hero h2 {
  margin: 0 0 8px;
  font-size: 28px;
  color: #18201b;
}

.feedback-hero p {
  margin: 0;
  color: #4e5b53;
}

.feedback-layout {
  max-width: 960px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 340px minmax(0, 1fr);
  gap: 20px;
}

.feedback-form-panel,
.feedback-list-panel {
  border: 1px solid #d7dfd9;
  border-radius: 18px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 18px 40px rgba(31, 50, 39, 0.06);
}

.feedback-form-panel {
  padding: 20px;
}

.feedback-list-panel {
  padding: 18px;
}

.feedback-form-panel h3,
.feedback-list-panel h3 {
  margin: 0 0 14px;
  font-size: 18px;
}

.feedback-form {
  display: grid;
  gap: 12px;
}

.feedback-form label {
  display: grid;
  gap: 6px;
}

.feedback-form span {
  font-size: 12px;
  font-weight: 600;
  color: #536159;
}

.feedback-form input,
.feedback-form textarea,
.feedback-admin-form input {
  width: 100%;
  border: 1px solid #d3ddd5;
  border-radius: 10px;
  background: #fbfdfb;
  padding: 10px 12px;
  color: #18201b;
}

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

.feedback-list-header {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 14px;
}

.feedback-list-header p {
  margin: 4px 0 0;
  color: #66746b;
  font-size: 12px;
}

.feedback-admin {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.feedback-admin-badge {
  display: inline-flex;
  align-items: center;
  min-height: 28px;
  padding: 0 10px;
  border-radius: 999px;
  background: #e7f1ea;
  color: #245c3a;
  font-size: 12px;
  font-weight: 600;
}

.feedback-admin-form {
  display: flex;
  gap: 8px;
}

.feedback-admin-form input {
  width: 140px;
  height: 40px;
}

.feedback-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.feedback-item {
  padding: 14px;
  border: 1px solid #dce4de;
  border-radius: 12px;
  background: #f9fbf9;
}

.feedback-item-header {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 8px;
}

.feedback-item-header strong {
  display: block;
  color: #18201b;
}

.feedback-item-meta,
.feedback-item-actions time {
  font-size: 12px;
  color: #647168;
}

.feedback-item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.feedback-delete {
  height: 30px;
  padding: 0 10px;
  border-color: #b74848;
  background: linear-gradient(180deg, #cd6161 0%, #a24040 100%);
}

.feedback-item p,
.feedback-empty,
.feedback-success,
.feedback-error {
  white-space: pre-wrap;
}

.feedback-success {
  margin-top: 12px;
  color: #245c3a;
}

.feedback-error {
  margin-top: 12px;
  color: #a24040;
}

@media (max-width: 860px) {
  .feedback-layout {
    grid-template-columns: 1fr;
  }

  .feedback-admin-form {
    flex-direction: column;
  }

  .feedback-admin-form input {
    width: 100%;
  }
}
</style>
