<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dictionnaire trilingue Zoto | معجم زوتو الثلاثي</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@400;500;700&display=swap');
        @import url('https://fonts.googleapis.com/css2?family=Noto+Kufi+Arabic:wght@400;700&display=swap');
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&display=swap');
        
        :root {
            --primary-color: #7c2d12;
            --primary-light: #b45309;
            --secondary-color: #047857;
            --background: #fffbf5;
            --card-bg: #ffffff;
            --text-primary: #1e293b;
            --text-secondary: #475569;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Noto Sans Arabic', 'Poppins', sans-serif;
            background: var(--background);
            margin: 0;
            padding: 0;
            direction: rtl;
            min-height: 100vh;
            color: var(--text-primary);
        }

        body.fr {
            direction: ltr;
            font-family: 'Poppins', 'Noto Sans Arabic', sans-serif;
        }

        header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: white;
            padding: 1.5rem;
            text-align: center;
            font-family: 'Noto Kufi Arabic', 'Poppins', serif;
            position: relative;
            overflow: hidden;
        }

        .header-content {
            position: relative;
            z-index: 2;
        }

        .header-title {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
        }

        .header-subtitle {
            font-size: 1rem;
            opacity: 0.9;
            font-weight: 500;
        }

        .header-pattern {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-image: 
                radial-gradient(circle at 20% 50%, rgba(255,255,255,0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 30%, rgba(255,255,255,0.08) 0%, transparent 50%);
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 1.5rem;
            position: relative;
        }

        .search-bar {
            text-align: center;
            margin: -2.5rem auto 1.5rem;
            position: sticky;
            top: 1rem;
            z-index: 1000;
            max-width: 600px;
        }

        .search-wrapper {
            position: relative;
            display: inline-block;
            width: 100%;
        }

        .search-bar input {
            width: 100%;
            padding: 1rem 1.5rem;
            border-radius: 15px;
            border: none;
            font-size: 1rem;
            background: var(--card-bg);
            color: var(--text-primary);
            box-shadow: 0 8px 20px rgba(0,0,0,0.1);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .search-bar input:focus {
            outline: none;
            box-shadow: 0 12px 25px rgba(124,45,18,0.15);
            transform: translateY(-2px);
        }

        .suggestions {
            background: var(--card-bg);
            max-width: 100%;
            margin: 0.5rem auto;
            border-radius: 15px;
            display: none;
            box-shadow: 0 12px 25px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .suggestions div {
            padding: 0.75rem 1.5rem;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 1rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .suggestions div:hover {
            background-color: rgba(124,45,18,0.05);
            padding-right: 2rem;
        }

        .word-card {
            background: var(--card-bg);
            margin-bottom: 1.5rem;
            padding: 1.5rem;
            border-radius: 15px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.05);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            border: 1px solid rgba(0,0,0,0.05);
        }

        .word-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.08);
        }

        .teny {
            color: var(--primary-color);
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.75rem;
            font-family: 'Noto Kufi Arabic', 'Poppins', serif;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .teny::before {
            content: '';
            display: block;
            width: 6px;
            height: 6px;
            background: var(--primary-color);
            border-radius: 50%;
        }

        .category {
            color: var(--secondary-color);
            font-style: italic;
            font-size: 1rem;
            margin-bottom: 1rem;
            opacity: 0.9;
            padding-right: 0.75rem;
            border-right: 2px solid var(--secondary-color);
        }

        .fr .category {
            padding-right: 0;
            padding-left: 0.75rem;
            border-right: none;
            border-left: 2px solid var(--secondary-color);
        }

        .dikany {
            margin-top: 1rem;
            line-height: 1.6;
            color: var(--text-secondary);
            font-size: 1rem;
            white-space: pre-line;
            padding: 0.75rem;
            background: rgba(0,0,0,0.02);
            border-radius: 12px;
        }

        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }
            
            .header-title {
                font-size: 1.75rem;
            }
            
            .header-subtitle {
                font-size: 0.9rem;
            }
            
            .word-card {
                padding: 1.25rem;
            }

            .search-bar {
                margin-top: -2rem;
                padding: 0 1rem;
            }

            .search-bar input {
                padding: 0.875rem 1.25rem;
            }

            .teny {
                font-size: 1.25rem;
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .word-card {
            animation: fadeIn 0.5s ease forwards;
        }

        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--background);
        }

        ::-webkit-scrollbar-thumb {
            background: var(--primary-color);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--primary-light);
        }
    </style>
