---
import { getCollection } from "astro:content";
import GameLayout from "../layouts/GameLayout.astro";
import Header from "../components/Header.astro";

const classes = await getCollection("classes");
const especes = await getCollection("especes");
const personnages = await getCollection("personnages");

// 1. Groupement par CLASSE (Bordure BAS = Espèce)
const classData = personnages.reduce((acc, p) => {
    const pEspeceData = especes.find(
        (e) => e.id.toLowerCase() === p.data.espece?.toLowerCase(),
    );
    // On récupère juste la clé du spectre (ex: 'solaire', 'ombre')
    const spectreKey = pEspeceData?.data.spectre?.toLowerCase() || "default";

    p.data.classes_detail.forEach((c) => {
        if (!c.nom) return;
        const key = c.nom.toLowerCase();
        if (!acc[key]) acc[key] = [];

        acc[key].push({
            id: p.id,
            nom: p.data.nom,
            niveau_classe: c.niveau,
            spectreVar: `var(--color-${spectreKey})`,
        });
    });
    return acc;
}, {});

// 2. Groupement par ESPECE (Bordure HAUT = Couleurs des classes)
const especeData = personnages.reduce((acc, p) => {
    if (!p.data.espece) return acc;
    const key = p.data.espece.toLowerCase();
    if (!acc[key]) acc[key] = [];

    // On récupère les clés d'encre pour construire le dégradé en CSS
    const classInks = (p.data.classes_detail || []).map((c) => {
        const pClassData = classes.find(
            (cl) =>
                cl.id.toLowerCase() === c.nom?.toLowerCase() ||
                cl.data.title?.toLowerCase() === c.nom?.toLowerCase(),
        );
        return pClassData?.data.encre?.toLowerCase() || "default";
    });

    acc[key].push({
        id: p.id,
        nom: p.data.nom,
        niveau: p.data.niveau_global || 1,
        inks: classInks,
    });
    return acc;
}, {});
---

