// Dictionary Widget JavaScript
class DictionaryWidget {
    constructor() {
        this.isOpen = false;
        this.currentLang = 'en';
        this.uiLang = this.getUILang();
        this.uiStrings = {
            tr: {
                searchPlaceholder: 'Kelime arayın...',
                searchButton: 'Ara',
                popularTitle: 'Popüler Kelimeler',
                noResult: 'Kelime bulunamadı',
                source: 'Kaynak'
            },
            en: {
                searchPlaceholder: 'Search a word...',
                searchButton: 'Search',
                popularTitle: 'Popular Words',
                noResult: 'No results found',
                source: 'Source'
            },
            de: {
                searchPlaceholder: 'Wort suchen...',
                searchButton: 'Suchen',
                popularTitle: 'Beliebte Wörter',
                noResult: 'Keine Ergebnisse gefunden',
                source: 'Quelle'
            },
            es: {
                searchPlaceholder: 'Buscar una palabra...',
                searchButton: 'Buscar',
                popularTitle: 'Palabras Populares',
                noResult: 'No se encontraron resultados',
                source: 'Fuente'
            },
            fr: {
                searchPlaceholder: 'Rechercher un mot...',
                searchButton: 'Rechercher',
                popularTitle: 'Mots Populaires',
                noResult: 'Aucun résultat trouvé',
                source: 'Source'
            },
            ru: {
                searchPlaceholder: 'Найдите слово...',
                searchButton: 'Искать',
                popularTitle: 'Популярные слова',
                noResult: 'Ничего не найдено',
                source: 'Источник'
            }
        };
        // Minimal bilingual pairs for 5 languages; extend as needed
        this.dictionary = {
            en: {
                "hello": {
                    word: "hello",
                    phonetic: "/həˈloʊ/",
                    meanings: [
                        {
                            partOfSpeech: "noun",
                            definition: "Bir selamlama sözü",
                            examples: ["Hello, how are you?", "She said hello to everyone."]
                        },
                        {
                            partOfSpeech: "interjection",
                            definition: "Selam vermek için kullanılan ünlem",
                            examples: ["Hello! Nice to meet you."]
                        }
                    ]
                },
                "computer": {
                    word: "computer",
                    phonetic: "/kəmˈpjuːtər/",
                    meanings: [
                        {
                            partOfSpeech: "noun",
                            definition: "Elektronik hesaplama ve veri işleme makinesi",
                            examples: ["I use my computer for work.", "The computer is very fast."]
                        }
                    ]
                },
                "beautiful": {
                    word: "beautiful",
                    phonetic: "/ˈbjuːtɪfʊl/",
                    meanings: [
                        {
                            partOfSpeech: "adjective",
                            definition: "Güzel, hoş görünümlü",
                            examples: ["She is beautiful.", "What a beautiful day!"]
                        }
                    ]
                },
                "learn": {
                    word: "learn",
                    phonetic: "/lɜːrn/",
                    meanings: [
                        {
                            partOfSpeech: "verb",
                            definition: "Öğrenmek, bilgi edinmek",
                            examples: ["I want to learn English.", "She learned to play piano."]
                        }
                    ]
                },
                "friend": {
                    word: "friend",
                    phonetic: "/frend/",
                    meanings: [
                        {
                            partOfSpeech: "noun",
                            definition: "Arkadaş, dost",
                            examples: ["He is my best friend.", "We are good friends."]
                        }
                    ]
                },
                "language": {
                    word: "language",
                    phonetic: "/ˈlæŋɡwɪdʒ/",
                    meanings: [
                        {
                            partOfSpeech: "noun",
                            definition: "İnsanların iletişim kurduğu sözlü veya yazılı sistem",
                            examples: ["English is a global language.", "She speaks three languages."]
                        }
                    ]
                }
            },
            fr: {
                "bonjour": {
                    word: "bonjour",
                    phonetic: "/bɔ̃.ʒuʁ/",
                    meanings: [
                        { partOfSpeech: "interjection", definition: "Salutation, formule de politesse", examples: ["Bonjour, comment ça va ?"] }
                    ]
                },
                "ordinateur": {
                    word: "ordinateur",
                    phonetic: "/ɔʁ.di.na.tœʁ/",
                    meanings: [
                        { partOfSpeech: "nom", definition: "Machine électronique de traitement de l'information", examples: ["J'utilise mon ordinateur pour travailler."] }
                    ]
                },
                "beau": {
                    word: "beau",
                    phonetic: "/bo/",
                    meanings: [
                        { partOfSpeech: "adjectif", definition: "Qui plaît à la vue, agréable", examples: ["Quel beau jour !"] }
                    ]
                },
                "apprendre": {
                    word: "apprendre",
                    phonetic: "/a.pʁɑ̃dʁ/",
                    meanings: [
                        { partOfSpeech: "verbe", definition: "Acquérir des connaissances", examples: ["Je veux apprendre le français."] }
                    ]
                }
            },
            tr: {
                "merhaba": {
                    word: "merhaba",
                    phonetic: "/merˈhaba/",
                    meanings: [
                        {
                            partOfSpeech: "ünlem",
                            definition: "Selam vermek için kullanılan söz",
                            examples: ["Merhaba, nasılsın?", "Merhaba arkadaşlar!"]
                        }
                    ]
                },
                "bilgisayar": {
                    word: "bilgisayar",
                    phonetic: "/bilɡiˈsaːjar/",
                    meanings: [
                        {
                            partOfSpeech: "isim",
                            definition: "Elektronik hesaplama ve veri işleme makinesi",
                            examples: ["Bilgisayarımı iş için kullanıyorum.", "Bu bilgisayar çok hızlı."]
                        }
                    ]
                },
                "güzel": {
                    word: "güzel",
                    phonetic: "/ɡyˈzel/",
                    meanings: [
                        {
                            partOfSpeech: "sıfat",
                            definition: "Hoş görünümlü, estetik",
                            examples: ["Çok güzel bir gün!", "Bu resim çok güzel."]
                        }
                    ]
                },
                "öğrenmek": {
                    word: "öğrenmek",
                    phonetic: "/œːɡrenˈmek/",
                    meanings: [
                        {
                            partOfSpeech: "fiil",
                            definition: "Bilgi edinmek, öğrenmek",
                            examples: ["İngilizce öğrenmek istiyorum.", "Yeni bir dil öğreniyor."]
                        }
                    ]
                },
                "arkadaş": {
                    word: "arkadaş",
                    phonetic: "/arˈkadaʃ/",
                    meanings: [
                        {
                            partOfSpeech: "isim",
                            definition: "Dost, yakın tanıdık",
                            examples: ["En iyi arkadaşım o.", "İyi arkadaşlarız."]
                        }
                    ]
                },
                "dil": {
                    word: "dil",
                    phonetic: "/dil/",
                    meanings: [
                        {
                            partOfSpeech: "isim",
                            definition: "İnsanların iletişim kurduğu sözlü veya yazılı sistem",
                            examples: ["Türkçe güzel bir dil.", "Üç dil biliyor."]
                        }
                    ]
                }
            },
            de: {
                "hallo": {
                    word: "hallo",
                    phonetic: "/haˈloː/",
                    meanings: [
                        {
                            partOfSpeech: "Interjektion",
                            definition: "Selam vermek için kullanılan söz",
                            examples: ["Hallo, wie geht es dir?", "Hallo Freunde!"]
                        }
                    ]
                },
                "computer": {
                    word: "computer",
                    phonetic: "/kɔmˈpjuːtɐ/",
                    meanings: [
                        {
                            partOfSpeech: "Substantiv",
                            definition: "Elektronische Rechenmaschine",
                            examples: ["Ich benutze meinen Computer für die Arbeit.", "Der Computer ist sehr schnell."]
                        }
                    ]
                },
                "schön": {
                    word: "schön",
                    phonetic: "/ʃøːn/",
                    meanings: [
                        {
                            partOfSpeech: "Adjektiv",
                            definition: "Schön, ansprechend",
                            examples: ["Das ist ein schöner Tag!", "Sie ist sehr schön."]
                        }
                    ]
                },
                "lernen": {
                    word: "lernen",
                    phonetic: "/ˈlɛrnən/",
                    meanings: [
                        {
                            partOfSpeech: "Verb",
                            definition: "Lernen, sich Wissen aneignen",
                            examples: ["Ich möchte Deutsch lernen.", "Sie lernt Klavier spielen."]
                        }
                    ]
                },
                "freund": {
                    word: "freund",
                    phonetic: "/fʁɔɪnt/",
                    meanings: [
                        {
                            partOfSpeech: "Substantiv",
                            definition: "Freund, Bekannter",
                            examples: ["Er ist mein bester Freund.", "Wir sind gute Freunde."]
                        }
                    ]
                },
                "sprache": {
                    word: "sprache",
                    phonetic: "/ˈʃpʁaːxə/",
                    meanings: [
                        {
                            partOfSpeech: "Substantiv",
                            definition: "Menschliches Kommunikationssystem",
                            examples: ["Deutsch ist eine schöne Sprache.", "Sie spricht drei Sprachen."]
                        }
                    ]
                }
            },
            es: {
                "hola": {
                    word: "hola",
                    phonetic: "/ˈola/",
                    meanings: [
                        {
                            partOfSpeech: "interjección",
                            definition: "Saludo informal",
                            examples: ["¡Hola! ¿Cómo estás?", "Hola amigos!"]
                        }
                    ]
                },
                "computadora": {
                    word: "computadora",
                    phonetic: "/komputaˈðoɾa/",
                    meanings: [
                        {
                            partOfSpeech: "sustantivo",
                            definition: "Máquina electrónica para procesar datos",
                            examples: ["Uso mi computadora para trabajar.", "La computadora es muy rápida."]
                        }
                    ]
                },
                "hermoso": {
                    word: "hermoso",
                    phonetic: "/eɾˈmoso/",
                    meanings: [
                        {
                            partOfSpeech: "adjetivo",
                            definition: "Bello, atractivo",
                            examples: ["¡Qué día tan hermoso!", "Ella es muy hermosa."]
                        }
                    ]
                },
                "aprender": {
                    word: "aprender",
                    phonetic: "/apɾenˈdeɾ/",
                    meanings: [
                        {
                            partOfSpeech: "verbo",
                            definition: "Adquirir conocimientos",
                            examples: ["Quiero aprender español.", "Ella aprende a tocar piano."]
                        }
                    ]
                },
                "amigo": {
                    word: "amigo",
                    phonetic: "/aˈmiɣo/",
                    meanings: [
                        {
                            partOfSpeech: "sustantivo",
                            definition: "Persona con quien se tiene amistad",
                            examples: ["Él es mi mejor amigo.", "Somos buenos amigos."]
                        }
                    ]
                },
                "idioma": {
                    word: "idioma",
                    phonetic: "/iˈðjoma/",
                    meanings: [
                        {
                            partOfSpeech: "sustantivo",
                            definition: "Sistema de comunicación humana",
                            examples: ["El español es un idioma hermoso.", "Habla tres idiomas."]
                        }
                    ]
                }
            },
            ru: {
                "привет": {
                    word: "привет",
                    phonetic: "/prʲɪˈvʲet/",
                    meanings: [
                        {
                            partOfSpeech: "междометие",
                            definition: "Приветствие, привет",
                            examples: ["Привет! Как дела?", "Привет, друзья!"]
                        }
                    ]
                },
                "компьютер": {
                    word: "компьютер",
                    phonetic: "/kɐmˈpʲutɨr/",
                    meanings: [
                        {
                            partOfSpeech: "существительное",
                            definition: "Электронно-вычислительная машина",
                            examples: ["Я использую компьютер для работы.", "Этот компьютер очень быстрый."]
                        }
                    ]
                },
                "красивый": {
                    word: "красивый",
                    phonetic: "/krɐˈsʲivɨj/",
                    meanings: [
                        {
                            partOfSpeech: "прилагательное",
                            definition: "Красивый, привлекательный",
                            examples: ["Какой красивый день!", "Она очень красивая."]
                        }
                    ]
                },
                "учиться": {
                    word: "учиться",
                    phonetic: "/ʊˈtɕitsə/",
                    meanings: [
                        {
                            partOfSpeech: "глагол",
                            definition: "Получать знания, учиться",
                            examples: ["Я хочу учиться английскому.", "Она учится играть на пианино."]
                        }
                    ]
                },
                "друг": {
                    word: "друг",
                    phonetic: "/druk/",
                    meanings: [
                        {
                            partOfSpeech: "существительное",
                            definition: "Друг, товарищ",
                            examples: ["Он мой лучший друг.", "Мы хорошие друзья."]
                        }
                    ]
                },
                "язык": {
                    word: "язык",
                    phonetic: "/jɪˈzɨk/",
                    meanings: [
                        {
                            partOfSpeech: "существительное",
                            definition: "Система общения людей",
                            examples: ["Русский - красивый язык.", "Она говорит на трех языках."]
                        }
                    ]
                }
            }
        };

        // Auto-select widget language based on site selection if available
        try {
            const savedLang = (localStorage.getItem('liguana-language') || '').toLowerCase();
            const map = { english: 'en', turkish: 'tr', german: 'de', spanish: 'es', russian: 'ru', french: 'fr' };
            if (map[savedLang]) this.currentLang = map[savedLang];
        } catch (e) {}
        
        this.init();
    }

