// ============================================================
// Amavero — TABLEAU (version V4 - Autocomplétion champ 2 filtrée)
// Champ 2 : suggère uniquement les mots co-occurrents avec mot1
// ============================================================

const AMV_URL_IMAGES = "https://lfadev.com/amavero/cors.php?f=amavero.json"; 
const AMV_URL_PROCHES = "https://lfadev.com/amavero/cors.php?f=proches.json";

let amvImages = [];
let amvProches = {};       
let amvMotsFrequents = []; 

// -------------------------
// Normalisation des textes
// -------------------------
function amvNormaliser(texte) {
  return (texte || "")
    .toString()
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/œ/g, "oe")
    .replace(/[^a-z0-9 ]/g, "")
    .trim();
}

// -------------------------
// Gestion de l'état des boutons
// -------------------------
function amvSetBoutons(desactiver) {
    const btnRechercher = document.getElementById("btnRechercher");
    const btnHasard = document.getElementById("btnHasard");
    const input1 = document.getElementById("motcle1");
    const input2 = document.getElementById("motcle2");

    if (btnRechercher) btnRechercher.disabled = desactiver;
    if (btnHasard) btnHasard.disabled = desactiver;
    if (input1) input1.disabled = desactiver;
    if (input2) input2.disabled = desactiver;

    const logZone = document.getElementById("messages"); 
    if (logZone) {
        if (desactiver) {
            logZone.textContent = "⏳ Chargement des données de recherche en cours...";
            logZone.style.color = "orange";
        } else if (!amvImages.length) {
             logZone.textContent = "❌ Chargement des images échoué ou JSON vide.";
             logZone.style.color = "red";
        } else {
             logZone.textContent = "✅ Système de recherche prêt.";
             logZone.style.color = "green";
        }
    }
}

// -------------------------
// Chargement des données
// -------------------------
async function amvChargerImagesEtProches_Tableau() {
    amvSetBoutons(true);
    try {
        const rImg = await fetch(AMV_URL_IMAGES);
        const toutesLesImages = await rImg.json();
        
        amvImages = toutesLesImages.filter(img => {
            const tags = (img.Tags || "").toLowerCase();
            return !tags.includes("exclu-tableau");
        });
        
        try {
            const rProches = await fetch(AMV_URL_PROCHES);
            const dataProches = await rProches.json(); 
            amvProches = {};
            for (const cle in dataProches) {
                if (!Object.prototype.hasOwnProperty.call(dataProches, cle)) continue;
                const n = amvNormaliser(cle);
                if (!n) continue;
                const liste = Array.isArray(dataProches[cle]) ? dataProches[cle] : [];
                amvProches[n] = liste;
            }
        } catch (e2) {
            amvProches = {};
        }

        amvCalculerMotsFrequents_Tableau();
        amvActiverAutocompletion_Tableau();
        amvSetBoutons(false);

    } catch (e) {
        amvSetBoutons(true); 
        const zone = document.getElementById("messages"); 
        if (zone) {
            zone.innerHTML = "<p style='color:red;'>❌ Impossible de charger les données.</p>";
        }
    }
}

function amvCalculerMotsFrequents_Tableau() {
    if (!amvImages.length) return;
    const compteur = {};
    for (const img of amvImages) {
        const motsCles = img.MotsClés || "";
        if (!motsCles) continue;
        const mots = motsCles.split(",").map(m => m.trim()).filter(m => m.length > 0);
        for (const mot of mots) {
            const n = amvNormaliser(mot);
            if (!n) continue;
            if (!compteur[n]) compteur[n] = { count: 0, forme: mot };
            compteur[n].count++;
        }
    }
    amvMotsFrequents = Object.values(compteur)
        .filter(o => o.count >= 9)
        .map(o => o.forme)
        .sort((a, b) => a.localeCompare(b, "fr"));
}

// -------------------------
// Filtrage par mot-clé (Utilitaire interne)
// -------------------------
function amvFiltrerParMot_Tableau(mot) {
    if (!mot) return []; 
    const cleCherchee = amvNormaliser(mot);
    if (!cleCherchee) return [];

    return amvImages.filter(img => {
        const motsCles = img.MotsClés || "";
        const motsNormalises = motsCles
            .split(',')
            .map(m => amvNormaliser(m))
            .filter(m => m.length > 0);
        return motsNormalises.includes(cleCherchee);
    });
}

