<template>
  <div>
    <div v-if="worships.length" class="mg-stack">
      <article
        v-for="worship in worships"
        :key="worship.id"
        class="mg-card"
      >
        <div class="worship-card">
          <aside
            class="worship-card__left"
            :style="worship.eventPlace?.backgroundColor ? `background-color:${worship.eventPlace.backgroundColor}` : ''"
          >
            <div class="worship-card__date">{{ formatDate(worship.date) }}</div>
            <div v-if="worship.dayName" class="worship-card__day">{{ worship.dayName }}</div>
            <div v-if="worship.eventPlace?.name" class="worship-card__place">{{ worship.eventPlace.name }}</div>
          </aside>

          <div class="worship-card__right">
            <h3 class="mg-title">
              <span :class="worship.highlightTime ? 'highlight-time' : ''">{{ formatTime(worship.time) }}</span>
              <span aria-hidden="true"> – </span>
              {{
                worship.title
                  ? worship.title
                  : (worship.eventPlace && worship.eventPlace.name
                      ? `Gottesdienst in ${worship.eventPlace.name}`
                      : 'Gottesdienst')
              }}
            </h3>

            <p v-if="worship.neighborInvitation" class="neighborhood-invitation mg-accent-left">
              Einladung zum Gottesdienst im Nachbarschaftsraum
            </p>

            <div class="mg-stack stack-tight">
              <p v-if="worship.organizer" class="mg-text"><strong>Gestaltung:</strong> {{ worship.organizer }}</p>
              <p v-if="worship.collection" class="mg-text"><strong>Kollekte:</strong> {{ worship.collection }}</p>
              <p v-if="worship.address" class="mg-text"><strong>Adresse:</strong> {{ worship.address }}</p>
              <p v-if="!worship.address && worship.eventPlace && worship.eventPlace.id" class="mg-text">
                <strong>Adresse:</strong> {{ worship.eventPlace.name }}, {{ worship.eventPlace.street }}, {{ worship.eventPlace.city }}
              </p>

              <p v-if="worship.sacristanService" class="internal-information mg-text">
                <strong>Küsterdienst:</strong> {{ worship.sacristanService }}
              </p>
              <p v-if="worship.organPlaying" class="internal-information mg-text">
                <strong>Orgelspiel:</strong> {{ worship.organPlaying }}
              </p>

              <p v-if="worship.selfInformation" class="selfinformation mg-text">
                Bitte informieren Sie sich auch auf den
                <a
                  v-if="worship.eventPlace && worship.eventPlace.website"
                  :href="worship.eventPlace.website"
                  target="_blank"
                  rel="noopener noreferrer"
                >Internetseiten dieser Gemeinde</a>
                <span v-else>Internetseiten dieser Gemeinde</span>.
              </p>
            </div>
          </div>
        </div>
      </article>
    </div>
    <p v-else>Keine Gottesdienste verfügbar.</p>
  </div>
</template>

<script>
import axios from '@/axios';
import { formatTime, formatDate } from '@/utils/strings';

export default {
    name: 'WorshipRender',
    props: {
        config: {
            type: Object,
            required: true
        },
    },
    data() {
        return {
            worships: []
        };
    },
    async created() {
        await this.fetchWorships();
    },
    methods: {
        formatTime,
        formatDate,
        async fetchWorships() {
            try {
                const params = { ...(this.config || {}) };
                const currentPath = String(this.$route?.path || '').toLowerCase();
                const isNeighborhoodPage = currentPath.includes('/worship/neighborhood') || currentPath.includes('/worship/neighbor');
                const isLegacyNeighborhoodConfig = (() => {
                  if (!params.location) return false;
                  try {
                    const list = Array.isArray(params.location) ? params.location : JSON.parse(params.location);
                    if (!Array.isArray(list)) return false;
                    const normalized = list.map((x) => Number(x)).sort((a, b) => a - b);
                    return normalized.length === 3 && normalized[0] === 13 && normalized[1] === 14 && normalized[2] === 15;
                  } catch (e) {
                    return false;
                  }
                })();
                if (isNeighborhoodPage) {
                  // Für die Nachbarschaftsseite ist das Flag maßgeblich;
                  // ein evtl. gesetzter Ortsfilter darf hier nicht blockieren.
                  params.neighborInvitation = true;
                  delete params.location;
                }
                if (isLegacyNeighborhoodConfig) {
                  // Abwärtskompatibel für bestehende Seitenkonfigurationen in Inhalten/DB:
                  // location [13,14,15] bedeutete historisch "Nachbarschaftsraum".
                  params.neighborInvitation = true;
                  delete params.location;
                }
                const response = await axios.get('/worships/filtered', {
                    params
                });
                this.worships = response.data;
            } catch (error) {
                console.error('Fehler beim Abrufen der Gottesdienste:', error);
            }
        }
    }
};
</script>

<style scoped>
.worship-card {
  display: grid;
  grid-template-columns: 180px 1fr;
  gap: var(--space-4);
  align-items: start;
}

@media (max-width: 640px) {
  .worship-card {
    grid-template-columns: 1fr;
    gap: var(--space-3);
  }
}

.worship-card__left {
  border-radius: 6px;
  padding: var(--space-3);
  color: var(--color-text);
  background: var(--color-bg-subtle);
  border: 1px solid rgba(0, 0, 0, 0.08);
}

.worship-card__date {
  font-weight: 600;
}

.worship-card__day,
.worship-card__place {
  margin-top: var(--space-1);
  color: rgba(0, 0, 0, 0.75);
}

.worship-card__right {
  min-width: 0;
}

.highlight-time {
  text-decoration: underline;
}
.neighborhood-invitation {
  font-weight: 600;
}
a {
  color: var(--color-brand-primary-hover);
}
.internal-information {
  color: #a01935;
  font-style: italic;
}

.stack-tight {
  gap: var(--space-2);
}
</style>