    getUILang() {
        try {
            const sel = document.querySelector('#site-language') || document.querySelector('#site-language-desktop');
            const v = sel && sel.value ? sel.value.toLowerCase() : null;
            return v || 'tr';
        } catch (_) { return 'tr'; }
    }

    tUI(key) {
        const dict = this.uiStrings[this.uiLang] || this.uiStrings.en;
        return dict[key] || key;
    }

    init() {
        this.createWidget();
        this.bindEvents();
        this.loadPopularWords();
    }

    createWidget() {
        const widgetHTML = `
            <div class="dictionary-widget" id="dictionaryWidget">
                <div class="dictionary-widget-content" id="dictionaryContent">
                    <div class="dictionary-widget-search">
                        <input type="text" class="dictionary-widget-input" id="dictionaryInput" placeholder="${this.tUI('searchPlaceholder')}">
                        <button class="dictionary-widget-search-btn" id="dictionarySearchBtn" aria-label="${this.tUI('searchButton')}">${this.tUI('searchButton')}</button>
                        <div class="dictionary-widget-langs">
                            <button class="dictionary-widget-lang active" data-lang="en">EN</button>
                            <button class="dictionary-widget-lang" data-lang="tr">TR</button>
                            <button class="dictionary-widget-lang" data-lang="de">DE</button>
                            <button class="dictionary-widget-lang" data-lang="es">ES</button>
                            <button class="dictionary-widget-lang" data-lang="fr">FR</button>
                            <button class="dictionary-widget-lang" data-lang="ru">RU</button>
                        </div>
                    </div>
                    <div id="dictionaryResult"></div>
                    <div class="dictionary-widget-popular" id="dictionaryPopular">
                        <div class="dictionary-widget-popular-title" id="dictionaryPopularTitle">${this.tUI('popularTitle')}</div>
                        <div class="dictionary-widget-popular-grid" id="dictionaryPopularGrid"></div>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', widgetHTML);
    }

    bindEvents() {
        const toggle = document.getElementById('dictionaryToggle');
        const input = document.getElementById('dictionaryInput');
        const searchBtn = document.getElementById('dictionarySearchBtn');
        const langBtns = document.querySelectorAll('.dictionary-widget-lang');
        const siteLangSel = document.querySelector('#site-language');
        const siteLangSelDesk = document.querySelector('#site-language-desktop');

        // Toggle widget from chat input button
        if (toggle) {
            toggle.addEventListener('click', () => {
                this.toggleWidget();
            });
            
            // Keyboard navigation support
            toggle.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    this.toggleWidget();
                }
            });
        }

        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.searchWord(e.target.value);
            }
        });

        if (searchBtn) {
            searchBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                this.searchWord(input.value);
            });
        }

        // Language selection
        langBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                langBtns.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                this.currentLang = btn.dataset.lang;
                this.loadPopularWords();
                this.clearResult();
            });
        });

        const updateUIText = () => {
            this.uiLang = this.getUILang();
            const inputEl = document.getElementById('dictionaryInput');
            const btnEl = document.getElementById('dictionarySearchBtn');
            const titleEl = document.getElementById('dictionaryPopularTitle');
            if (inputEl) inputEl.placeholder = this.tUI('searchPlaceholder');
            if (btnEl) { btnEl.textContent = this.tUI('searchButton'); btnEl.setAttribute('aria-label', this.tUI('searchButton')); }
            if (titleEl) titleEl.textContent = this.tUI('popularTitle');
        };
        if (siteLangSel) siteLangSel.addEventListener('change', updateUIText);
        if (siteLangSelDesk) siteLangSelDesk.addEventListener('change', updateUIText);
    }

    toggleWidget() {
        const widget = document.getElementById('dictionaryWidget');
        const toggle = document.getElementById('dictionaryToggle');
        
        this.isOpen = !this.isOpen;
        
        if (this.isOpen) {
            widget.classList.add('open');
            if (widget) widget.setAttribute('aria-expanded', 'true');
            if (toggle) toggle.textContent = '▲';
        } else {
            widget.classList.remove('open');
            if (widget) widget.setAttribute('aria-expanded', 'false');
            if (toggle) toggle.textContent = '📚';
        }
    }

    async fetchFromWiktionary(word, langCode) {
        const langToSubdomain = { en: 'en', de: 'de', es: 'es', fr: 'fr', ru: 'ru', tr: 'tr' };
        const sub = langToSubdomain[langCode] || 'en';
        const language = { en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', ru: 'Русский', tr: 'Türkçe' };
        const languageName = langNameMap[langCode] || langCode;
        const url = `https://freedictionaryapi.com/api/v1/entries/${languageName}/${word}`;
        try {
            const resp = await fetch(url, { headers: { 'accept': 'application/json' } });
            if (!resp.ok) return null;
            const data = await resp.json();
            const entries = data[languageName];
            if (!entries || !Array.isArray(entries)) return null;

            const meanings = [];
            let phonetic = '';
            for (const entry of entries) {
                const pos = entry.partOfSpeech || entry.partOfSpeechText || '';
                const defs = entry.definitions || [];
                for (const d of defs) {
                    const definitionText = d.definition || d.sense || d.text;
                    if (!definitionText) continue;
                    const exampleList = [];
                    const exs = d.examples || [];
                    for (const ex of exs) {
                        if (typeof ex === 'string') exampleList.push(ex);
                        else if (ex && typeof ex === 'object') {
                            const t = ex.example || ex.text;
                            if (t) exampleList.push(t);
                        }
                    }
                    meanings.push({
                        partOfSpeech: pos || '',
                        definition: definitionText,
                        examples: exampleList.slice(0, 1)
                    });
                }
                const ipa = entry.pronunciations || entry.ipa;
                if (!phonetic && ipa) {
                    if (typeof ipa === 'string') phonetic = ipa;
                    else if (Array.isArray(ipa) && ipa.length) {
                        const first = ipa[0];
                        if (typeof first === 'string') phonetic = first;
                        else if (first && typeof first === 'object') phonetic = first.ipa || first.text || '';
                    }
                }
            }

            if (!meanings.length) return null;
            return {
                word,
                phonetic,
                meanings: meanings.slice(0, 10),
                sourceUrl: `https://${sub}.wiktionary.org/wiki/${encodeURIComponent(word)}`,
                sourceLabel: 'Wiktionary'
            };
        } catch (_) {
            return null;
        }
    }