// -------------------------
// RECHERCHE (AND STRICT)
// -------------------------
function amvChercherAvecProches_Tableau(mot1, mot2) {
    const m1 = (mot1 || "").trim();
    const m2 = (mot2 || "").trim();

    if (!m1 && !m2) return [];

    // CAS 1 : Recherche à DEUX MOTS (Intersection stricte - AND)
    if (m1 && m2) {
        const cle1 = amvNormaliser(m1);
        const cle2 = amvNormaliser(m2);

        return amvImages.filter(img => {
            const motsCles = (img.MotsClés || "")
                .split(',')
                .map(m => amvNormaliser(m))
                .filter(m => m.length > 0);
            return motsCles.includes(cle1) && motsCles.includes(cle2);
        });
    }

    // CAS 2 : Recherche à UN SEUL MOT (avec proches.json)
    const motSaisi = m1 || m2;
    let resultat = amvFiltrerParMot_Tableau(motSaisi); 

    const cleNorm = amvNormaliser(motSaisi);
    const equivalences = amvProches[cleNorm];

    if (equivalences && equivalences.length) {
        for (const syn of equivalences) {
            const liste = amvFiltrerParMot_Tableau(syn);
            resultat = resultat.concat(liste); 
        }
    }
    
    return resultat;
}

// -------------------------
// Affichage résultats
// -------------------------
function amvAfficherImages_Tableau(liste) {
    const zone = document.getElementById("resultats");
    const msg = document.getElementById("messages");
    if (!zone || !msg) return;

    zone.innerHTML = "";
    msg.innerHTML = "";

    if (!liste.length) {
        msg.textContent = "Aucune image trouvée.";
        return;
    }

    msg.textContent = `${liste.length} image${liste.length > 1 ? "s" : ""} trouvée${liste.length > 1 ? "s" : ""}.`;

    for (const img of liste) {
        const bloc = document.createElement("div");
        bloc.style.textAlign = "center";

        const lien = document.createElement("a");
        lien.href = img.URLPage;
        lien.target = "_blank";

        const image = document.createElement("img");
        image.src = img.URLImage;
        image.alt = img.Légende || "";
        image.loading = "lazy";
        image.style.maxWidth = "100%";
        image.style.borderRadius = "6px";
        image.style.boxShadow = "0 0 4px rgba(0,0,0,0.2)";

        lien.appendChild(image);

        const legende = document.createElement("div");
        legende.textContent = img.Légende || "";
        Object.assign(legende.style, {
            fontFamily: "Inter, sans-serif",
            fontWeight: "300",
            fontSize: "14px",
            lineHeight: "20px",
            color: "rgb(85,85,85)",
            marginTop: "8px"
        });

        bloc.appendChild(lien);
        bloc.appendChild(legende);
        zone.appendChild(bloc);
    }
}

function amvImageHasard_Tableau() {
    if (!amvImages.length) return;
    const i = Math.floor(Math.random() * amvImages.length);
    amvAfficherImages_Tableau([amvImages[i]]);
}

