<template>
    <div class="project">
        <div class="project-header">
            <h2 @click="goToLink">{{ projectName }}</h2>
            <div class="header-actions">
                <div class="dropdown-wrapper">
                    <!-- Empêche la propagation du clic vers le parent -->
                    <button class="contact-button" @click.stop="toggleDropdown">
                        Contact
                    </button>

                    <div v-if="isDropdownOpen" class="dropdown-menu">
                        <button @click.stop="contactAll">Contacter tous</button>
                        <button
                            v-for="(email, index) in entrepreneurEmails"
                            :key="index"
                            @click.stop="contactSingle(email)"
                        >
                            {{ email }}
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Toute cette partie est cliquable -->
        <div class="project-body" @click="goToLink">
            <ul>
                <li v-for="(name, index) in listName" :key="index">
                    {{ name }}
                </li>
            </ul>
        </div>
    </div>
</template>

<script setup lang="ts">
import { defineProps, ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";

const IS_MOCK_MODE = true;

const props = defineProps<{
    projectName: string;
    listName: string[];
    projectLink: string;
    projectId: number;
}>();

const router = useRouter();

const isDropdownOpen = ref(false);
const entrepreneurEmails = ref<string[]>([]);

// Pour fermer le dropdown si on clique ailleurs
const handleClickOutside = (event: MouseEvent) => {
    const dropdown = document.querySelector(".dropdown-wrapper");
    if (dropdown && !dropdown.contains(event.target as Node)) {
        isDropdownOpen.value = false;
    }
};

onMounted(() => {
    fetchEntrepreneurs(props.projectId, IS_MOCK_MODE);
    document.addEventListener("click", handleClickOutside);
});

onBeforeUnmount(() => {
    document.removeEventListener("click", handleClickOutside);
});

const toggleDropdown = () => {
    isDropdownOpen.value = !isDropdownOpen.value;
};

const goToLink = () => {
    if (props.projectLink) {
        router.push(props.projectLink);
    }
};

const fetchEntrepreneurs = async (
    projectId: number,
    useMock = IS_MOCK_MODE
) => {
    try {
        const responseData: Entrepreneur[] = useMock
            ? await mockFetchEntrepreneurs(/*projectId*/)
            : (
                  await axios.get(
                      `http://localhost:5000/shared/projects/entrepreneurs/${projectId}`
                  )
              ).data;

        entrepreneurEmails.value = responseData.map(
            (item: Entrepreneur) => item.primaryMail
        );
    } catch (error) {
        console.error(
            "Erreur lors de la récupération des entrepreneurs :",
            error
        );
    }
};

type Entrepreneur = {
    idUser: number;
    userSurname: string;
    userName: string;
    primaryMail: string;
    secondaryMail: string;
    phoneNumber: string;
    school: string;
    course: string;
    sneeStatus: boolean;
};

const mockFetchEntrepreneurs = async (/*projectId: number*/) => {
    return new Promise<Entrepreneur[]>((resolve) => {
        setTimeout(() => {
            resolve([
                {
                    idUser: 1,
                    userSurname: "Doe",
                    userName: "John",
                    primaryMail: "john.doe@example.com",
                    secondaryMail: "johndoe@backup.com",
                    phoneNumber: "612345678",
                    school: "ENSEIRB",
                    course: "Info",
                    sneeStatus: false,
                },
                {
                    idUser: 2,
                    userSurname: "Smith",
                    userName: "Jane",
                    primaryMail: "jane.smith@example.com",
                    secondaryMail: "janesmith@backup.com",
                    phoneNumber: "698765432",
                    school: "ENSEIRB",
                    course: "Info",
                    sneeStatus: true,
                },
            ]);
        }, 500);
    });
};

const contactAll = () => {
    const allEmails = entrepreneurEmails.value.join(", ");
    navigator.clipboard.writeText(allEmails).then(() => {
        alert("Tous les emails copiés dans le presse-papiers !");
        window.open("https://partage.bordeaux-inp.fr/", "_blank");
    });
};

const contactSingle = (email: string) => {
    navigator.clipboard.writeText(email).then(() => {
        alert(`Adresse copiée : ${email}`);
        window.open("https://partage.bordeaux-inp.fr/", "_blank");
    });
};
</script>

<style scoped>
.project {
    background: linear-gradient(to right, #f8f9fb, #ffffff);
    border: 1px solid #e0e0e0;
    border-radius: 16px;
    padding: 1.5rem;
    margin: 1.5rem 0;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: box-shadow 0.3s ease;
    cursor: pointer;
}

.project:hover {
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
}

.project-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.project-header h2 {
    font-size: 1.25rem;
    color: #222;
    margin: 0;
    font-weight: 600;
}

.project-buttons {
    display: flex;
    gap: 0.5rem;
}

.contact-btn {
    background-color: #007bff;
    color: #fff;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 8px;
    font-size: 0.9rem;
    font-weight: 500;
    transition:
        background-color 0.2s ease,
        transform 0.2s ease;
}

.contact-btn:hover {
    background-color: #0056b3;
    transform: translateY(-2px);
}

.project-body {
    margin-top: 1rem;
}

.project-body ul {
    list-style-type: disc;
    padding-left: 1.25rem;
    margin: 0;
}

.project-body ul li {
    font-size: 0.95rem;
    color: #555;
    line-height: 1.6;
}

button {
    padding: 10px 15px;
    background-color: #007bff;
    color: white;
    border: none;
    cursor: pointer;
    border-radius: 5px;
}
button:hover {
    background-color: #0056b3;
}

.dropdown-wrapper {
    position: relative;
}

.dropdown-menu {
    position: absolute;
    top: 100%; /* juste en dessous du bouton */
    right: 0;
    background-color: white;
    border: 1px solid #ccc;
    padding: 0.5rem;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 0.25rem;
    min-width: 150px;
}

.dropdown-menu button {
    text-align: left;
    padding: 0.3rem 0.5rem;
    background: none;
    border: none;
    cursor: pointer;
    transition: background-color 0.2s;
}

.dropdown-menu button:hover {
    background-color: #f0f0f0;
}
</style>