    async fetchFromWiktionaryExtract(word, langCode) {
        const langToSubdomain = { en: 'en', de: 'de', es: 'es', fr: 'fr', ru: 'ru', tr: 'tr' };
        const sub = langToSubdomain[langCode] || 'en';
        const url = `https://${sub}.wiktionary.org/w/api.php?action=query&prop=extracts&titles=${encodeURIComponent(word)}&format=json&explaintext=1&redirects=1&origin=*`;
        try {
            const resp = await fetch(url, { headers: { 'accept': 'application/json' } });
            if (!resp.ok) return null;
            const data = await resp.json();
            if (!data || !data.query || !data.query.pages) return null;
            const pages = data.query.pages;
            const firstKey = Object.keys(pages)[0];
            if (!firstKey || firstKey === '-1') return null;
            const page = pages[firstKey];
            const extract = (page && page.extract) ? String(page.extract) : '';
            if (!extract.trim()) return null;

            const lines = extract.split('\n').map(s => s.trim()).filter(Boolean);
            const candidates = [];
            for (const line of lines) {
                if (/^=+\s*.+\s*=+$/.test(line)) continue;
                if (/^(?:\d+[\).]|[-*•])\s+/.test(line)) { candidates.push(line.replace(/^(?:\d+[\).]|[-*•])\s+/, '')); continue; }
                if (line.length > 12) candidates.push(line);
                if (candidates.length >= 12) break;
            }

