<?php
// Default namespace yang akan di-load (bisa di-override sebelum include)
$active_namespaces = isset($active_namespaces) ? $active_namespaces : ['login', 'dashboard'];
$default_namespace = $active_namespaces[0]; // defaultNS hanya satu, ambil pertama
?>
<script src="https://unpkg.com/i18next@21.6.16/dist/umd/i18next.min.js"></script>
<script src="https://unpkg.com/i18next-browser-languagedetector/i18nextBrowserLanguageDetector.min.js"></script>
<script src="https://unpkg.com/jquery-i18next@1.2.1/dist/umd/jquery-i18next.min.js"></script>

<script>
    let currentLangCode = localStorage.getItem('lang') || 'id';
    window.onI18nReadyCallbacks = [];
    window.onLanguageChangeCallbacks = [];

    function updateFlagAndName(langCode) {
        let langNameText, flagSrc;
        switch (langCode) {
            case 'id':
                langNameText = 'Indonesia';
                flagSrc = 'assets/media/flags/indonesia.svg';
                break;
            default:
                langNameText = 'English';
                flagSrc = 'assets/media/flags/united-states.svg';
        }

        const langNameEl = document.querySelector('[data-kt-element="current-lang-name"]');
        const langFlagEl = document.querySelector('[data-kt-element="current-lang-flag"]');
        if (langNameEl) langNameEl.textContent = langNameText;
        if (langFlagEl) langFlagEl.src = flagSrc;
        console.log('Flag dan nama bahasa disetel:', langNameText, flagSrc);

    }

    function updateHeader() {
        const elementMap = {
            h_myprofile: "h_myprofile", 
            btn_sign_out: "btn_sign_out",
            h_daftar_menu: "h_daftar_menu",
            h_dashboard: "h_dashboard"
        };

        Object.entries(elementMap).forEach(([dataAttr, i18nKey]) => {
            const el = document.querySelector(`[data-header-element="${dataAttr}"]`);
            if (el) {
                el.textContent = i18next.t("header:" + i18nKey);
            } else {
                console.warn(`[Header] Element "${dataAttr}" tidak ditemukan di DOM`);
            }
        });
    }

    updateFlagAndName(currentLangCode);

    window.i18nReady = new Promise((resolve, reject) => {
        const namespaces = <?php echo json_encode($active_namespaces); ?>;
        const defaultNS = "<?php echo $default_namespace; ?>";

        i18next
            .use(i18nextBrowserLanguageDetector)
            .use({
                type: 'backend',
                read: function (language, namespace, callback) {
                    const url = `locales/${language}/${namespace}.json`;
                  //  console.log('Mencoba memuat file:', url);

                    fetch(url)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`HTTP ${response.status} saat load ${url}`);
                            }
                            return response.json();
                        })
                        .then(data => {
                       //     console.log(`✅ Berhasil load file ${url}`);
                            callback(null, data);
                        })
                        .catch(error => {
                          //  console.error(`❌ Gagal memuat file ${url}:`, error);
                            callback(error, null);
                        });
                }
            })
            .init({
                fallbackLng: 'en',
                debug: true,
                lng: currentLangCode,
                ns: namespaces,
                defaultNS: defaultNS
            }, function (err, t) {
                if (err) {
                    console.error('Gagal inisialisasi i18next:', err);
                    reject(err);
                } else {
                    console.log('✅ i18next siap dengan namespace:', namespaces.join(', '));

                    window.onLanguageChangeCallbacks = window.onLanguageChangeCallbacks || [];

                    jqueryI18next.init(i18next, $, { useOptionsAttr: true });
                    $('body').localize();
                    $('body').removeClass('d-none');

                    // Callback jika ada fungsi onI18nReady
                    /*if (typeof window.onI18nReady === "function") {
                        console.log('Panggil window.onI18nReady()');
                        window.onI18nReady();
                    }*/

                    setTimeout(() => {
                        if (Array.isArray(window.onI18nReadyCallbacks)) {
                            for (const cb of window.onI18nReadyCallbacks) {
                                try { cb(); } catch (e) { console.error(e); }
                            }
                        }
                    }, 100);

                    resolve(); // Tandai i18n selesai
                }
            });

        // Listener ganti bahasa
        const langButtonEls = document.querySelectorAll('[data-kt-lang]');
        langButtonEls.forEach(el => {
            el.addEventListener('click', async function (e) {
                e.preventDefault();
                const langText = this.getAttribute('data-kt-lang');
                const langCode = langText === 'Indonesia' ? 'id' : langText === 'Japanese' ? 'jp' : 'en';

                if (langCode === currentLangCode) {
                    console.log('Bahasa sama, tidak ada perubahan');
                    return;
                }

                localStorage.setItem('lang', langCode);

                i18next.changeLanguage(langCode, async (err, t) => {
                    if (err) {
                        console.error('Gagal ganti bahasa:', err);
                        return;
                    }

                    currentLangCode = langCode;
                    $('body').localize();
                    updateFlagAndName(langCode);
                    console.log('✅ Konten dilokalkan ulang');

                    // Jalankan semua callback language change
                    setTimeout(() => {
                        if (Array.isArray(window.onI18nReadyCallbacks)) {
                            for (const cb of window.onI18nReadyCallbacks) {
                                try { cb(); } catch (e) { console.error(e); }
                            }
                        }
                    }, 100);
                });
            });
        });



    });
</script>