<GameLayout title="Création de Personnage">
    <div class="creation-container">
        <Header />
        <section class="character-select">
            <section class="character-select">
                <h2 class="dnd-title">Choisissez votre Classe</h2>
                <div class="dnd-bar"></div>
                <p class="dnd-intro">
                    La classe définit vos compétences et votre rôle.
                </p>

                <div class="dnd-intro-badges">
                    <span class="ink-badge ink-arcane">Arcane</span>
                    <span class="ink-badge ink-martial">Martial</span>
                    <span class="ink-badge ink-hybride">Neutre</span>
                    <span class="ink-badge ink-divin">Sacré</span>
                    <span class="ink-badge ink-primal">Primal</span>
                </div>

                <div class="class-grid">
                    {
                        classes.map((charClass) => {
                            const charactersInClass =
                                classData[charClass.id.toLowerCase()] || [];
                            const encreKey =
                                charClass.data.encre?.toLowerCase() ||
                                "default";

                            return (
                                <div
                                    class="class-card"
                                    style={`--accent-color: var(--color-${encreKey})`}
                                >
                                    <h3 class="dynamic-title">
                                        {charClass.data.title}
                                    </h3>
                                    <div class="bubble-container">
                                        {charactersInClass.map((p) => (
                                            <a
                                                href={`/personnages/${p.id}`}
                                                class="notification-bubble bubble-species-border"
                                                style={`--p-color: ${p.spectreVar}`}
                                            >
                                                <span class="p-name">
                                                    {p.nom}
                                                </span>
                                                <span class="p-lvl">
                                                    Niv.{p.niveau_classe}
                                                </span>
                                            </a>
                                        ))}
                                    </div>
                                    <p>{charClass.data.description}</p>
                                    <a
                                        href={`/classes/${charClass.id}`}
                                        class="select-button"
                                    >
                                        Détails
                                    </a>
                                </div>
                            );
                        })
                    }
                </div>
            </section>

            <section class="character-select">
                <h2 class="dnd-title">Choisissez votre Espèce</h2>
                <div class="dnd-bar"></div>
                <p class="dnd-intro">
                    L'espèce influence votre apparence et votre histoire
                </p>

                <div class="dnd-intro-badges">
                    <span class="spec-badge spec-solaire">Solaire</span>
                    <span class="spec-badge spec-elementaire">Elementaire</span>
                    <span class="spec-badge spec-terrestre">Terrestre</span>
                    <span class="spec-badge spec-sylvestre">Sylvestre</span>
                    <span class="spec-badge spec-ombre">Ombre</span>
                </div>

                <div class="class-grid">
                    {
                        especes.map((espece) => {
                            const charactersInEspece =
                                especeData[espece.id.toLowerCase()] || [];
                            const spectreKey =
                                espece.data.spectre?.toLowerCase() || "default";

                            return (
                                <div
                                    class="class-card species-card"
                                    style={`--bg-color: var(--color-${spectreKey})`}
                                >
                                    <h3>{espece.data.title}</h3>
                                    <div class="bubble-container">
                                        {charactersInEspece.map((p) => {
                                            // Création du dégradé basé sur les variables CSS des encres
                                            const c1 = `var(--color-${p.inks[0]})`;
                                            const c2 =
                                                p.inks.length > 1
                                                    ? `var(--color-${p.inks[1]})`
                                                    : c1;
                                            const gradient = `linear-gradient(to right, ${c1}, ${c2})`;

                                            return (
                                                <a
                                                    href={`/personnages/${p.id}`}
                                                    class="notification-bubble bubble-class-border"
                                                    style={`--p-gradient: ${gradient}`}
                                                >
                                                    <span class="p-name">
                                                        {p.nom}
                                                    </span>
                                                    <span class="p-lvl">
                                                        Niv.{p.niveau}
                                                    </span>
                                                </a>
                                            );
                                        })}
                                    </div>
                                    <p>{espece.data.description}</p>
                                    <a
                                        href={`/especes/${espece.id}`}
                                        class="select-button species-button"
                                    >
                                        Détails
                                    </a>
                                </div>
                            );
                        })
                    }
                </div>
            </section>
        </section>
    </div>

    <style>
        /* [Tes styles existants restent identiques sauf les ajouts ci-dessous] */
        .creation-container {
            max-width: 1000px;
            margin: 0 auto;
        }
        .character-select {
            margin: 4rem 0;
        }
        .dnd-title {
            font-family: "Playfair Display", serif;
            font-size: 2.5rem;
            color: #c89b3c;
            text-align: center;
        }
        .dnd-bar {
            height: 3px;
            background: linear-gradient(
                to right,
                transparent,
                #c89b3c,
                transparent
            );
            margin: 4px auto 1rem;
            width: 50%;
        }
        .dnd-intro {
            font-family: "Cinzel", serif;
            font-size: 0.9rem;
            text-align: center;
            opacity: 0.8;
            margin-bottom: 2rem;
        }

        .dnd-intro-badges {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: center;
            margin-bottom: 2rem;
            gap: 10px;
        }

        /* Badges d'Encre avec ombres colorées basées sur les variables du Layout */
        .ink-badge {
            background-color: white;
            padding: 5px 10px;
            border-radius: 5px;
            font-family: "Cinzel", serif;
            font-size: 0.8rem;
        }
        .ink-arcane {
            color: var(--color-arcane);
            box-shadow: 0 4px 15px -5px var(--color-arcane);
        }
        .ink-martial {
            color: var(--color-martial);
            box-shadow: 0 4px 15px -5px var(--color-martial);
        }
        .ink-hybride {
            color: var(--color-hybride);
            box-shadow: 0 4px 15px -5px var(--color-hybride);
        }
        .ink-divin {
            color: var(--color-divin);
            box-shadow: 0 4px 15px -5px var(--color-divin);
        }
        .ink-primal {
            color: var(--color-primal);
            box-shadow: 0 4px 15px -5px var(--color-primal);
        }

        /* Badges de Spectre */
        .spec-badge {
            padding: 5px 10px;
            border-radius: 5px;
            font-family: "Cinzel", serif;
            font-size: 0.8rem;
            color: #1a1a1a;
        }
        .spec-solaire {
            background-color: var(--color-solaire);
        }
        .spec-elementaire {
            background-color: var(--color-elementaire);
        }
        .spec-terrestre {
            background-color: var(--color-terrestre);
        }
        .spec-sylvestre {
            background-color: var(--color-sylvestre);
        }
        .spec-ombre {
            background-color: var(--color-ombre);
        }

        .class-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 2rem;
        }
        .class-card {
            background-color: white;
            padding: 2rem 1.5rem;
            border-radius: 5px;
            text-align: center;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            transition: all 0.3s ease;
            box-shadow: 0 10px 25px -5px
                color-mix(in srgb, var(--accent-color), transparent 80%);
        }
        .dynamic-title {
            color: var(--accent-color) !important;
            font-family: "Playfair Display", serif;
            font-size: 1.8rem;
        }
        .species-card {
            background-color: var(--bg-color) !important;
        }

        .notification-bubble {
            background: #1a1a1a !important;
            color: white !important;
            font-family: "Cinzel", serif;
            font-size: 0.7rem;
            padding: 4px 10px;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            text-decoration: none;
            transition: transform 0.2s ease;
        }
        .notification-bubble:hover {
            transform: translateY(-2px);
            filter: brightness(1.2);
        }

        .bubble-species-border {
            background-color: var(--p-color) !important;
            border-bottom: 3px solid rgba(0, 0, 0, 0.2) !important;
        }

        .bubble-class-border {
            position: relative;
            border-top: none !important;
            overflow: hidden;
        }
        .bubble-class-border::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--p-gradient);
        }

        .p-lvl {
            font-size: 0.6rem;
            opacity: 0.7;
            padding-left: 5px;
            border-left: 1px solid rgba(255, 255, 255, 0.2);
        }
        .bubble-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 6px;
            margin-bottom: 1.5rem;
            min-height: 30px;
        }

        .select-button {
            font-family: "Cinzel", serif;
            text-decoration: none;
            padding: 0.5rem 1rem;
            color: var(--accent-color);
            background: color-mix(
                in srgb,
                var(--accent-color),
                transparent 85%
            );
            transition: all 0.3s;
        }
        .select-button:hover {
            background: var(--accent-color);
            color: white;
        }

        .species-button {
            border-color: #1a1a1a;
            color: #1a1a1a;
            background: transparent;
        }
        .species-button:hover {
            background: #1a1a1a;
            color: white;
        }

        .class-card p {
            font-family: "Cinzel", serif;
            font-size: 0.85rem;
            margin-bottom: 1.5rem;
            flex-grow: 1;
        }
    </style>
</GameLayout>
