(function (window, document, polylangConfig) {
    const Polylang = function (options) {
        this.options = {
            actionUrl: '/assets/components/polylang/action.php',
            trigger: 'polylang-toggle',
        };
        this.options = Object.assign(this.options, options || {});
        this.setup();
    };

    Polylang.prototype.setup = function () {
        this.bindEvents();
    };

    Polylang.prototype.bindEvents = function () {
        document.addEventListener('click', (e) => {
            const target = e.target.closest('.' + this.options.trigger);
            if (target) {
                e.preventDefault();
                this.toggleLanguage(target.getAttribute('href'), target.dataset.id);
            }
        });
    };

    Polylang.prototype.toggleLanguage = function (url, id) {
        if (!url) return;

        fetch(this.options.actionUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                id: id,
                action: 'language/toggle',
            }),
            cache: 'no-cache',
        })
            .then(response => {
                return response.json();
            })
            .then((response) => {
                if (response.success) {
                    window.location.href = url;
                } else if (response.message) {
                    console.error(response.message);
                }
            })
            .catch(error => {
                console.error('Error toggling language:', error);
            });
    };

    document.addEventListener('DOMContentLoaded', function () {
        const polylang = new Polylang(polylangConfig || {});
    });
})(window, document, polylangConfig);