            if (!candidates.length) return null;
            const meanings = candidates.slice(0, 10).map(t => ({ partOfSpeech: '', definition: t, examples: [] }));
            return {
                word,
                phonetic: '',
                meanings,
                sourceUrl: `https://${sub}.wiktionary.org/wiki/${encodeURIComponent(word)}`,
                sourceLabel: 'Wiktionary'
            };
        } catch (_) {
            return null;
        }
    }

    async fetchFromFreeDictionary(word) {
        const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${encodeURIComponent(word)}`;
        try {
            const resp = await fetch(url);
            if (!resp.ok) return null;
            const data = await resp.json();
            if (!Array.isArray(data) || !data.length) return null;
            const entry = data[0];
            const phonetic = (entry.phonetics && entry.phonetics[0] && entry.phonetics[0].text) || '';
            const meanings = [];
            for (const m of (entry.meanings || [])) {
                const pos = m.partOfSpeech || '';
                for (const d of (m.definitions || [])) {
                    if (!d.definition) continue;
                    meanings.push({
                        partOfSpeech: pos,
                        definition: d.definition,
                        examples: d.example ? [d.example] : []
                    });
                }
            }
            if (!meanings.length) return null;
            return {
                word: entry.word || word,
                phonetic,
                meanings: meanings.slice(0, 10),
                sourceUrl: `https://api.dictionaryapi.dev/api/v2/entries/en/${encodeURIComponent(word)}`,
                sourceLabel: 'Free Dictionary'
            };
        } catch (_) {
            return null;
        }
    }

    async fetchFromTDK(word) {
        const url = `https://sozluk.gov.tr/gts?ara=${encodeURIComponent(word)}`;
        try {
            const resp = await fetch(url, { headers: { 'accept': 'application/json' } });
            if (!resp.ok) return null;
            const data = await resp.json();
            let entry = null;
            if (Array.isArray(data) && data.length) entry = data[0];
            else if (data && typeof data === 'object') entry = data;
            if (!entry) return null;

            const anlamlar = entry.anlamlarListe || [];
            if (!Array.isArray(anlamlar) || !anlamlar.length) return null;

            const meanings = [];
            for (const item of anlamlar) {
                const definitionText = item.anlam;
                if (!definitionText) continue;
                const examples = [];
                const exs = item.orneklerListe || [];
                for (const ex of exs) {
                    if (ex && typeof ex === 'object' && ex.ornek) examples.push(ex.ornek);
                }
                const posList = [];
                const ozs = item.ozelliklerListe || [];
                for (const oz of ozs) {
                    const val = oz.tam_adi || oz.kisa_adi || oz.tur;
                    if (val) posList.push(val);
                }
                meanings.push({
                    partOfSpeech: posList.join(', ') || '',
                    definition: definitionText,
                    examples: examples.slice(0, 1)
                });
            }

            if (!meanings.length) return null;
            return {
                word,
                phonetic: '',
                meanings: meanings.slice(0, 10),
                sourceUrl: `https://sozluk.gov.tr/gts?ara=${encodeURIComponent(word)}`,
                sourceLabel: 'TDK'
            };
        } catch (_) {
            return null;
        }
    }

    async fetchFromDWDSSnippet(word) {
        const url = `https://www.dwds.de/api/wb/snippet/?q=${encodeURIComponent(word)}`;
        try {
            const resp = await fetch(url, { headers: { 'accept': 'application/json' } });
            if (!resp.ok) return null;
            const data = await resp.json();
            if (Array.isArray(data) && data.length) {
                const first = data[0];
                return {
                    lemma: first.lemma || word,
                    url: first.url || '',
                    wortart: first.wortart || ''
                };
            }
            return null;
        } catch (_) {
            return null;
        }
    }

    collectGermanDefinitions(obj, found = []) {
        if (!obj) return found;
        if (Array.isArray(obj)) {
            for (const item of obj) this.collectGermanDefinitions(item, found);
            return found;
        }
        if (typeof obj === 'object') {
            // Common keys that might carry textual definitions
            const keys = ['definition', 'bedeutung', 'bedeutungen', 'gloss', 'erklaerung', 'Erklärung', 'Def', 'DefText'];
            for (const k of keys) {
                if (k in obj && typeof obj[k] === 'string') {
                    const txt = obj[k].trim();
                    if (txt) found.push(txt);
                }
            }
            for (const v of Object.values(obj)) this.collectGermanDefinitions(v, found);
        }
        return found;
    }

    async fetchFromDWDSDetail(dwdsUrl, lemma) {
        const candidates = [];
        if (dwdsUrl) {
            candidates.push(dwdsUrl.replace('/wb/', '/api/wb/'));
        }
        if (lemma) {
            candidates.push(`https://www.dwds.de/api/wb/${encodeURIComponent(lemma)}`);
        }
        for (const url of candidates) {
            try {
                const resp = await fetch(url, { headers: { 'accept': 'application/json' } });
                if (!resp.ok) continue;
                const contentType = (resp.headers.get('content-type') || '').toLowerCase();
                if (!contentType.includes('json')) continue;
                const data = await resp.json();

                const meaningsTexts = this.collectGermanDefinitions(data, []);
                const meanings = (meaningsTexts || []).slice(0, 10).map(t => ({ partOfSpeech: '', definition: t, examples: [] }));
                if (meanings.length) {
                    return {
                        word: lemma || '',
                        phonetic: '',
                        meanings
                    };
                }
            } catch (_) { /* try next candidate */ }
        }
        return null;
    }

    async searchWord(query) {
        if (!query.trim()) {
            this.clearResult();
            return;
        }

        const q = query.trim();
        let searchTerm = q;

        // Turkish → TDK first
        if (this.currentLang === 'tr') {
            const tdk = await this.fetchFromTDK(q);
            if (tdk) { this.displayResult(tdk); return; }
        }

        // English → Free Dictionary first, then Wiktionary
        if (this.currentLang === 'en') {
            const enApi = await this.fetchFromFreeDictionary(q);
            if (enApi) { this.displayResult(enApi); return; }
            const wikiEn = await this.fetchFromWiktionary(searchTerm, 'en');
            if (wikiEn) { this.displayResult(wikiEn); return; }
        }

        // German → DWDS primary, fallback Wiktionary extract
        if (this.currentLang === 'de') {
            const dwds = await this.fetchFromDWDSSnippet(q);
            const lemma = dwds && dwds.lemma ? dwds.lemma : q;
            const detail = await this.fetchFromDWDSDetail(dwds && dwds.url ? dwds.url : null, lemma);
            if (detail) {
                if (dwds && dwds.url) { detail.sourceUrl = dwds.url; detail.sourceLabel = 'DWDS'; }
                if (!detail.word) detail.word = lemma;
                this.displayResult(detail);
                return;
            }
            const wikiDe = await this.fetchFromWiktionaryExtract(searchTerm, 'de');
            if (wikiDe) { this.displayResult(wikiDe); return; }
        }

        // Spanish/Russian/French → Wiktionary extract primary, fallback REST
        if (['es','ru','fr'].includes(this.currentLang)) {
            const wikiExtract = await this.fetchFromWiktionaryExtract(searchTerm, this.currentLang);
            if (wikiExtract) { this.displayResult(wikiExtract); return; }
            const wikiRest = await this.fetchFromWiktionary(searchTerm, this.currentLang);
            if (wikiRest) { this.displayResult(wikiRest); return; }
        }

        // 4) Local mini dictionary fallback
        const langDict = this.dictionary[this.currentLang];
        const low = searchTerm.toLowerCase();
        let result = langDict[low];
        if (!result) {
            const dicts = this.dictionary;
            for (const lang of Object.keys(dicts)) {
                if (lang === this.currentLang) continue;
                if (dicts[lang][low]) {
                    const foreign = dicts[lang][low];
                    const translated = langDict[low] || foreign;
                    result = {
                        word: `${foreign.word} → ${translated.word || low}`,
                        phonetic: foreign.phonetic || '',
                        meanings: foreign.meanings || []
                    };
                    break;
                }
            }
        }

        if (result) {
            this.displayResult(result);
        } else this.displayNoResult();
    }

    displayResult(wordData) {
        const resultDiv = document.getElementById('dictionaryResult');
        const rawWord = (wordData && wordData.word) ? String(wordData.word) : '';
        const pronounceText = rawWord.includes('→') ? rawWord.split('→')[0].trim() : rawWord;
        
        resultDiv.innerHTML = `
            <div class="dictionary-widget-result">
                <div class="dictionary-widget-word"><span>${wordData.word}</span><button id="dictionarySpeakBtn" class="dictionary-widget-speak" title="Telaffuz" aria-label="Telaffuz" style="margin-left:8px; cursor:pointer;">🔊</button></div>
                <div class="dictionary-widget-phonetic">${wordData.phonetic}</div>
                ${wordData.sourceUrl ? `
                    <div class="dictionary-widget-source">
                        <a href="${wordData.sourceUrl}" target="_blank" rel="noopener">${this.tUI('source')}: ${wordData.sourceLabel || this.tUI('source')}</a>
                    </div>
                ` : ''}
                ${wordData.meanings.map(meaning => `
                    <div class="dictionary-widget-meaning">
                        <strong>${meaning.partOfSpeech}:</strong> ${meaning.definition}
                        ${meaning.examples.length > 0 ? `
                            <div class="dictionary-widget-example">"${meaning.examples[0]}"</div>
                        ` : ''}
                    </div>
                `).join('')}
            </div>
        `;
        const speakBtn = document.getElementById('dictionarySpeakBtn');
        if (speakBtn && pronounceText) {
            speakBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                if (window.ttsHelper && typeof window.ttsHelper.speak === 'function') {
                    window.ttsHelper.speak(pronounceText, this.currentLang);
                } else {
                    this.pronounce(pronounceText, this.currentLang);
                }
            });
        }
    }

    pronounce(text, languageCode) {
        try {
            if (window.ttsHelper && typeof window.ttsHelper.speak === 'function') {
                return window.ttsHelper.speak(text, (languageCode || this.currentLang || 'en'));
            }
            if (!text) return;
            if (!('speechSynthesis' in window)) return;
            try { window.speechSynthesis.cancel(); } catch (_) {}
            const utterance = new SpeechSynthesisUtterance(text);
            const mapLocale = { en: 'en-US', tr: 'tr-TR', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', ru: 'ru-RU' };
            const code = (languageCode || this.currentLang || 'en').toLowerCase();
            const desiredLocale = mapLocale[code] || 'en-US';
            utterance.lang = desiredLocale;
            // Minimal fallback without voice-picking to avoid collisions; let browser choose
            utterance.rate = 0.9;
            utterance.pitch = 1.0;
            utterance.volume = 1.0;
            setTimeout(() => { try { speechSynthesis.speak(utterance); } catch (_) {} }, 30);
        } catch (_) {}
    }

    displayNoResult() {
        const resultDiv = document.getElementById('dictionaryResult');
        resultDiv.innerHTML = `
            <div class="dictionary-widget-no-result">
                ${this.tUI('noResult')}
            </div>
        `;
    }

    clearResult() {
        const resultDiv = document.getElementById('dictionaryResult');
        resultDiv.innerHTML = '';
    }

    loadPopularWords() {
        const langDict = this.dictionary[this.currentLang];
        const words = Object.keys(langDict).slice(0, 4);
        const grid = document.getElementById('dictionaryPopularGrid');
        const titleEl = document.getElementById('dictionaryPopularTitle');
        if (titleEl) titleEl.textContent = this.tUI('popularTitle');
        
        grid.innerHTML = words.map(word => `
            <div class="dictionary-widget-popular-word" onclick="dictionaryWidget.searchPopularWord('${word}')">
                <div class="dictionary-widget-popular-text">${word}</div>
                <div class="dictionary-widget-popular-meaning">${langDict[word].meanings[0].definition}</div>
            </div>
        `).join('');
    }

    searchPopularWord(word) {
        const input = document.getElementById('dictionaryInput');
        input.value = word;
        this.searchWord(word);
    }
    
}

// Initialize dictionary widget when DOM is loaded
let dictionaryWidget;
document.addEventListener('DOMContentLoaded', () => {
    dictionaryWidget = new DictionaryWidget();
});
