---
import type { CollectionEntry } from "astro:content";
interface Props {
    posts: CollectionEntry<"journal">[];
    tags: string[];
    basePath: "journal";
}
const { posts, tags, basePath } = Astro.props;

// Groupement des tags par catégorie (ton code actuel)
const groupedTags: Record<string, string[]> = { Général: [] };
tags.forEach((tag) => {
    if (tag.includes(":")) {
        const cat = tag.split(":")[0];
        const catName = cat.charAt(0).toUpperCase() + cat.slice(1);
        if (!groupedTags[catName]) groupedTags[catName] = [];
        groupedTags[catName].push(tag);
    } else {
        groupedTags["Général"].push(tag);
    }
});
---

<div id="content-search-component">
    <div class="search-wrapper">
        <input
            type="search"
            id="search-input"
            placeholder="Rechercher dans le journal..."
        />
    </div>

    <div class="filter-box">
        <div class="category-nav">
            <span class="nav-label">Filtres :</span>
            <button class="cat-nav-btn active" data-target="all">Toutes</button>
            {
                Object.keys(groupedTags).map(
                    (cat) =>
                        cat !== "Général" && (
                            <button class="cat-nav-btn" data-target={cat}>
                                {cat}
                            </button>
                        ),
                )
            }
        </div>
        <div class="tags-reveal-area">
            {
                Object.entries(groupedTags).map(([category, categoryTags]) => (
                    <div
                        class="tag-subgroup"
                        id={`group-${category}`}
                        style={category === "Général" ? "" : "display: none;"}
                    >
                        {categoryTags.map((tag) => (
                            <button class="js-tag-filter" data-tag={tag}>
                                {tag.includes(":") ? tag.split(":")[1] : tag}
                            </button>
                        ))}
                    </div>
                ))
            }
        </div>
    </div>

    <div id="search-results" class="card-grid">
        {
            posts.map((post) => (
                <a
                    href={`/${basePath}/${post.id}/`}
                    class="gold-button"
                    data-era={post.data.era}
                >
                    <div class="title">{post.data.title}</div>
                    <p class="body">
                        Publié le{" "}
                        {new Date(post.data.publishDate).toLocaleDateString(
                            "fr-FR",
                        )}
                    </p>
                </a>
            ))
        }
    </div>

    <div
        id="search-data-bridge"
        data-posts={JSON.stringify(posts)}
        style="display: none;"
    >
    </div>
</div>

<script>
    function init() {
        const bridge = document.getElementById("search-data-bridge");
        const input = document.getElementById(
            "search-input",
        ) as HTMLInputElement;
        const container = document.getElementById("search-results");
        if (!bridge || !input || !container) return;

        const posts = JSON.parse(bridge.getAttribute("data-posts") || "[]");

        // --- ÉTATS DES FILTRES ---
        let activeTag = "all";
        let activeEra = "all";

        function update() {
            const query = input.value
                .toLowerCase()
                .normalize("NFD")
                .replace(/[\u0300-\u036f]/g, "");

            const filtered = posts.filter((p: any) => {
                const mQuery = p.data.title.toLowerCase().includes(query);
                const mTag =
                    activeTag === "all" || p.data.tags?.includes(activeTag);
                const mEra = activeEra === "all" || p.data.era === activeEra;
                return mQuery && mTag && mEra;
            });

            container.innerHTML = filtered
                .map(
                    (p: any) => `
                <a href="/journal/${p.id}/" class="gold-button" data-era="${p.data.era || ""}">
                    <div class="title">${p.data.title}</div>
                    <p class="body">Publié le ${new Date(p.data.publishDate).toLocaleDateString("fr-FR")}</p>
                </a>
            `,
                )
                .join("");
        }

        // --- ÉCOUTEUR POUR LA TIMELINE (INDEX) ---
        // On écoute les clics sur les chips de la Timeline qui sont hors du composant
        document.addEventListener("click", (e) => {
            const target = e.target as HTMLElement;
            const eraBtn = target.closest(".era-chip");

            if (eraBtn) {
                activeEra = eraBtn.getAttribute("data-era") || "all";

                // On gère la classe active visuellement
                document
                    .querySelectorAll(".era-chip")
                    .forEach((btn) => btn.classList.remove("active"));
                eraBtn.classList.add("active");

                update();
            }
        });

        // --- TES ÉCOUTEURS ACTUELS ---
        input.addEventListener("input", update);

        document.querySelectorAll(".cat-nav-btn").forEach((btn) => {
            btn.addEventListener("click", () => {
                document
                    .querySelectorAll(".cat-nav-btn")
                    .forEach((b) => b.classList.remove("active"));
                btn.classList.add("active");
                const target = btn.getAttribute("data-target");
                document.querySelectorAll(".tag-subgroup").forEach((g) => {
                    (g as HTMLElement).style.display =
                        g.id === `group-${target}` ? "block" : "none";
                });
                if (target === "all") {
                    activeTag = "all";
                    document
                        .querySelectorAll(".js-tag-filter")
                        .forEach((el) => el.classList.remove("active-tag"));
                    update();
                }
            });
        });

        document.querySelectorAll(".js-tag-filter").forEach((t) => {
            t.addEventListener("click", () => {
                document
                    .querySelectorAll(".js-tag-filter")
                    .forEach((el) => el.classList.remove("active-tag"));
                t.classList.add("active-tag");
                activeTag = (t as HTMLElement).dataset.tag || "all";
                update();
            });
        });
    }

    document.addEventListener("astro:page-load", init);
</script>

<style>
    .search-wrapper {
        margin-bottom: 2rem;
        display: flex;
        justify-content: center;
    }
    #search-input {
        width: 100%;
        max-width: 400px;
        padding: 0.7rem 1rem;
        border-radius: 20px;
        border: 1px solid var(--color-gold);
        outline: none;
        font-family: inherit;
        background: white;
    }
    .filter-box {
        border: 1px solid #dcd0b9;
        border-radius: 8px;
        background: #fffaf0;
        margin-bottom: 2rem;
        overflow: hidden;
    }
    .category-nav {
        background: #f3ece0;
        padding: 0.5rem;
        display: flex;
        gap: 0.5rem;
        flex-wrap: wrap;
        align-items: center;
        border-bottom: 1px solid #dcd0b9;
    }
    .nav-label {
        font-family: "Cinzel", serif;
        font-size: 0.75rem;
        color: var(--color-gold-dark);
        margin-right: 0.5rem;
    }
    .cat-nav-btn {
        background: none;
        border: none;
        font-family: "Cinzel", serif;
        font-size: 0.7rem;
        cursor: pointer;
        color: var(--color-ink);
    }
    .cat-nav-btn.active {
        color: var(--color-gold-dark);
        font-weight: bold;
        border-bottom: 2px solid var(--color-gold);
    }
    .tags-reveal-area {
        padding: 0.8rem;
        min-height: 40px;
    }
</style>