</head>
<body>
    <script>
        // Detect browser language
        const userLang = navigator.language || navigator.userLanguage;
        if (userLang.startsWith('fr')) {
            document.body.classList.add('fr');
            document.documentElement.lang = 'fr';
        }
    </script>

    <header>
        <div class="header-pattern"></div>
        <div class="header-content">
            <h1 class="header-title" data-ar="معجم زوتو الثلاثي" data-fr="Dictionnaire trilingue Zoto">
                <script>
                    document.currentScript.parentElement.textContent = 
                        document.body.classList.contains('fr') ? 
                        "Dictionnaire trilingue Zoto" : "معجم زوتو الثلاثي";
                </script>
            </h1>
            <p class="header-subtitle" data-ar="يمكنك البحث عن كلمات بالعربية أو المالغاشية أو الفرنسية" data-fr="Vous pouvez y rechercher des mots en arabe, malgache ou français">
                <script>
                    document.currentScript.parentElement.textContent = 
                        document.body.classList.contains('fr') ? 
                        "Vous pouvez y rechercher des mots en arabe, malgache ou français" : 
                        "يمكنك البحث عن كلمات بالعربية أو المالغاشية أو الفرنسية";
                </script>
            </p>
        </div>
    </header>
    <div class="container">
        <div class="search-bar">
            <div class="search-wrapper">
                <input type="text" id="search" placeholder="Rechercher un mot..." data-ar="ابحث عن كلمة..." oninput="searchWords()" autocomplete="off">
                <script>
                    const searchInput = document.getElementById('search');
                    searchInput.placeholder = document.body.classList.contains('fr') ? 
                        "Rechercher un mot..." : "ابحث عن كلمة...";
                </script>
            </div>
            <div class="suggestions" id="suggestions"></div>
        </div>
        <div id="dictionary"></div>
    </div>

<script>
let jsonData = {}; // Conteneur pour les données
let currentPage = 0; // Page actuelle pour le chargement
const PAGE_SIZE = 2000; // Nombre d'entrées à charger par lot
const SUGGESTION_LIMIT = 20; // Limite de suggestions

// Dictionnaire des symboles et leurs équivalents en arabe
const symbolMapping = {
    "[N1]": "/اسم موصوف/",
    "[N2]": "/صفة/",
    "[N3]": "/ظرف/",
    "[N4]": "/ضمير/",
    "[N5]": "/اسم الإشارة/",
    "[N6]": "/اسم الموصول/",
    "[N7]": "/كلمة مركبة/",
    "[N8]": "/اسم فعل/",
    "[N9]": "/علم/",
    "[V1]": "/فعل مجرد/",
    "[V2]": "/فعل مزيد/",
    "[V3]": "/فعل جامد/",
    "[P1]": "/حرف/",
    "[P2]": "/عبارة/",
    "[P3]": "/اسم استفهام/",
    "[P4]": "/عدد/",
    "[P5]": "/اسم شرط/",
    "[P6]": "/مصدر/",
    "[S7]": "/نعت ومنعوت/",
    "[D2]": "/مصطلح/"
};

// Fonction pour extraire les mots entre parenthèses dans "note1"
function extractWordsFromNote1(note1) {
    const regex = /\(([^)]+)\)/g;
    return [...note1.matchAll(regex)].map(match => match[1]);
}

// Fonction pour remplacer les symboles par leurs équivalents en arabe
function replaceSymbols(text) {
    let replacedText = text;
    for (const symbol in symbolMapping) {
        replacedText = replacedText.replace(symbol, symbolMapping[symbol]);
    }
    return replacedText;
}

// Fonction pour supprimer les mots entre parenthèses dans "note1"
function removeParenthesesWords(text) {
    return text.replace(/\([^)]+\)/g, '');
}

// Fonction pour supprimer les accents des caractères
function removeAccents(str) {
    return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}

// Fonction pour calculer la similarité entre deux mots sans tenir compte des accents
function similarity(str1, str2) {
    const len1 = str1.length;
    const len2 = str2.length;
    const maxLen = Math.max(len1, len2);

    let count = 0;
    const normalizedStr1 = removeAccents(str1.toLowerCase());
    const normalizedStr2 = removeAccents(str2.toLowerCase());

    for (let i = 0; i < Math.min(len1, len2); i++) {
        if (normalizedStr1[i] === normalizedStr2[i]) {
            count++;
        }
    }

    return count / maxLen; // Retourne la proportion de correspondance
}

// Fonction pour obtenir le drapeau du mot
function getFlag(word) {
    if (word.includes('#')) {
        return '🇫🇷'; // Drapeau pour les mots en français
    } else if (/[أ-ي]/.test(word)) {
        return '🇸🇦'; // Drapeau pour les mots en arabe
    }
    return '🇲🇬'; // Drapeau pour les mots en malgache
}

