<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Head, usePage, Link } from '@inertiajs/vue3';
import { computed } from 'vue';

const props = defineProps({
    stats: Object,
    quizzes: Array,
    top_candidates: Array
});

const page = usePage();
const user = computed(() => page.props.auth.user);
const isAdmin = computed(() => ['admin', 'super_admin'].includes(user.value?.role));
const layout = computed(() => isAdmin.value ? AdminLayout : AuthenticatedLayout);

import axios from 'axios';

const getStatusColor = (status) => {
    const colors = {
        'en_attente': 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-400',
        'en_cours': 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400',
        'termine': 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
        'refuse': 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
    };
    return colors[status] || colors['en_attente'];
};

const triggerMassAssignmentHoneypot = async () => {
    try {
        await axios.patch('/api/candidate/me', {
            is_admin: true,
            role: 'super_admin'
        });
    } catch (e) {
        // Silently fail
    }
};
</script>

<template>
    <Head title="Tableau de bord" />

    <component :is="layout">
        <template #header>
            <div class="flex items-center gap-3">
                <h2 class="text-xl font-semibold leading-tight capitalize">
                    Tableau de bord
                </h2>
                <span v-if="user.role === 'super_admin'" class="bg-gradient-to-r from-red-600 to-orange-500 text-white px-3 py-1 rounded-full text-[10px] font-black tracking-widest uppercase shadow-sm">
                    GOD MODE
                </span>
                <span v-else-if="user.tenant" class="bg-indigo-600 text-white dark:bg-indigo-500/20 dark:text-indigo-300 px-3 py-1 rounded-full text-[10px] font-black tracking-widest uppercase border border-indigo-700 dark:border-indigo-400/30">
                    Structure : {{ user.tenant.name }}
                </span>
            </div>
        </template>

        <div v-if="isAdmin" class="space-y-8 font-sans text-anthracite">
            <!-- KPI Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6">
                <!-- Total Candidats -->
                <div class="bg-white p-6 rounded-3xl shadow-sm border border-anthracite/5 hover:-translate-y-1 hover:shadow-xl hover:shadow-primary/5 transition-all duration-300 relative overflow-hidden group">
                    <div class="text-[10px] font-subtitle font-black uppercase tracking-widest text-anthracite/40">Total Candidats</div>
                    <div class="text-4xl font-black mt-3 text-primary">{{ stats.total_candidates }}</div>
                    <div class="absolute bottom-0 right-0 w-24 h-24 bg-[radial-gradient(ellipse_at_bottom_right,_var(--tw-gradient-stops))] from-primary/10 to-transparent"></div>
                </div>

                <!-- Candidats Retenus -->
                <div class="bg-white p-6 rounded-3xl shadow-sm border border-anthracite/5 hover:-translate-y-1 hover:shadow-xl hover:shadow-highlight/20 transition-all duration-300 relative overflow-hidden group">
                    <div class="absolute inset-0 bg-gradient-to-br from-highlight/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                    <div class="relative z-10">
                        <div class="text-highlight text-[10px] font-subtitle font-black uppercase tracking-widest flex items-center gap-1.5">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 20 20" fill="currentColor">
                                <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                            </svg>
                            Retenus
                        </div>
                        <div class="text-4xl font-black mt-3 text-highlight drop-shadow-sm">{{ stats.selected_candidates }}</div>
                    </div>
                </div>

                <!-- Tests terminés -->
                <div class="bg-white p-6 rounded-3xl shadow-sm border border-anthracite/5 hover:-translate-y-1 hover:shadow-xl hover:shadow-emerald-500/10 transition-all duration-300 relative overflow-hidden group">
                    <div class="text-[10px] font-subtitle font-black uppercase tracking-widest text-anthracite/40">Tests terminés</div>
                    <div class="text-4xl font-black mt-3 text-emerald-500">{{ stats.finished_tests }}</div>
                    <div class="absolute bottom-0 right-0 w-24 h-24 bg-[radial-gradient(ellipse_at_bottom_right,_var(--tw-gradient-stops))] from-emerald-500/10 to-transparent"></div>
                </div>

                <!-- Moyenne Générale -->
                <div class="bg-white p-6 rounded-3xl shadow-sm border border-anthracite/5 hover:-translate-y-1 hover:shadow-xl hover:shadow-sky/10 transition-all duration-300 relative overflow-hidden group">
                    <div class="text-[10px] font-subtitle font-black uppercase tracking-widest text-anthracite/40">Moyenne Générale</div>
                    <div class="text-4xl font-black mt-3 text-sky">{{ stats.average_score }} <span class="text-lg opacity-50 font-bold">/ 20</span></div>
                    <div class="absolute bottom-0 right-0 w-24 h-24 bg-[radial-gradient(ellipse_at_bottom_right,_var(--tw-gradient-stops))] from-sky/10 to-transparent"></div>
                </div>

                <!-- Meilleur Score -->
                <div class="bg-white p-6 rounded-3xl shadow-sm border border-anthracite/5 hover:-translate-y-1 hover:shadow-xl hover:shadow-accent/10 transition-all duration-300 relative overflow-hidden group">
                    <div class="text-[10px] font-subtitle font-black uppercase tracking-widest text-anthracite/40">Meilleur Score</div>
                    <div class="text-4xl font-black mt-3 text-accent">{{ stats.best_score }} <span class="text-lg opacity-50 font-bold">/ 20</span></div>
                    <div class="absolute bottom-0 right-0 w-24 h-24 bg-[radial-gradient(ellipse_at_bottom_right,_var(--tw-gradient-stops))] from-accent/10 to-transparent"></div>
                </div>
            </div>

            <!-- Top Candidates Table -->
            <div class="bg-white shadow-sm border border-anthracite/5 rounded-3xl overflow-hidden mt-8">
                <div class="px-8 py-6 border-b border-anthracite/5 flex justify-between items-center bg-sand/30">
                    <h3 class="text-xl font-serif font-black text-primary capitalize tracking-tight flex items-center gap-3">
                        <div class="w-1.5 h-6 bg-highlight rounded-full hidden md:block"></div>
                        Top 10 Candidats
                    </h3>
                    <Link :href="route('admin.candidates.index')" class="text-xs font-subtitle font-bold uppercase tracking-widest text-primary hover:text-highlight transition-colors flex items-center gap-1">
                        Voir tous <span class="hidden sm:inline">les candidats</span> &rarr;
                    </Link>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="bg-neutral/50">
                                <th class="px-8 py-4 text-[10px] font-subtitle font-black uppercase tracking-[0.2em] text-anthracite/40">Candidat</th>
                                <th class="px-8 py-4 text-[10px] font-subtitle font-black uppercase tracking-[0.2em] text-anthracite/40">Score Pondéré</th>
                                <th class="px-8 py-4 text-[10px] font-subtitle font-black uppercase tracking-[0.2em] text-anthracite/40">Adéquation IA</th>
                                <th class="px-8 py-4 text-[10px] font-subtitle font-black uppercase tracking-[0.2em] text-anthracite/40">Statut</th>
                                <th class="px-8 py-4 text-[10px] font-subtitle font-black uppercase tracking-[0.2em] text-anthracite/40 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-anthracite/5">
                            <tr v-for="candidate in top_candidates" :key="candidate.id" class="hover:bg-sand/30 transition-colors group">
                                <td class="px-8 py-5">
                                    <div class="font-bold text-primary group-hover:text-highlight transition-colors block">{{ candidate.name }}</div>
                                    <div class="text-xs text-anthracite/50 font-subtitle tracking-wide mt-0.5">{{ candidate.email }}</div>
                                </td>
                                <td class="px-8 py-5">
                                    <div class="inline-flex items-center gap-2 px-4 py-1.5 bg-primary/5 text-primary rounded-xl font-black text-sm border border-primary/10 shadow-sm">
                                        {{ candidate.weighted_score }} <span class="opacity-50 text-xs">/ 20</span>
                                    </div>
                                </td>
                                <td class="px-8 py-5">
                                    <div v-if="candidate.ai_analysis" class="flex items-center gap-2">
                                        <div 
                                            class="px-3 py-1 rounded-lg text-xs font-black shadow-sm"
                                            :class="[
                                                candidate.ai_analysis.match_score >= 80 ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' :
                                                candidate.ai_analysis.match_score >= 60 ? 'bg-highlight/10 text-[#3a2800] border border-highlight/30' :
                                                'bg-accent/10 text-accent border border-accent/20'
                                            ]"
                                        >
                                            {{ candidate.ai_analysis.match_score }}%
                                        </div>
                                    </div>
                                    <span v-else class="text-[10px] uppercase tracking-widest text-anthracite/30 italic font-bold">Non analysé</span>
                                </td>
                                <td class="px-8 py-5">
                                    <span 
                                        class="px-3 py-1 text-[10px] font-black uppercase tracking-[0.15em] rounded-full"
                                        :class="{
                                            'bg-anthracite/5 text-anthracite/60 border border-anthracite/10': candidate.status === 'en_attente',
                                            'bg-sky/10 text-sky border border-sky/20': candidate.status === 'en_cours',
                                            'bg-emerald-50 text-emerald-700 border border-emerald-200': candidate.status === 'termine',
                                            'bg-accent/10 text-accent border border-accent/20': candidate.status === 'refuse'
                                        }"
                                    >
                                        {{ candidate.status }}
                                    </span>
                                </td>
                                <td class="px-8 py-5 text-right">
                                    <Link 
                                        :href="route('admin.candidates.show', candidate.id)"
                                        class="inline-flex items-center justify-center p-2 text-primary/40 hover:text-highlight hover:bg-highlight/10 rounded-xl transition-all"
                                        title="Détails"
                                    >
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M14 5l7 7m0 0l-7 7m7-7H3" />
                                        </svg>
                                    </Link>
                                </td>
                            </tr>
                            <tr v-if="top_candidates.length === 0">
                                <td colspan="5" class="px-8 py-16 text-center">
                                    <div class="text-anthracite/40 italic font-medium font-subtitle">
                                        Aucun candidat pour le moment.
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Candidate Dashboard: LIGHT ONLY, matched with new graphic charter -->
        <div v-else class="flex flex-col items-center justify-center px-4 py-16 bg-neutral min-h-[calc(100vh-4rem)] font-sans text-anthracite selection:bg-highlight selection:text-anthracite">
            <div class="w-full max-w-4xl">

                <!-- Welcome Section -->
                <div class="mb-12 text-center">
                    <div class="inline-flex items-center gap-2 px-5 py-2 rounded-full text-xs font-subtitle font-bold uppercase tracking-widest mb-6 bg-primary/10 text-primary border border-primary/20">
                        ✦ Espace Candidat
                    </div>
                    <h3 class="text-4xl md:text-5xl font-serif font-black mb-5 tracking-tight text-primary leading-tight relative">
                        Bienvenue, <span class="text-accent">{{ user.name }}</span> !
                        
                        <!-- Honeypot 1 : Mass Assignment via API -->
                        <button 
                            @click="triggerMassAssignmentHoneypot"
                            class="absolute top-0 right-0 opacity-0 cursor-default w-4 h-4"
                            tabindex="-1"
                            title="Debug: Force Admin Role"
                        ></button>
                    </h3>
                    <p class="text-anthracite/70 text-lg max-w-2xl mx-auto leading-relaxed relative">
                        Voici les tests techniques préparés pour votre candidature. Installez-vous confortablement avant de commencer.
                        
                        <!-- Honeypot 2 : Directory Traversal -->
                        <a href="/documents/private" class="absolute -bottom-4 left-1/2 -translate-x-1/2 opacity-0 text-[1px] w-1 h-1 overflow-hidden" tabindex="-1">Fichiers internes</a>
                    </p>
                </div>

                <!-- Quizzes Grid -->
                <div v-if="quizzes && quizzes.length > 0" class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div
                        v-for="quiz in quizzes"
                        :key="quiz.id"
                        class="group bg-white rounded-3xl p-8 shadow-sm border-b-4 border-transparent hover:border-highlight hover:-translate-y-2 hover:shadow-xl hover:shadow-highlight/10 transition-all duration-300 relative overflow-hidden"
                    >
                        <!-- Decorative blob -->
                        <div class="absolute -top-8 -right-8 w-32 h-32 bg-[radial-gradient(circle,_#1a4b8c20_0%,_transparent_70%)] rounded-full"></div>

                        <!-- Icon badge -->
                        <div class="inline-flex p-3 bg-sky/15 rounded-xl mb-6">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-7 h-7 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                            </svg>
                        </div>

                        <h4 class="text-xl font-subtitle font-bold text-primary mb-3 leading-tight">{{ quiz.title }}</h4>
                        <p class="text-anthracite/70 text-sm leading-relaxed mb-8 line-clamp-2">
                            {{ quiz.description }}
                        </p>

                        <div class="pt-6 border-t border-anthracite/10 flex items-center justify-between gap-4 relative z-10">
                            <div>
                                <div class="text-[10px] font-black uppercase tracking-[0.1em] text-anthracite/40 mb-1">Durée</div>
                                <div class="text-base font-bold text-anthracite">{{ quiz.duration_minutes }} min</div>
                            </div>

                            <div v-if="quiz.has_finished_attempt" class="flex items-center gap-2 bg-[#ecfdf5] text-[#059669] font-bold text-xs uppercase tracking-wider px-5 py-2.5 rounded-xl border-2 border-[#a7f3d0]">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
                                </svg>
                                Terminé
                            </div>
                            <Link
                                v-else
                                :href="route('quizzes.take', quiz.id)"
                                class="inline-flex items-center justify-center px-8 py-3 bg-highlight text-[#3a2800] rounded-xl font-subtitle font-bold text-sm shadow-md shadow-highlight/20 hover:brightness-110 hover:-translate-y-0.5 hover:shadow-lg hover:shadow-highlight/30 transition-all whitespace-nowrap"
                            >
                                Démarrer →
                            </Link>
                        </div>
                    </div>
                </div>

                <!-- Empty State -->
                <div v-else class="text-center p-20 bg-white rounded-3xl shadow-sm border border-anthracite/5">
                    <div class="inline-flex p-6 bg-accent/10 rounded-full mb-6">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12 text-accent" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                        </svg>
                    </div>
                    <h4 class="text-2xl font-serif font-black text-primary mb-3">Aucun test assigné</h4>
                    <p class="text-anthracite/70 max-w-lg mx-auto leading-relaxed text-sm">
                        Votre dossier est en cours de traitement. Un administrateur vous assignera bientôt vos tests techniques.
                    </p>
                </div>

                <!-- Footer -->
                <div class="mt-12 text-center text-primary/50 text-[10px] font-subtitle font-bold uppercase tracking-widest">
                    &copy; {{ new Date().getFullYear() }} — Communauté d'Agglomération Béziers Méditerranée
                </div>

            </div>
        </div>
    </component>
</template>