// -------------------------
// Autocomplétion — VERSION CORRIGÉE
// Champ 1 : tous les mots fréquents
// Champ 2 : uniquement les mots co-occurrents avec mot1
// -------------------------
function amvActiverAutocompletion_Tableau() {
    if (!amvMotsFrequents.length) return;

    const input1 = document.getElementById("motcle1");
    const box1   = document.getElementById("sug1");
    const input2 = document.getElementById("motcle2");
    const box2   = document.getElementById("sug2");

    // ── Fonction commune d'affichage d'une boîte de suggestions ───────────
    function afficherBox(box, input, liste) {
        if (!liste || !liste.length) {
            box.style.display = "none";
            box.innerHTML = "";
            return;
        }
        let html = "";
        for (const mot of liste) {
            html += `<div data-mot="${mot.replace(/"/g, "&quot;")}"
                style="padding:6px 10px;cursor:pointer;border-bottom:1px solid #eee;background:#fff;"
                onmouseover="this.style.backgroundColor='#f0f0f0'"
                onmouseout="this.style.backgroundColor='#fff'">${mot}</div>`;
        }
        box.innerHTML = html;
        box.style.display = "block";
        box.querySelectorAll("div[data-mot]").forEach(div => {
            div.addEventListener("mousedown", e => {
                e.preventDefault();
                input.value = div.getAttribute("data-mot");
                box.style.display = "none";
                input.focus();
            });
        });
    }

    // ── Champ 1 : tous les mots fréquents ─────────────────────────────────
    function rendreSug1() {
        const val = (input1.value || "").trim();
        if (!val) { box1.style.display = "none"; box1.innerHTML = ""; return; }
        const v = amvNormaliser(val);
        const liste = amvMotsFrequents
            .filter(m => amvNormaliser(m).startsWith(v))
            .slice(0, 14);
        afficherBox(box1, input1, liste);
    }

    // ── Champ 2 : mots co-occurrents avec mot1 uniquement ─────────────────
    function rendreSug2() {
        const val  = (input2.value || "").trim();
        if (!val) { box2.style.display = "none"; box2.innerHTML = ""; return; }
        const v    = amvNormaliser(val);
        const mot1 = amvNormaliser((input1.value || "").trim());

        let candidats = [];

        if (mot1) {
            // Stratégie 1 : proches.json contient les voisins de mot1
            if (amvProches[mot1] && amvProches[mot1].length) {
                candidats = amvProches[mot1]
                    .filter(m => amvNormaliser(m).startsWith(v))
                    .slice(0, 14);
            }

            // Stratégie 2 (fallback) : parcourir les images contenant mot1
            // et collecter leurs autres mots-clés
            if (!candidats.length) {
                const imagesMot1 = amvFiltrerParMot_Tableau(mot1);
                const compteur = {};
                for (const img of imagesMot1) {
                    const mots = (img.MotsClés || "").split(",").map(m => m.trim()).filter(m => m);
                    for (const m of mots) {
                        const n = amvNormaliser(m);
                        if (n === mot1 || !n) continue;
                        if (!compteur[n]) compteur[n] = { forme: m, count: 0 };
                        compteur[n].count++;
                    }
                }
                candidats = Object.values(compteur)
                    .filter(o => o.count >= 1 && amvNormaliser(o.forme).startsWith(v))
                    .sort((a, b) => b.count - a.count)
                    .slice(0, 14)
                    .map(o => o.forme);
            }
        } else {
            // Pas de mot1 : comportement identique au champ 1
            candidats = amvMotsFrequents
                .filter(m => amvNormaliser(m).startsWith(v))
                .slice(0, 14);
        }

        afficherBox(box2, input2, candidats);
    }

    // ── Événements champ 1 ─────────────────────────────────────────────────
    if (input1) {
        input1.addEventListener("input", rendreSug1);
        input1.addEventListener("focus", rendreSug1);
        input1.addEventListener("blur",  () => setTimeout(() => { box1.style.display = "none"; }, 200));
        // Quand mot1 change, vider mot2 et ses suggestions
        input1.addEventListener("input", () => {
            if (input2) input2.value = "";
            if (box2) { box2.style.display = "none"; box2.innerHTML = ""; }
        });
    }

    // ── Événements champ 2 ─────────────────────────────────────────────────
    if (input2) {
        input2.addEventListener("input", rendreSug2);
        input2.addEventListener("focus", rendreSug2);
        input2.addEventListener("blur",  () => setTimeout(() => { box2.style.display = "none"; }, 200));
    }
}

// -------------------------
// Initialisation
// -------------------------
(function amvInitTableau() {
    const btnRechercher = document.getElementById("btnRechercher");
    const btnHasard = document.getElementById("btnHasard");

    if (btnRechercher) {
        btnRechercher.addEventListener("click", () => {
            const mot1 = (document.getElementById("motcle1") || {}).value || "";
            const mot2 = (document.getElementById("motcle2") || {}).value || "";
            const res = amvChercherAvecProches_Tableau(mot1, mot2);
            amvAfficherImages_Tableau(res);
        });
    }

    if (btnHasard) {
        btnHasard.addEventListener("click", () => amvImageHasard_Tableau());
    }

    [document.getElementById("motcle1"), document.getElementById("motcle2")].forEach(el => {
        if (el) el.addEventListener("keypress", (e) => {
            if (e.key === "Enter") {
                e.preventDefault();
                if (btnRechercher) btnRechercher.click();
            }
        });
    });

    amvChargerImagesEtProches_Tableau();
})();
