// ============================================================
//  LIB AMAVERO — Fonctions partagées Tableau + Mosaïque
// ============================================================

// --- Normalisation (sans accents, lower case)
function amv_normaliser(texte) {
    return (texte || "")
        .toLowerCase()
        .normalize("NFD").replace(/[\u0300-\u036f]/g, "")
        .replace(/œ/g, "oe")
        .trim();
}

// --- Dictionnaire minimal accents (le reste est dans proches.json)
const amv_diccoAccents = {
    'beaute': 'beauté', 'coeur': 'cœur', 'lumiere': 'lumière',
    'memoire': 'mémoire', 'reve': 'rêve', 'mosaique': 'mosaïque'
};

function amv_avecAccents(mot) {
    const key = amv_normaliser(mot);
    return amv_diccoAccents[key] || mot;
}

// --- Chargement JSON (via cors.php obligatoirement)
async function amv_chargerJSON(url) {
    const txt = await fetch(url).then(r => r.text());
    return JSON.parse(txt);
}

// --- Chargement proches.json
let amv_proches = {};

async function amv_chargerProches(url) {
    try {
        amv_proches = await amv_chargerJSON(url);
        console.log("📘 proches.json chargé :", Object.keys(amv_proches).length, "entrées");
    } catch (e) {
        console.error("❌ Erreur proches.json :", e);
        amv_proches = {};
    }
}

// --- Tirage élargi : mots proches → liste de mots élargis
function amv_equivalents(mot) {
    const cle = amv_normaliser(mot);
    if (amv_proches[cle]) return amv_proches[cle];
    return [mot];
}

// --- Filtrer images par mots (logique ET)
function amv_filtrer(images, mot1, mot2) {
    const A = amv_normaliser(mot1);
    const B = amv_normaliser(mot2);

    return images.filter(img => {
        const mots = amv_normaliser(img.MotsClés || "");
        const ok1 = A ? mots.includes(A) : true;
        const ok2 = B ? mots.includes(B) : true;
        return ok1 && ok2;
    });
}

// --- Déduplication d’images (pour Mosaïque)
function amv_unique(images) {
    const seen = new Set();
    return images.filter(img => {
        if (seen.has(img.NomFichier)) return false;
        seen.add(img.NomFichier);
        return true;
    });
}

// --- Tirage aléatoire
function amv_shuffle(arr) {
    return arr.sort(() => Math.random() - 0.5);
}