// Fonction pour afficher les mots associés à un mot
function displayMultipleEntries(keys) {
    const dictionaryDiv = document.getElementById('dictionary');
    dictionaryDiv.innerHTML = ''; // Réinitialiser l'affichage précédent

    keys.forEach(key => {
        const entry = jsonData[key];
        if (entry) {
            const wordCard = document.createElement('div');
            wordCard.className = 'word-card';

            // Clé "teny" (mot en grenat)
            const tenyElement = document.createElement('div');
            tenyElement.className = 'teny';
            tenyElement.textContent = entry.teny;
            wordCard.appendChild(tenyElement);

            // Clé "note1" (catégorie en vert sans les mots entre parenthèses)
            const categoryElement = document.createElement('div');
            categoryElement.className = 'category';
            categoryElement.textContent = removeParenthesesWords(replaceSymbols(entry.note1));
            wordCard.appendChild(categoryElement);

            // Clé "dikany" (définition)
            const dikanyElement = document.createElement('div');
            dikanyElement.className = 'dikany';
            dikanyElement.textContent = entry.dikany;
            wordCard.appendChild(dikanyElement);

            dictionaryDiv.appendChild(wordCard);
        }
    });
}

// Fonction pour afficher les suggestions triées par correspondance sans tenir compte des accents
function showSuggestions(input) {
    if (input.length <= 1) {
        suggestionsDiv.style.display = 'none';
        return;
    }

    const suggestions = [];
    const wordOccurrences = {}; // Objet pour stocker les occurrences de mots et leurs clés

    for (const key in jsonData) {
        if (suggestions.length >= SUGGESTION_LIMIT) break; // Limiter les suggestions

        const entry = jsonData[key];
        const note1Content = entry.note1;
        const words = extractWordsFromNote1(note1Content);

        words.forEach(word => {
            // Ne pas afficher les mots contenant ***
            if (word.includes('***')) return;

            const cleanedWord = word.replace(/#/g, '');

            if (removeAccents(cleanedWord).toLowerCase().includes(removeAccents(input).toLowerCase())) {
                if (!wordOccurrences[cleanedWord]) {
                    wordOccurrences[cleanedWord] = { word: cleanedWord, flag: getFlag(word), keys: [] };
                }
                wordOccurrences[cleanedWord].keys.push(key);
            }
        });
    }

    // Trier les mots par la similarité avec l'entrée de recherche
    for (const word in wordOccurrences) {
        suggestions.push(wordOccurrences[word]);
    }

    suggestions.sort((a, b) => {
        const similarityA = similarity(a.word, input);
        const similarityB = similarity(b.word, input);
        return similarityB - similarityA; // Trier de manière décroissante
    });

    const suggestionsDiv = document.getElementById('suggestions');
    if (suggestions.length > 0) {
        suggestionsDiv.innerHTML = '';
        suggestions.forEach(suggestion => {
            const suggestionDiv = document.createElement('div');
            suggestionDiv.innerHTML = `${suggestion.flag} ${suggestion.word}`;
            suggestionDiv.onclick = () => {
                // Afficher toutes les entrées du mot en cliquant sur la suggestion
                displayMultipleEntries(suggestion.keys);
                suggestionsDiv.style.display = 'none';
            };
            suggestionsDiv.appendChild(suggestionDiv);
        });
        suggestionsDiv.style.display = 'block';
    } else {
        suggestionsDiv.style.display = 'none';
    }
}

// Fonction de recherche
function searchWords() {
    const searchValue = document.getElementById('search').value.toLowerCase();

    if (searchValue.length > 1) {
        showSuggestions(searchValue);
    } else {
        suggestionsDiv.style.display = 'none';
        dictionaryDiv.innerHTML = ''; // Masquer les mots
    }
}

// Fonction pour charger le fichier JSON partiellement
async function loadDictionary(page) {
    try {
        const response = await fetch(`data2.json?page=${page}&size=${PAGE_SIZE}`);
        const data = await response.json();
        Object.assign(jsonData, data); // Ajouter les nouvelles données
    } catch (error) {
        console.error('Erreur lors du chargement du fichier JSON:', error);
    }
}

// Charger les données au démarrage avec un chargement progressif
window.onload = async function() {
    await loadDictionary(currentPage); // Charger la première page
    currentPage++; // Préparer la page suivante

    // Charger les données supplémentaires au défilement
    window.addEventListener('scroll', async () => {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
            await loadDictionary(currentPage);
            currentPage++;
        }
    });
};

</script>
</body>
</html>