(function () {
    window.ZaloroxI18n = {
        set: function (lang) {
            var apiBase = window.ZALOROX_API_BASE || '/api';
            return fetch(apiBase.replace(/\/$/, '') + '/language/set', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                credentials: 'same-origin',
                body: new URLSearchParams({ lang: lang })
            }).then(function (response) {
                return response.json().then(function (payload) {
                    if (!response.ok || !payload.ok) {
                        throw new Error(payload.message || 'Language could not be changed.');
                    }

                    return payload;
                });
            });
        }
    };

    document.querySelectorAll('[data-lang-form]').forEach(function (form) {
        form.addEventListener('change', function () {
            var field = form.querySelector('[name="lang"]');
            if (!field) return;
            window.ZaloroxI18n.set(field.value)
                .then(function () {
                    window.location.reload();
                })
                .catch(function (error) {
                    if (window.ZaloroxToast) window.ZaloroxToast.error(error.message);
                });
        });

        form.querySelectorAll('[data-lang-option]').forEach(function (button) {
            button.addEventListener('click', function () {
                var lang = button.dataset.langOption;
                var field = form.querySelector('[name="lang"]');
                if (!lang || !field || field.value === lang) return;

                field.value = lang;
                form.querySelectorAll('[data-lang-option]').forEach(function (item) {
                    var active = item === button;
                    item.classList.toggle('is-active', active);
                    item.setAttribute('aria-pressed', active ? 'true' : 'false');
                    item.disabled = true;
                });

                window.ZaloroxI18n.set(lang)
                    .then(function () {
                        if (window.ZaloroxToast) window.ZaloroxToast.success('Dil guncellendi.');
                        window.setTimeout(function () { window.location.reload(); }, 260);
                    })
                    .catch(function (error) {
                        form.querySelectorAll('[data-lang-option]').forEach(function (item) {
                            item.disabled = false;
                        });
                        if (window.ZaloroxToast) window.ZaloroxToast.error(error.message);
                    });
            });
        });
    });
})();
