<template>
    <div v-if="config && config.style === 'box' && contacts && contacts.length && contacts.length > 0">
        <div v-for="contact in contacts" :key="contact.id" class="contact-box">
            <p>{{ contact.name }}</p>
            <p v-if="displayOptions.includes('phone')">Telefon: {{ contact.phone }}</p>
            <p v-if="displayOptions.includes('street')">Straße: {{ contact.street }}</p>
            <p v-if="displayOptions.includes('zipcode')">Postleitzahl: {{ contact.zipcode }}</p>
            <p v-if="displayOptions.includes('city')">Stadt: {{ contact.city }}</p>
            <p v-if="displayOptions.includes('email')">E-Mail: {{ contact.email }}</p>
            <p v-if="displayOptions.includes('positions')">Positionen: {{ contact.positions.map(pos =>
                pos.caption).join(', ') }}</p>
        </div>
    </div>
    <span v-else-if="config.style === 'float' && contacts && contacts.length && contacts.length > 0">
        <span v-for="contact in contacts" :key="contact.id">
            {{ contact.name }}
            <span v-if="displayOptions.includes('phone')">, Telefon: {{ contact.phone }}</span>
            <span v-if="displayOptions.includes('street')">, Straße: {{ contact.street }}</span>
            <span v-if="displayOptions.includes('zipcode')">, Postleitzahl: {{ contact.zipcode }}</span>
            <span v-if="displayOptions.includes('city')">, Stadt: {{ contact.city }}</span>
            <span v-if="displayOptions.includes('email')">, E-Mail: {{ contact.email }}</span>
            <span v-if="displayOptions.includes('positions')">, Positionen: {{ contact.positions.map(pos =>
                pos.caption).join(', ') }}</span>
        </span>
    </span>
</template>

<script>
import axios from '@/axios';

export default {
    name: 'ContactRender',
    props: {
        config: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            contacts: [],
            loading: true,
            error: null,
            displayOptions: [],
        };
    },
    async created() {
        try {
            this.displayOptions = this.config.display || [];
            const response = await axios.post('/contact-persons/filter', {
                config: JSON.stringify(this.config),
            });
            this.contacts = response.data;
            this.loading = false;
        } catch (error) {
            console.error('Error loading contacts:', error);
            this.error = 'Fehler beim Laden der Kontaktpersonen';
            this.loading = false;
        }
    },
};
</script>

<style scoped>
.contact-box p {
    margin: 0;
}
</style>